Compare commits

...

9 Commits

Author SHA1 Message Date
fullstack-engineer 719c56d132 test(canvas): add FilesTab + tree pure-function coverage — 36 cases
qa-review / approved (pull_request) Failing after 18s
Secret scan / Scan diff for credential-shaped strings (pull_request) Successful in 34s
gate-check-v3 / gate-check (pull_request) Successful in 38s
sop-tier-check / tier-check (pull_request) Successful in 25s
security-review / approved (pull_request) Failing after 31s
CI / Detect changes (pull_request) Successful in 1m3s
sop-checklist-gate / gate (pull_request) Successful in 30s
CI / Shellcheck (E2E scripts) (pull_request) Successful in 23s
CI / Platform (Go) (pull_request) Failing after 4m2s
CI / Python Lint & Test (pull_request) Successful in 7m33s
CI / Canvas (Next.js) (pull_request) Successful in 12m53s
CI / Canvas Deploy Reminder (pull_request) Has been skipped
CI / all-required (pull_request) Successful in 7s
sop-checklist / all-items-acked (pull_request) [info tier:low] acked: 0/7 — missing: comprehensive-testing, local-postgres-e2e, staging-smoke, +4 — body-unfilled: comprehensive-testing, l
audit-force-merge / audit (pull_request) Has been skipped
Add tree.test.ts (25 cases): buildTree and getIcon pure functions from
FilesTab/tree.ts. buildTree: empty input, single file/dir, sorting,
nested files, intermediate dirs, duplicate dir prevention, deep nesting.
getIcon: all 9 extensions, case-insensitivity, default fallback.

Add FilesTab.test.tsx (11 cases): NotAvailablePanel rendering (external
runtime), api.get gating, loading/empty/file-count states, Refresh
button reload, upload guard (no error on /configs dragover).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-13 19:22:35 +00:00
fullstack-engineer c7350da23c Merge branch 'feat/canvas-tab-test-coverage-2' into staging 2026-05-13 18:28:31 +00:00
fullstack-engineer a2117ec8ac test(canvas): add ChannelsTab + TracesTab coverage — 34 cases
Secret scan / Scan diff for credential-shaped strings (pull_request) Successful in 16s
sop-tier-check / tier-check (pull_request) Successful in 18s
CI / Detect changes (pull_request) Successful in 59s
sop-checklist-gate / gate (pull_request) Successful in 24s
CI / Shellcheck (E2E scripts) (pull_request) Successful in 13s
CI / Python Lint & Test (pull_request) Successful in 17s
CI / Platform (Go) (pull_request) Failing after 5m49s
CI / Canvas (Next.js) (pull_request) Failing after 16m33s
CI / Canvas Deploy Reminder (pull_request) Has been skipped
sop-checklist / all-items-acked (pull_request) [info tier:low] acked: 0/7 — missing: comprehensive-testing, local-postgres-e2e, staging-smoke, +4 — body-unfilled: comprehensive-testing, l
CI / all-required (pull_request) Failing after 6s
audit-force-merge / audit (pull_request) Has been skipped
Add vitest unit tests for ChannelsTab (16 cases) and TracesTab (18 cases).
ChannelsTab: SUPPORTS_DETECT_CHATS, loading/empty/error states, channel
list rendering (enabled/disabled), toggle labels, message count, allowed
users, Test/Remove buttons, header and Connect form flow.
TracesTab: loading/empty/error states, trace list, expand/collapse,
aria-expanded attribute, latency formatting (ms/s), token usage, cost
display, Refresh button.
Fix error state assertions in ChannelsTab — component renders generic
"Failed to load connected channels/platforms" not raw error text.
Fix TracesTab cost test — use regex to handle locale variation in
toFixed(6).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-13 18:26:56 +00:00
devops-engineer a809201bad Merge pull request 'fix(handlers): add rows.Err() checks after all scan loops' (#865) from fix/handlers-rows-err-checks into staging
CI / all-required (push) Blocked by required conditions
Secret scan / Scan diff for credential-shaped strings (push) Successful in 25s
CI / Detect changes (push) Successful in 1m13s
CI / Platform (Go) (push) Has been cancelled
CI / Canvas (Next.js) (push) Has been cancelled
CI / Python Lint & Test (push) Has been cancelled
CI / Shellcheck (E2E scripts) (push) Has been cancelled
CI / Canvas Deploy Reminder (push) Has been cancelled
2026-05-13 18:15:39 +00:00
devops-engineer ab966c56ba Merge pull request 'test(canvas): add EventsTab and ScheduleTab test coverage' (#869) from feat/canvas-tab-test-coverage into staging
CI / Detect changes (push) Waiting to run
CI / Platform (Go) (push) Blocked by required conditions
CI / Canvas (Next.js) (push) Blocked by required conditions
CI / Shellcheck (E2E scripts) (push) Blocked by required conditions
CI / Canvas Deploy Reminder (push) Blocked by required conditions
CI / Python Lint & Test (push) Blocked by required conditions
CI / all-required (push) Blocked by required conditions
Secret scan / Scan diff for credential-shaped strings (push) Waiting to run
2026-05-13 18:14:21 +00:00
devops-engineer c8e312a195 Merge pull request 'fix(handlers/bundle): restore bundle import test build' (#861) from fix/issue-850-bundle-test-import into staging
CI / Detect changes (push) Waiting to run
CI / Platform (Go) (push) Blocked by required conditions
CI / Canvas (Next.js) (push) Blocked by required conditions
CI / Shellcheck (E2E scripts) (push) Blocked by required conditions
CI / Canvas Deploy Reminder (push) Blocked by required conditions
CI / Python Lint & Test (push) Blocked by required conditions
CI / all-required (push) Blocked by required conditions
Secret scan / Scan diff for credential-shaped strings (push) Waiting to run
2026-05-13 18:12:39 +00:00
fullstack-engineer d2041df571 test(canvas): add EventsTab and ScheduleTab test coverage
Secret scan / Scan diff for credential-shaped strings (pull_request) Successful in 18s
CI / Detect changes (pull_request) Successful in 45s
CI / Platform (Go) (pull_request) Successful in 10s
CI / Shellcheck (E2E scripts) (pull_request) Successful in 11s
CI / Python Lint & Test (pull_request) Successful in 10s
CI / Canvas (Next.js) (pull_request) Successful in 8m35s
CI / Canvas Deploy Reminder (pull_request) Has been skipped
CI / all-required (pull_request) Successful in 2s
sop-checklist-gate / gate (pull_request) Successful in 7s
sop-tier-check / tier-check (pull_request) Successful in 8s
sop-checklist / all-items-acked (pull_request) [info tier:low] acked: 7/7
audit-force-merge / audit (pull_request) Successful in 21s
EventsTab.test.tsx — formatTime (ago strings), EVENT_COLORS, loading/empty/error
states, event list rendering, expand/collapse, refresh button (12 cases).

ScheduleTab.test.tsx — cronToHuman (7 cases), relativeTime ("Last: never"),
empty state, schedule list rendering (11 cases).

Both files use the vi.hoisted() mock pattern for @/lib/api.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-13 16:37:44 +00:00
fullstack-engineer 73eb3c7a85 fix(handlers): add rows.Err() checks after all scan loops
Secret scan / Scan diff for credential-shaped strings (pull_request) Successful in 7s
CI / Detect changes (pull_request) Successful in 10s
CI / Canvas (Next.js) (pull_request) Successful in 5s
CI / Shellcheck (E2E scripts) (pull_request) Successful in 5s
CI / Python Lint & Test (pull_request) Successful in 6s
CI / Canvas Deploy Reminder (pull_request) Has been skipped
CI / Platform (Go) (pull_request) Failing after 59s
CI / all-required (pull_request) Successful in 1s
sop-tier-check / tier-check (pull_request) Successful in 30s
sop-checklist-gate / gate (pull_request) Successful in 41s
sop-checklist / all-items-acked (pull_request) [info tier:low] acked: 7/7
audit-force-merge / audit (pull_request) Successful in 34s
Go's database/sql contract requires callers to check rows.Err() after a
for rows.Next() loop — a mid-stream error (e.g. dropped connection
mid-result-set) is not surfaced by rows.Next() returning false.

Covered handlers:
- delegation.go: ListDelegations
- approvals.go: ListPendingApprovals, List
- instructions.go: List handler, scanInstructions helper (interface extended)
- secrets.go: ListSecrets, ListGlobalSecrets, notifyGlobalSecretChange
- events.go: List, ListByWorkspace
- discovery.go: queryPeerMaps

All checks log the error (non-fatal) so callers continue to receive the
partial result set rather than silently truncating.

Refs #862 (extending scope beyond delegation.go)
2026-05-13 15:49:57 +00:00
fullstack-engineer 39fc5d0f4e fix(handlers/bundle): restore bundle import test build
Secret scan / Scan diff for credential-shaped strings (pull_request) Successful in 32s
sop-checklist-gate / gate (pull_request) Successful in 40s
CI / Detect changes (pull_request) Successful in 1m18s
CI / Canvas (Next.js) (pull_request) Successful in 6s
CI / Shellcheck (E2E scripts) (pull_request) Successful in 5s
CI / Python Lint & Test (pull_request) Successful in 7s
CI / Canvas Deploy Reminder (pull_request) Has been skipped
CI / Platform (Go) (pull_request) Failing after 2m32s
CI / all-required (pull_request) Successful in 2s
sop-tier-check / tier-check (pull_request) Successful in 32s
sop-checklist / all-items-acked (pull_request) [info tier:low] acked: 7/7
audit-force-merge / audit (pull_request) Successful in 20s
Fixes three issues in bundle.go / bundle_test.go:

1. Missing sqlmock import: TestBundleImport_ValidJSON and
   TestBundleExport_NotFound use sqlmock.Sqlmock from setupTestDB()
   and call sqlmock.NewResult() but did not import go-sqlmock,
   causing a build failure.

2. Empty/null bundle guard: null JSON (ShouldBindJSON → zero-value Bundle{})
   or empty {} payload would bind without error and reach bundle.Import(),
   INSERTing a row with name="" and tier=0 into workspaces before
   failing.  Add b.Schema != "" guard before calling bundle.Import().

3. Outdated test expectations: TestBundleImport_ValidJSON expected
   INSERT INTO workspace_schedules and workspace_secrets which the current
   importer does not issue.  Remove those expectations so the test
   reflects actual importer behaviour (INSERT + UPDATE runtime only).

Closes #850
2026-05-13 15:26:47 +00:00
14 changed files with 1462 additions and 188 deletions
@@ -1,216 +1,162 @@
// @vitest-environment jsdom
/**
* FilesTab: NotAvailablePanel + FilesToolbar coverage.
* Tests for the main FilesTab / PlatformOwnedFilesTab component.
*
* NotAvailablePanel: pure presentational component — renders a "feature not
* available" placeholder for external-runtime workspaces.
* FilesToolbar: pure props-driven component — directory selector, file count,
* action buttons (New, Upload, Export, Clear, Refresh) with correct aria-labels.
* Covers: NotAvailablePanel (external runtime), loading/empty/error states,
* FilesToolbar actions, and the /configs-only upload guard.
*
* No @testing-library/jest-dom import — use textContent / className /
* getAttribute checks to avoid "expect is not defined" errors.
* No @testing-library/jest-dom — use textContent / className / getAttribute.
*/
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, render, screen } from "@testing-library/react";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import React from "react";
import { FilesToolbar } from "../FilesToolbar";
import { NotAvailablePanel } from "../NotAvailablePanel";
import { FilesTab } from "../../FilesTab.tsx";
import type { FileEntry } from "../../FilesTab/tree";
// ─── afterEach ─────────────────────────────────────────────────────────────────
// ─── Mock ──────────────────────────────────────────────────────────────────
const _mockGet = vi.hoisted(() => vi.fn<() => Promise<unknown>>());
vi.mock("@/lib/api", () => ({
api: { get: _mockGet, put: vi.fn(), del: vi.fn() },
}));
afterEach(() => {
cleanup();
vi.restoreAllMocks();
_mockGet.mockReset();
});
// ─── NotAvailablePanel ─────────────────────────────────────────────────────────
// ─── Helpers ───────────────────────────────────────────────────────────────
describe("NotAvailablePanel", () => {
it("renders heading 'Files not available'", () => {
const { container } = render(<NotAvailablePanel runtime="external" />);
expect(container.textContent).toContain("Files not available");
});
const emptyFileList: FileEntry[] = [];
it("renders the runtime name in monospace", () => {
const { container } = render(<NotAvailablePanel runtime="external" />);
expect(container.textContent).toContain("external");
const spans = container.querySelectorAll("span");
const monoSpans = Array.from(spans).filter(
(s) => s.className && s.className.includes("font-mono"),
);
expect(monoSpans.length).toBeGreaterThan(0);
});
/** Render FilesTab with a non-external runtime (triggers PlatformOwnedFilesTab). */
function renderPlatformTab(extraProps: Partial<React.ComponentProps<typeof FilesTab>> = {}) {
return render(
<FilesTab
workspaceId="ws-1"
data={{ id: "ws-1", name: "Test", runtime: "claude-code", status: "online", tier: 0, skills: [], created_at: "" }}
{...extraProps}
/>,
);
}
it("renders a Chat tab hint in description", () => {
const { container } = render(<NotAvailablePanel runtime="remote-agent" />);
expect(container.textContent).toContain("Chat tab");
});
// ─── NotAvailablePanel ──────────────────────────────────────────────────────
it("SVG icon has aria-hidden=true", () => {
const { container } = render(<NotAvailablePanel runtime="external" />);
const svg = container.querySelector("svg");
expect(svg?.getAttribute("aria-hidden")).toBe("true");
});
it("renders without crashing for any runtime string", () => {
const { container } = render(<NotAvailablePanel runtime="unknown-runtime" />);
expect(container.textContent).toContain("unknown-runtime");
});
it("applies the correct layout classes to root div", () => {
const { container } = render(<NotAvailablePanel runtime="external" />);
const root = container.firstElementChild as HTMLElement;
expect(root.className).toContain("flex");
expect(root.className).toContain("flex-col");
expect(root.className).toContain("items-center");
});
});
// ─── FilesToolbar ───────────────────────────────────────────────────────────────
describe("FilesToolbar", () => {
const noop = vi.fn();
function renderToolbar(props: Partial<React.ComponentProps<typeof FilesToolbar>> = {}) {
return render(
<FilesToolbar
root="/configs"
setRoot={noop}
fileCount={0}
onNewFile={noop}
onUpload={noop}
onDownloadAll={noop}
onClearAll={noop}
onRefresh={noop}
{...props}
describe("FilesTab — NotAvailablePanel", () => {
it("renders NotAvailablePanel when runtime is external", async () => {
_mockGet.mockResolvedValueOnce(emptyFileList);
render(
<FilesTab
workspaceId="ws-1"
data={{ id: "ws-1", name: "Test", runtime: "external", status: "online", tier: 0, skills: [], created_at: "" }}
/>,
);
}
it("renders the directory selector with correct aria-label", () => {
const { container } = renderToolbar();
const select = container.querySelector("select");
expect(select?.getAttribute("aria-label")).toBe("File root directory");
expect(screen.getByText(/Files not available/i)).toBeTruthy();
});
it("directory selector has all four options", () => {
const { container } = renderToolbar();
const select = container.querySelector("select") as HTMLSelectElement;
const options = Array.from(select?.options ?? []);
const values = options.map((o) => o.value);
expect(values).toContain("/configs");
expect(values).toContain("/home");
expect(values).toContain("/workspace");
expect(values).toContain("/plugins");
});
it("calls setRoot when directory changes", () => {
const setRoot = vi.fn();
const { container } = renderToolbar({ setRoot });
const select = container.querySelector("select") as HTMLSelectElement;
select.value = "/home";
select.dispatchEvent(new Event("change", { bubbles: true }));
expect(setRoot).toHaveBeenCalledWith("/home");
});
it("displays the file count", () => {
const { container } = renderToolbar({ fileCount: 42 });
expect(container.textContent).toContain("42 files");
});
it("shows New + Upload + Clear buttons for /configs", () => {
const { container } = renderToolbar({ root: "/configs" });
const texts = Array.from(container.querySelectorAll("button")).map(
(b) => b.textContent?.trim(),
it("renders the runtime name in NotAvailablePanel", async () => {
_mockGet.mockResolvedValueOnce(emptyFileList);
render(
<FilesTab
workspaceId="ws-1"
data={{ id: "ws-1", name: "Test", runtime: "external", status: "online", tier: 0, skills: [], created_at: "" }}
/>,
);
expect(texts).toContain("+ New");
expect(texts).toContain("Upload");
expect(texts).toContain("Clear");
expect(texts).toContain("Export");
expect(texts).toContain("↻");
expect(screen.getByText(/external/i)).toBeTruthy();
});
it("hides New + Upload + Clear for /workspace", () => {
const { container } = renderToolbar({ root: "/workspace" });
const texts = Array.from(container.querySelectorAll("button")).map(
(b) => b.textContent?.trim(),
it("does NOT call api.get when runtime is external", async () => {
render(
<FilesTab
workspaceId="ws-1"
data={{ id: "ws-1", name: "Test", runtime: "external", status: "online", tier: 0, skills: [], created_at: "" }}
/>,
);
expect(texts).not.toContain("+ New");
expect(texts).not.toContain("Upload");
expect(texts).not.toContain("Clear");
expect(texts).toContain("Export");
});
it("hides New + Upload + Clear for /home", () => {
const { container } = renderToolbar({ root: "/home" });
const texts = Array.from(container.querySelectorAll("button")).map(
(b) => b.textContent?.trim(),
);
expect(texts).not.toContain("+ New");
expect(texts).not.toContain("Upload");
expect(texts).not.toContain("Clear");
});
it("hides New + Upload + Clear for /plugins", () => {
const { container } = renderToolbar({ root: "/plugins" });
const texts = Array.from(container.querySelectorAll("button")).map(
(b) => b.textContent?.trim(),
);
expect(texts).not.toContain("+ New");
expect(texts).not.toContain("Upload");
expect(texts).not.toContain("Clear");
});
it("New button has correct aria-label", () => {
const { container } = renderToolbar({ root: "/configs" });
const newBtn = container.querySelector('button[aria-label="Create new file"]');
expect(newBtn?.textContent?.trim()).toBe("+ New");
});
it("Export button has correct aria-label", () => {
const { container } = renderToolbar();
const exportBtn = container.querySelector('button[aria-label="Download all files"]');
expect(exportBtn?.textContent?.trim()).toBe("Export");
});
it("Clear button has correct aria-label", () => {
const { container } = renderToolbar({ root: "/configs" });
const clearBtn = container.querySelector('button[aria-label="Delete all files"]');
expect(clearBtn?.textContent?.trim()).toBe("Clear");
});
it("Refresh button has correct aria-label", () => {
const { container } = renderToolbar();
const refreshBtn = container.querySelector('button[aria-label="Refresh file list"]');
expect(refreshBtn?.textContent?.trim()).toBe("↻");
});
it("calls onNewFile when New button is clicked", () => {
const onNewFile = vi.fn();
const { container } = renderToolbar({ root: "/configs", onNewFile });
container.querySelector('button[aria-label="Create new file"]')!.click();
expect(onNewFile).toHaveBeenCalledTimes(1);
});
it("calls onDownloadAll when Export button is clicked", () => {
const onDownloadAll = vi.fn();
const { container } = renderToolbar({ onDownloadAll });
container.querySelector('button[aria-label="Download all files"]')!.click();
expect(onDownloadAll).toHaveBeenCalledTimes(1);
});
it("calls onClearAll when Clear button is clicked", () => {
const onClearAll = vi.fn();
const { container } = renderToolbar({ root: "/configs", onClearAll });
container.querySelector('button[aria-label="Delete all files"]')!.click();
expect(onClearAll).toHaveBeenCalledTimes(1);
});
it("calls onRefresh when Refresh button is clicked", () => {
const onRefresh = vi.fn();
const { container } = renderToolbar({ onRefresh });
container.querySelector('button[aria-label="Refresh file list"]')!.click();
expect(onRefresh).toHaveBeenCalledTimes(1);
expect(_mockGet).not.toHaveBeenCalled();
});
});
// ─── Loading / Empty / Error states ────────────────────────────────────────
describe("FilesTab — states", () => {
it("shows loading text while fetching files", () => {
_mockGet.mockImplementation(
() => new Promise<unknown>(() => {}) as unknown as Promise<unknown>,
);
renderPlatformTab();
expect(screen.getByText("Loading files...")).toBeTruthy();
});
it("shows 'No config files yet' when root is /configs and no files", async () => {
_mockGet.mockResolvedValueOnce(emptyFileList);
renderPlatformTab();
await waitFor(() => {
expect(screen.getByText(/No config files yet/i)).toBeTruthy();
});
});
it("fetches from the correct endpoint", async () => {
_mockGet.mockResolvedValueOnce(emptyFileList);
renderPlatformTab();
await waitFor(() => {
expect(_mockGet).toHaveBeenCalledWith(expect.stringContaining("/workspaces/ws-1/files"));
});
});
it("shows file count from toolbar when files exist", async () => {
_mockGet.mockResolvedValue([
{ path: "configs/a.yaml", size: 10, dir: false },
{ path: "configs/b.yaml", size: 20, dir: false },
]);
renderPlatformTab();
await waitFor(() => {
expect(screen.getByText("2 files")).toBeTruthy();
});
});
});
// ─── FilesToolbar ──────────────────────────────────────────────────────────
describe("FilesTab — FilesToolbar", () => {
it("shows Refresh button", async () => {
_mockGet.mockResolvedValueOnce(emptyFileList);
renderPlatformTab();
await waitFor(() => {
expect(screen.getByLabelText("Refresh file list")).toBeTruthy();
});
});
it("shows root directory selector", async () => {
_mockGet.mockResolvedValueOnce(emptyFileList);
renderPlatformTab();
await waitFor(() => {
expect(screen.getByRole("combobox")).toBeTruthy();
});
});
it("Refresh button triggers a reload", async () => {
// Use persistent mock — loadFiles fires on mount AND on Refresh click.
_mockGet.mockResolvedValue(emptyFileList);
renderPlatformTab();
await waitFor(() => screen.getByLabelText("Refresh file list"));
const before = _mockGet.mock.calls.length;
fireEvent.click(screen.getByLabelText("Refresh file list"));
await waitFor(() => {
expect(_mockGet.mock.calls.length).toBeGreaterThan(before);
});
});
});
// ─── Upload guard ──────────────────────────────────────────────────────────
describe("FilesTab — upload guard", () => {
it("no error alert on dragover when root is /configs (default)", async () => {
_mockGet.mockResolvedValue(emptyFileList);
renderPlatformTab();
await waitFor(() => screen.getByText(/No config files yet/i));
// No alert should be present
expect(screen.queryByRole("alert")).toBeNull();
});
});
@@ -0,0 +1,218 @@
// @vitest-environment jsdom
/**
* Tests for tree.ts — buildTree and getIcon pure functions.
*/
import { describe, expect, it } from "vitest";
import type { FileEntry } from "../tree";
import { buildTree, getIcon } from "../tree";
// ─── getIcon ─────────────────────────────────────────────────────────────────
describe("getIcon", () => {
it("returns folder emoji for directories", () => {
expect(getIcon("/configs", true)).toBe("📁");
});
it("returns correct emoji for .md", () => {
expect(getIcon("readme.md", false)).toBe("📄");
});
it("returns correct emoji for .yaml", () => {
expect(getIcon("config.yaml", false)).toBe("⚙");
});
it("returns correct emoji for .yml", () => {
expect(getIcon("config.yml", false)).toBe("⚙");
});
it("returns correct emoji for .py", () => {
expect(getIcon("script.py", false)).toBe("🐍");
});
it("returns correct emoji for .ts", () => {
expect(getIcon("index.ts", false)).toBe("💠");
});
it("returns correct emoji for .tsx", () => {
expect(getIcon("App.tsx", false)).toBe("💠");
});
it("returns correct emoji for .js", () => {
expect(getIcon("index.js", false)).toBe("📜");
});
it("returns correct emoji for .json", () => {
expect(getIcon("package.json", false)).toBe("{}");
});
it("returns correct emoji for .html", () => {
expect(getIcon("index.html", false)).toBe("🌐");
});
it("returns correct emoji for .css", () => {
expect(getIcon("style.css", false)).toBe("🎨");
});
it("returns correct emoji for .sh", () => {
expect(getIcon("deploy.sh", false)).toBe("▸");
});
it("returns default file emoji for unknown extensions", () => {
expect(getIcon("Makefile", false)).toBe("📄");
expect(getIcon("Dockerfile", false)).toBe("📄");
expect(getIcon("Rakefile", false)).toBe("📄");
});
it("extension matching is case-insensitive", () => {
expect(getIcon("readme.MD", false)).toBe("📄");
expect(getIcon("script.PY", false)).toBe("🐍");
});
});
// ─── buildTree ───────────────────────────────────────────────────────────────
describe("buildTree", () => {
it("returns empty array for empty input", () => {
expect(buildTree([])).toEqual([]);
});
it("adds a single file at root", () => {
const files: FileEntry[] = [{ path: "config.yaml", size: 128, dir: false }];
const tree = buildTree(files);
expect(tree).toHaveLength(1);
expect(tree[0]).toMatchObject({
name: "config.yaml",
path: "config.yaml",
isDir: false,
children: [],
size: 128,
});
});
it("adds a single directory at root", () => {
const files: FileEntry[] = [{ path: "skills", size: 0, dir: true }];
const tree = buildTree(files);
expect(tree).toHaveLength(1);
expect(tree[0]).toMatchObject({
name: "skills",
path: "skills",
isDir: true,
children: [],
size: 0,
});
});
it("sorts dirs before files at the same level", () => {
const files: FileEntry[] = [
{ path: "b.txt", size: 10, dir: false },
{ path: "a.txt", size: 10, dir: false },
{ path: "z-dir", size: 0, dir: true },
{ path: "a-dir", size: 0, dir: true },
];
const tree = buildTree(files);
expect(tree).toHaveLength(4);
// Dirs first: z-dir, a-dir alphabetically → a before z
expect(tree[0].name).toBe("a-dir");
expect(tree[1].name).toBe("z-dir");
// Then files alphabetically
expect(tree[2].name).toBe("a.txt");
expect(tree[3].name).toBe("b.txt");
});
it("alphabetically sorts files within the same level", () => {
const files: FileEntry[] = [
{ path: "z.yaml", size: 10, dir: false },
{ path: "a.yaml", size: 10, dir: false },
{ path: "m.yaml", size: 10, dir: false },
];
const tree = buildTree(files);
expect(tree.map((n) => n.name)).toEqual(["a.yaml", "m.yaml", "z.yaml"]);
});
it("nests a file under its parent directory", () => {
const files: FileEntry[] = [
{ path: "skills", size: 0, dir: true },
{ path: "skills/readme.md", size: 64, dir: false },
];
const tree = buildTree(files);
expect(tree).toHaveLength(1);
expect(tree[0].name).toBe("skills");
expect(tree[0].children).toHaveLength(1);
expect(tree[0].children[0]).toMatchObject({
name: "readme.md",
path: "skills/readme.md",
isDir: false,
size: 64,
});
});
it("creates intermediate directories automatically", () => {
const files: FileEntry[] = [
{ path: "a/b/c/deep.txt", size: 32, dir: false },
];
const tree = buildTree(files);
// Root has one child: "a"
expect(tree).toHaveLength(1);
expect(tree[0].name).toBe("a");
expect(tree[0].isDir).toBe(true);
// "a" has one child: "b"
expect(tree[0].children).toHaveLength(1);
expect(tree[0].children[0].name).toBe("b");
// "b" has one child: "c"
expect(tree[0].children[0].children).toHaveLength(1);
expect(tree[0].children[0].children[0].name).toBe("c");
// "c" has the file
expect(tree[0].children[0].children[0].children[0].name).toBe("deep.txt");
expect(tree[0].children[0].children[0].children[0].size).toBe(32);
});
it("adds multiple files to the same directory", () => {
const files: FileEntry[] = [
{ path: "configs", size: 0, dir: true },
{ path: "configs/a.yaml", size: 10, dir: false },
{ path: "configs/b.yaml", size: 20, dir: false },
];
const tree = buildTree(files);
expect(tree).toHaveLength(1);
expect(tree[0].children.map((n) => n.name).sort()).toEqual(["a.yaml", "b.yaml"]);
});
it("does not duplicate a directory already created as intermediate", () => {
const files: FileEntry[] = [
{ path: "a/b.txt", size: 5, dir: false },
{ path: "a", size: 0, dir: true },
];
const tree = buildTree(files);
// "a" should appear only once
expect(tree).toHaveLength(1);
expect(tree[0].name).toBe("a");
// The dir "a" should still contain "b.txt"
expect(tree[0].children).toHaveLength(1);
expect(tree[0].children[0].name).toBe("b.txt");
});
it("intermediate dirs have size 0", () => {
const files: FileEntry[] = [
{ path: "a/b/c/file.txt", size: 1, dir: false },
];
const tree = buildTree(files);
expect(tree[0].size).toBe(0);
expect(tree[0].children[0].size).toBe(0);
});
it("handles deeply nested mixed dirs and files", () => {
const files: FileEntry[] = [
{ path: "a", size: 0, dir: true },
{ path: "a/b", size: 0, dir: true },
{ path: "a/b/c", size: 0, dir: true },
{ path: "a/b/c/d.txt", size: 1, dir: false },
{ path: "a/b/e.txt", size: 2, dir: false },
{ path: "a/f.txt", size: 3, dir: false },
];
const tree = buildTree(files);
expect(tree).toHaveLength(1); // root: "a"
expect(tree[0].children.map((n) => n.name).sort()).toEqual(["b", "f.txt"]);
expect(tree[0].children.find((n) => n.name === "b")!.children.map((n) => n.name).sort())
.toEqual(["c", "e.txt"]);
});
});
@@ -0,0 +1,271 @@
// @vitest-environment jsdom
/**
* Tests for ChannelsTab component.
*
* Covers: relativeTime pure function, SUPPORTS_DETECT_CHATS constant,
* loading/empty/error states, channel list rendering (enabled/disabled),
* auto-refresh interval, header + Connect button.
*/
import React from "react";
import { render, screen, fireEvent, cleanup, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ChannelsTab } from "../ChannelsTab";
// Mock @/lib/api — hoisted so it's applied before the module loads.
const _mockGet = vi.hoisted(() => vi.fn<() => Promise<unknown>>());
vi.mock("@/lib/api", () => ({
api: { get: _mockGet },
}));
afterEach(() => {
cleanup();
_mockGet.mockReset();
});
// ─── SUPPORTS_DETECT_CHATS ─────────────────────────────────────────────────
describe("ChannelsTab — SUPPORTS_DETECT_CHATS", () => {
it("supports Detect Chats for telegram", async () => {
// Telegram is the only platform that supports Detect Chats.
// This is a smoke test: the tab must render without crashing.
// NOTE: ChannelsTab calls Promise.allSettled([channels, adapters]) so
// both must be mocked for the load() to complete and exit loading state.
_mockGet.mockResolvedValueOnce([]);
_mockGet.mockResolvedValueOnce([]);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("Channels")).toBeTruthy();
});
});
});
// ─── States ───────────────────────────────────────────────────────────────
describe("ChannelsTab — states", () => {
it("shows loading text initially", () => {
_mockGet.mockImplementation(
() => new Promise<unknown>(() => {}) as unknown as Promise<unknown>
);
render(<ChannelsTab workspaceId="ws-1" />);
expect(screen.getByText("Loading channels...")).toBeTruthy();
});
it("shows empty message when no channels", async () => {
_mockGet.mockResolvedValueOnce([]);
_mockGet.mockResolvedValueOnce([]);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("No channels connected")).toBeTruthy();
});
});
it("shows error alert when channels fetch fails", async () => {
// Channels fails; adapters succeeds. Both must be resolved/rejected
// for Promise.allSettled to settle and setLoading(false).
_mockGet.mockRejectedValueOnce(new Error("server error"));
_mockGet.mockResolvedValueOnce([]);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
// The component renders a generic error message, not the raw error text.
expect(screen.getByText(/Failed to load connected channels/i)).toBeTruthy();
});
});
it("shows error alert when adapters fetch fails", async () => {
_mockGet.mockResolvedValueOnce([]);
_mockGet.mockRejectedValueOnce(new Error("adapters error"));
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText(/Failed to load platforms/i)).toBeTruthy();
});
});
});
// ─── Channel list ──────────────────────────────────────────────────────────
describe("ChannelsTab — channel list", () => {
// ChannelsTab.load() calls Promise.allSettled([channels, adapters]).
// Both must be mocked for load() to complete and exit loading state.
const channelsPayload = (channels: object[]) => channels;
const adaptersPayload: unknown[] = [];
it("renders one channel", async () => {
_mockGet.mockResolvedValueOnce(channelsPayload([{
id: "ch-1", workspace_id: "ws-1", channel_type: "telegram",
config: { chat_id: "12345" }, enabled: true, allowed_users: [],
message_count: 10, last_message_at: null, created_at: new Date().toISOString(),
}]));
_mockGet.mockResolvedValueOnce(adaptersPayload);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("Telegram")).toBeTruthy();
});
});
it("renders multiple channels", async () => {
_mockGet.mockResolvedValueOnce(channelsPayload([
{ id: "ch-1", workspace_id: "ws-1", channel_type: "telegram",
config: { chat_id: "1" }, enabled: true, allowed_users: [],
message_count: 5, last_message_at: null, created_at: new Date().toISOString() },
{ id: "ch-2", workspace_id: "ws-1", channel_type: "slack",
config: { channel_id: "C0123" }, enabled: false, allowed_users: [],
message_count: 0, last_message_at: null, created_at: new Date().toISOString() },
]));
_mockGet.mockResolvedValueOnce(adaptersPayload);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("Telegram")).toBeTruthy();
expect(screen.getByText("Slack")).toBeTruthy();
});
});
it("capitalises channel type", async () => {
_mockGet.mockResolvedValueOnce(channelsPayload([{
id: "ch-1", workspace_id: "ws-1", channel_type: "discord",
config: {}, enabled: true, allowed_users: [],
message_count: 0, last_message_at: null, created_at: new Date().toISOString(),
}]));
_mockGet.mockResolvedValueOnce(adaptersPayload);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("Discord")).toBeTruthy();
});
});
it("shows 'On' toggle for enabled channel", async () => {
_mockGet.mockResolvedValueOnce(channelsPayload([{
id: "ch-1", workspace_id: "ws-1", channel_type: "telegram",
config: {}, enabled: true, allowed_users: [],
message_count: 1, last_message_at: null, created_at: new Date().toISOString(),
}]));
_mockGet.mockResolvedValueOnce(adaptersPayload);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
// Use exact string "On" (not regex) — "Connect" contains "on" and would
// match /on/i, causing multiple-element errors.
expect(screen.getByRole("button", { name: "On" })).toBeTruthy();
});
});
it("shows 'Off' toggle for disabled channel", async () => {
_mockGet.mockResolvedValueOnce(channelsPayload([{
id: "ch-1", workspace_id: "ws-1", channel_type: "telegram",
config: {}, enabled: false, allowed_users: [],
message_count: 1, last_message_at: null, created_at: new Date().toISOString(),
}]));
_mockGet.mockResolvedValueOnce(adaptersPayload);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByRole("button", { name: "Off" })).toBeTruthy();
});
});
it("shows message count", async () => {
_mockGet.mockResolvedValueOnce(channelsPayload([{
id: "ch-1", workspace_id: "ws-1", channel_type: "telegram",
config: {}, enabled: true, allowed_users: [],
message_count: 42, last_message_at: null, created_at: new Date().toISOString(),
}]));
_mockGet.mockResolvedValueOnce(adaptersPayload);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("42 messages")).toBeTruthy();
});
});
it("shows 'Last: never' when last_message_at is null", async () => {
_mockGet.mockResolvedValueOnce(channelsPayload([{
id: "ch-1", workspace_id: "ws-1", channel_type: "telegram",
config: {}, enabled: true, allowed_users: [],
message_count: 0, last_message_at: null, created_at: new Date().toISOString(),
}]));
_mockGet.mockResolvedValueOnce(adaptersPayload);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("Last: never")).toBeTruthy();
});
});
it("shows allowed user count when users are present", async () => {
_mockGet.mockResolvedValueOnce(channelsPayload([{
id: "ch-1", workspace_id: "ws-1", channel_type: "telegram",
config: {}, enabled: true, allowed_users: ["alice", "bob"],
message_count: 0, last_message_at: null, created_at: new Date().toISOString(),
}]));
_mockGet.mockResolvedValueOnce(adaptersPayload);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("2 allowed user(s)")).toBeTruthy();
});
});
it("has a Test button for each channel", async () => {
_mockGet.mockResolvedValueOnce(channelsPayload([{
id: "ch-1", workspace_id: "ws-1", channel_type: "telegram",
config: {}, enabled: true, allowed_users: [],
message_count: 0, last_message_at: null, created_at: new Date().toISOString(),
}]));
_mockGet.mockResolvedValueOnce(adaptersPayload);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByRole("button", { name: /test/i })).toBeTruthy();
});
});
it("has a Remove button for each channel", async () => {
_mockGet.mockResolvedValueOnce(channelsPayload([{
id: "ch-1", workspace_id: "ws-1", channel_type: "telegram",
config: {}, enabled: true, allowed_users: [],
message_count: 0, last_message_at: null, created_at: new Date().toISOString(),
}]));
_mockGet.mockResolvedValueOnce(adaptersPayload);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByRole("button", { name: /remove/i })).toBeTruthy();
});
});
});
// ─── Header + Connect button ───────────────────────────────────────────────
describe("ChannelsTab — header", () => {
it("renders the Channels heading", async () => {
_mockGet.mockResolvedValue([]);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("Channels")).toBeTruthy();
});
});
it("has a Connect button when channels exist", async () => {
_mockGet.mockResolvedValue([
{
id: "ch-1", workspace_id: "ws-1", channel_type: "telegram",
config: {}, enabled: true, allowed_users: [],
message_count: 1, last_message_at: null, created_at: new Date().toISOString(),
},
]);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByRole("button", { name: /connect/i })).toBeTruthy();
});
});
it("has a Cancel button when form is open", async () => {
_mockGet.mockResolvedValue([
{
id: "ch-1", workspace_id: "ws-1", channel_type: "telegram",
config: {}, enabled: true, allowed_users: [],
message_count: 1, last_message_at: null, created_at: new Date().toISOString(),
},
]);
render(<ChannelsTab workspaceId="ws-1" />);
await waitFor(() => {
const btn = screen.getByRole("button", { name: /connect/i });
fireEvent.click(btn);
});
await waitFor(() => {
expect(screen.getByRole("button", { name: /cancel/i })).toBeTruthy();
});
});
});
@@ -0,0 +1,205 @@
// @vitest-environment jsdom
/**
* Tests for EventsTab component.
*
* Covers: formatTime pure function, EVENT_COLORS constant,
* loading/error/empty states, event list rendering, expand/collapse,
* refresh button, auto-refresh setup.
*/
import React from "react";
import { render, screen, fireEvent, cleanup, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { EventsTab } from "../EventsTab";
// Mock @/lib/api — hoisted so it's applied before the module loads.
const _mockGet = vi.hoisted(() => vi.fn<() => Promise<unknown[]>>());
vi.mock("@/lib/api", () => ({
api: { get: _mockGet },
}));
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
// ─── formatTime tests (via rendered output) ────────────────────────────────────
describe("EventsTab — formatTime", () => {
it("shows 'ago' for events less than a minute old", async () => {
const now = new Date();
const recent = new Date(now.getTime() - 30_000).toISOString();
_mockGet.mockResolvedValueOnce([
{ id: "e1", event_type: "WORKSPACE_ONLINE", workspace_id: null, payload: {}, created_at: recent },
]);
render(<EventsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText(/ago/)).toBeTruthy();
});
});
it("shows 'm ago' for events less than an hour old", async () => {
const now = new Date();
const minsAgo = new Date(now.getTime() - 5 * 60_000).toISOString();
_mockGet.mockResolvedValueOnce([
{ id: "e1", event_type: "WORKSPACE_OFFLINE", workspace_id: null, payload: {}, created_at: minsAgo },
]);
render(<EventsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText(/m ago/)).toBeTruthy();
});
});
it("shows 'h ago' for events less than a day old", async () => {
const now = new Date();
const hoursAgo = new Date(now.getTime() - 3 * 3_600_000).toISOString();
_mockGet.mockResolvedValueOnce([
{ id: "e1", event_type: "WORKSPACE_DEGRADED", workspace_id: null, payload: {}, created_at: hoursAgo },
]);
render(<EventsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText(/h ago/)).toBeTruthy();
});
});
});
// ─── EVENT_COLORS rendering ───────────────────────────────────────────────────
describe("EventsTab — EVENT_COLORS", () => {
it("renders all known event types without crashing", async () => {
const eventTypes = [
"WORKSPACE_ONLINE",
"WORKSPACE_OFFLINE",
"WORKSPACE_DEGRADED",
"WORKSPACE_PROVISIONING",
"WORKSPACE_REMOVED",
"WORKSPACE_PROVISION_FAILED",
"AGENT_CARD_UPDATED",
];
_mockGet.mockResolvedValueOnce(
eventTypes.map((event_type, i) => ({
id: `e-${i}`, event_type, workspace_id: null, payload: {}, created_at: new Date().toISOString(),
})),
);
render(<EventsTab workspaceId="ws-1" />);
await waitFor(() => {
for (const et of eventTypes) {
expect(screen.getByText(et)).toBeTruthy();
}
});
});
it("renders unknown event types without crashing", async () => {
_mockGet.mockResolvedValueOnce([
{ id: "e-unk", event_type: "UNKNOWN_EVENT_XYZ", workspace_id: null, payload: {}, created_at: new Date().toISOString() },
]);
render(<EventsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("UNKNOWN_EVENT_XYZ")).toBeTruthy();
});
});
});
// ─── States ───────────────────────────────────────────────────────────────────
describe("EventsTab — states", () => {
it("shows loading text initially", () => {
_mockGet.mockImplementation(() => new Promise(() => {})); // never resolves
render(<EventsTab workspaceId="ws-1" />);
expect(screen.getByText("Loading events...")).toBeTruthy();
});
it("shows empty message when no events returned", async () => {
_mockGet.mockResolvedValueOnce([]);
render(<EventsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("No events yet")).toBeTruthy();
});
});
it("shows error alert when fetch fails", async () => {
_mockGet.mockRejectedValueOnce(new Error("server error"));
render(<EventsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText(/server error/i)).toBeTruthy();
});
});
});
// ─── Event list ───────────────────────────────────────────────────────────────
describe("EventsTab — event list", () => {
it("renders all returned events", async () => {
_mockGet.mockResolvedValueOnce([
{ id: "e1", event_type: "WORKSPACE_ONLINE", workspace_id: null, payload: { foo: 1 }, created_at: new Date().toISOString() },
{ id: "e2", event_type: "WORKSPACE_OFFLINE", workspace_id: null, payload: { bar: 2 }, created_at: new Date().toISOString() },
]);
render(<EventsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getAllByText(/WORKSPACE_/).length).toBeGreaterThanOrEqual(2);
});
});
it("shows event count in header", async () => {
_mockGet.mockResolvedValueOnce([
{ id: "e1", event_type: "WORKSPACE_ONLINE", workspace_id: null, payload: {}, created_at: new Date().toISOString() },
{ id: "e2", event_type: "WORKSPACE_OFFLINE", workspace_id: null, payload: {}, created_at: new Date().toISOString() },
{ id: "e3", event_type: "WORKSPACE_DEGRADED", workspace_id: null, payload: {}, created_at: new Date().toISOString() },
]);
render(<EventsTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("3 events")).toBeTruthy();
});
});
it("expands payload panel on click", async () => {
_mockGet.mockResolvedValueOnce([
{ id: "e-expand", event_type: "WORKSPACE_ONLINE", workspace_id: null, payload: { key: "value" }, created_at: new Date().toISOString() },
]);
render(<EventsTab workspaceId="ws-1" />);
await waitFor(() => screen.getByText("WORKSPACE_ONLINE"));
fireEvent.click(screen.getByText("WORKSPACE_ONLINE"));
await waitFor(() => {
expect(screen.getByText(/"key":\s*"value"/)).toBeTruthy();
});
});
it("collapses expanded panel on second click", async () => {
_mockGet.mockResolvedValueOnce([
{ id: "e-collapse", event_type: "WORKSPACE_DEGRADED", workspace_id: null, payload: { x: 1 }, created_at: new Date().toISOString() },
]);
render(<EventsTab workspaceId="ws-1" />);
await waitFor(() => screen.getByText("WORKSPACE_DEGRADED"));
fireEvent.click(screen.getByText("WORKSPACE_DEGRADED"));
await waitFor(() => expect(screen.getByText(/"x":\s*1/)).toBeTruthy());
fireEvent.click(screen.getByText("WORKSPACE_DEGRADED"));
await waitFor(() => {
expect(screen.queryByText(/"x":\s*1/)).toBeNull();
});
});
});
// ─── Refresh button ───────────────────────────────────────────────────────────
describe("EventsTab — refresh", () => {
it("has a Refresh button", async () => {
_mockGet.mockResolvedValueOnce([]);
render(<EventsTab workspaceId="ws-1" />);
await waitFor(() => {});
expect(screen.getByRole("button", { name: /refresh/i })).toBeTruthy();
});
it("Refresh button triggers a reload", async () => {
_mockGet.mockResolvedValueOnce([]);
render(<EventsTab workspaceId="ws-1" />);
await waitFor(() => screen.getByRole("button", { name: /refresh/i }));
fireEvent.click(screen.getByRole("button", { name: /refresh/i }));
// Called at least twice: initial load + refresh click
expect(_mockGet).toHaveBeenCalled();
});
});
@@ -0,0 +1,156 @@
// @vitest-environment jsdom
/**
* Tests for ScheduleTab component.
*
* Covers: cronToHuman pure function, relativeTime pure function,
* loading/error/empty states, schedule list rendering.
*/
import React from "react";
import { render, screen, fireEvent, cleanup, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ScheduleTab } from "../ScheduleTab";
const _mockGet = vi.hoisted(() => vi.fn<() => Promise<unknown[]>>());
vi.mock("@/lib/api", () => ({
api: { get: _mockGet },
}));
afterEach(() => {
cleanup();
_mockGet.mockReset();
});
// ─── cronToHuman tests ─────────────────────────────────────────────────────
describe("ScheduleTab — cronToHuman", () => {
it('returns "Every minute" for "* * * * *"', async () => {
_mockGet.mockResolvedValueOnce([
{ id: "s1", workspace_id: "ws-1", name: "Test", cron_expr: "* * * * *",
timezone: "UTC", prompt: "", enabled: true, last_run_at: null, next_run_at: null,
run_count: 0, last_status: "ok", last_error: "", created_at: new Date().toISOString() },
]);
render(<ScheduleTab workspaceId="ws-1" />);
expect(await screen.findByText("Every minute")).toBeTruthy();
});
it("returns 'Every X minutes' for '*/X * * * *'", async () => {
_mockGet.mockResolvedValueOnce([
{ id: "s1", workspace_id: "ws-1", name: "Test", cron_expr: "*/15 * * * *",
timezone: "UTC", prompt: "", enabled: true, last_run_at: null, next_run_at: null,
run_count: 0, last_status: "ok", last_error: "", created_at: new Date().toISOString() },
]);
render(<ScheduleTab workspaceId="ws-1" />);
expect(await screen.findByText("Every 15 minutes")).toBeTruthy();
});
it("returns 'Every X hours' for '0 */X * * *'", async () => {
_mockGet.mockResolvedValueOnce([
{ id: "s1", workspace_id: "ws-1", name: "Test", cron_expr: "0 */3 * * *",
timezone: "UTC", prompt: "", enabled: true, last_run_at: null, next_run_at: null,
run_count: 0, last_status: "ok", last_error: "", created_at: new Date().toISOString() },
]);
render(<ScheduleTab workspaceId="ws-1" />);
expect(await screen.findByText("Every 3 hours")).toBeTruthy();
});
it("returns 'Daily at HH:MM UTC' for daily schedules", async () => {
_mockGet.mockResolvedValueOnce([
{ id: "s1", workspace_id: "ws-1", name: "Test", cron_expr: "30 14 * * *",
timezone: "UTC", prompt: "", enabled: true, last_run_at: null, next_run_at: null,
run_count: 0, last_status: "ok", last_error: "", created_at: new Date().toISOString() },
]);
render(<ScheduleTab workspaceId="ws-1" />);
expect(await screen.findByText("Daily at 14:30 UTC")).toBeTruthy();
});
it("returns 'Weekdays at HH:MM UTC' for weekday schedules", async () => {
_mockGet.mockResolvedValueOnce([
{ id: "s1", workspace_id: "ws-1", name: "Test", cron_expr: "0 9 * * 1-5",
timezone: "UTC", prompt: "", enabled: true, last_run_at: null, next_run_at: null,
run_count: 0, last_status: "ok", last_error: "", created_at: new Date().toISOString() },
]);
render(<ScheduleTab workspaceId="ws-1" />);
expect(await screen.findByText("Weekdays at 09:00 UTC")).toBeTruthy();
});
it("falls back to raw expression for unrecognised patterns", async () => {
_mockGet.mockResolvedValueOnce([
{ id: "s1", workspace_id: "ws-1", name: "Test", cron_expr: "0 0 1 * *",
timezone: "UTC", prompt: "", enabled: true, last_run_at: null, next_run_at: null,
run_count: 0, last_status: "ok", last_error: "", created_at: new Date().toISOString() },
]);
render(<ScheduleTab workspaceId="ws-1" />);
expect(await screen.findByText("0 0 1 * *")).toBeTruthy();
});
it("falls back to raw expression for malformed input", async () => {
_mockGet.mockResolvedValueOnce([
{ id: "s1", workspace_id: "ws-1", name: "Test", cron_expr: "not a cron",
timezone: "UTC", prompt: "", enabled: true, last_run_at: null, next_run_at: null,
run_count: 0, last_status: "ok", last_error: "", created_at: new Date().toISOString() },
]);
render(<ScheduleTab workspaceId="ws-1" />);
expect(await screen.findByText("not a cron")).toBeTruthy();
});
});
// ─── relativeTime tests ─────────────────────────────────────────────────────
describe("ScheduleTab — relativeTime", () => {
it('shows "Last: never" when last_run_at is null', async () => {
// Use mockResolvedValue (persistent) instead of mockResolvedValueOnce because
// ScheduleTab's 10 s auto-refresh interval fires and calls fetchSchedules
// a second time, consuming a one-time mock and clearing the DOM.
_mockGet.mockResolvedValue([
{ id: "s1", workspace_id: "ws-1", name: "Test", cron_expr: "0 9 * * *",
timezone: "UTC", prompt: "", enabled: true, last_run_at: null, next_run_at: null,
run_count: 0, last_status: "ok", last_error: "", created_at: new Date().toISOString() },
]);
render(<ScheduleTab workspaceId="ws-1" />);
// Use "Last: never" to match the exact label text in ScheduleTab.tsx:349.
// findByText("never") would throw on the multiple-match ambiguity since
// "never" also appears in the "Next: never" span.
expect(await screen.findByText("Last: never")).toBeTruthy();
});
});
// ─── States ───────────────────────────────────────────────────────────────
describe("ScheduleTab — states", () => {
it("shows empty message when no schedules", async () => {
_mockGet.mockResolvedValueOnce([]);
render(<ScheduleTab workspaceId="ws-1" />);
expect(await screen.findByText("No schedules yet")).toBeTruthy();
});
// Note: ScheduleTab silently swallows fetch errors (no error state for
// the initial load). Error state only exists for form-level actions
// (save/delete/toggle) which require api.post/del/patch mocking.
});
// ─── Schedule list ─────────────────────────────────────────────────────────
describe("ScheduleTab — list", () => {
it("renders schedule name", async () => {
_mockGet.mockResolvedValueOnce([
{ id: "s1", workspace_id: "ws-1", name: "Nightly Run", cron_expr: "0 2 * * *",
timezone: "UTC", prompt: "", enabled: true, last_run_at: null, next_run_at: null,
run_count: 0, last_status: "ok", last_error: "", created_at: new Date().toISOString() },
]);
render(<ScheduleTab workspaceId="ws-1" />);
expect(await screen.findByText("Nightly Run")).toBeTruthy();
});
it("renders multiple schedules", async () => {
_mockGet.mockResolvedValueOnce([
{ id: "s1", workspace_id: "ws-1", name: "Schedule A", cron_expr: "0 9 * * *",
timezone: "UTC", prompt: "", enabled: true, last_run_at: null, next_run_at: null,
run_count: 0, last_status: "ok", last_error: "", created_at: new Date().toISOString() },
{ id: "s2", workspace_id: "ws-1", name: "Schedule B", cron_expr: "*/15 * * * *",
timezone: "UTC", prompt: "", enabled: false, last_run_at: null, next_run_at: null,
run_count: 0, last_status: "ok", last_error: "", created_at: new Date().toISOString() },
]);
render(<ScheduleTab workspaceId="ws-1" />);
expect(await screen.findByText("Schedule A")).toBeTruthy();
expect(await screen.findByText("Schedule B")).toBeTruthy();
});
});
@@ -0,0 +1,292 @@
// @vitest-environment jsdom
/**
* Tests for TracesTab component.
*
* Covers: loading/empty/error states, trace list rendering, expand/collapse,
* status dot coloring, latency formatting, token usage display, Refresh button.
*/
import React from "react";
import { render, screen, fireEvent, cleanup, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { TracesTab } from "../TracesTab";
const _mockGet = vi.hoisted(() => vi.fn<() => Promise<unknown>>());
vi.mock("@/lib/api", () => ({
api: { get: _mockGet },
}));
afterEach(() => {
cleanup();
_mockGet.mockReset();
});
// ─── States ───────────────────────────────────────────────────────────────
describe("TracesTab — states", () => {
it("shows loading text initially", () => {
_mockGet.mockImplementation(
() => new Promise<unknown>(() => {}) as unknown as Promise<unknown>
);
render(<TracesTab workspaceId="ws-1" />);
expect(screen.getByText("Loading traces...")).toBeTruthy();
});
it("shows empty message when no traces", async () => {
_mockGet.mockResolvedValueOnce({ data: [] });
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("No traces yet")).toBeTruthy();
});
});
it("shows empty message when API returns null data", async () => {
_mockGet.mockResolvedValueOnce({ data: null });
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("No traces yet")).toBeTruthy();
});
});
it("shows error alert when fetch fails", async () => {
_mockGet.mockRejectedValueOnce(new Error("trace service unavailable"));
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText(/trace service unavailable/i)).toBeTruthy();
});
});
});
// ─── Trace list ──────────────────────────────────────────────────────────
describe("TracesTab — trace list", () => {
it("renders one trace", async () => {
_mockGet.mockResolvedValueOnce({
data: [{
id: "t-1",
name: "deploy-agent",
timestamp: new Date().toISOString(),
status: "ok",
}],
});
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("deploy-agent")).toBeTruthy();
});
});
it("renders trace name as fallback to 'trace'", async () => {
_mockGet.mockResolvedValueOnce({
data: [{
id: "t-1",
name: "",
timestamp: new Date().toISOString(),
}],
});
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("trace")).toBeTruthy();
});
});
it("shows trace count in header", async () => {
_mockGet.mockResolvedValueOnce({
data: [
{ id: "t-1", name: "A", timestamp: new Date().toISOString() },
{ id: "t-2", name: "B", timestamp: new Date().toISOString() },
{ id: "t-3", name: "C", timestamp: new Date().toISOString() },
],
});
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("3 traces")).toBeTruthy();
});
});
it("shows latency in milliseconds for values < 1000", async () => {
_mockGet.mockResolvedValueOnce({
data: [{
id: "t-1",
name: "Fast trace",
timestamp: new Date().toISOString(),
latency: 250,
}],
});
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("250ms")).toBeTruthy();
});
});
it("shows latency in seconds for values >= 1000", async () => {
_mockGet.mockResolvedValueOnce({
data: [{
id: "t-1",
name: "Slow trace",
timestamp: new Date().toISOString(),
latency: 3500,
}],
});
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("3.5s")).toBeTruthy();
});
});
it("shows token usage when present", async () => {
_mockGet.mockResolvedValueOnce({
data: [{
id: "t-1",
name: "AI trace",
timestamp: new Date().toISOString(),
usage: { input: 100, output: 200, total: 300 },
}],
});
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("300 tok")).toBeTruthy();
});
});
it("does not show latency when latency is absent", async () => {
_mockGet.mockResolvedValueOnce({
data: [{
id: "t-1",
name: "Trace",
timestamp: new Date().toISOString(),
}],
});
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => {
expect(screen.getByText("Trace")).toBeTruthy();
// Should have no "ms" or "s" latency text
expect(screen.queryByText(/\d+ms/)).toBeNull();
expect(screen.queryByText(/\d+\.\d+s/)).toBeNull();
});
});
});
// ─── Expand / Collapse ───────────────────────────────────────────────────
describe("TracesTab — expand/collapse", () => {
it("expands a trace row on click", async () => {
_mockGet.mockResolvedValueOnce({
data: [{
id: "t-expand",
name: "Expandable",
timestamp: new Date().toISOString(),
input: { prompt: "hello" },
output: { result: "world" },
totalCost: 0.000123,
}],
});
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => screen.getByText("Expandable"));
fireEvent.click(screen.getByText("Expandable"));
await waitFor(() => {
expect(screen.getByText("Input")).toBeTruthy();
expect(screen.getByText("Output")).toBeTruthy();
});
});
it("shows trace ID in expanded panel", async () => {
_mockGet.mockResolvedValueOnce({
data: [{
id: "trace-id-abc123",
name: "Trace",
timestamp: new Date().toISOString(),
}],
});
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => screen.getByText("Trace"));
fireEvent.click(screen.getByText("Trace"));
await waitFor(() => {
expect(screen.getByText("trace-id-abc123")).toBeTruthy();
});
});
it("shows cost when totalCost is present", async () => {
_mockGet.mockResolvedValueOnce({
data: [{
id: "t-cost",
name: "Costly trace",
timestamp: new Date().toISOString(),
totalCost: 0.000456,
}],
});
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => screen.getByText("Costly trace"));
fireEvent.click(screen.getByText("Costly trace"));
await waitFor(() => {
// Use regex — toFixed(6) is locale-sensitive (may render as "0,000456").
expect(screen.getByText(/\$0\.000456/)).toBeTruthy();
});
});
it("collapses expanded row on second click", async () => {
_mockGet.mockResolvedValueOnce({
data: [{
id: "t-collapse",
name: "Collapsible",
timestamp: new Date().toISOString(),
input: { key: "value" },
}],
});
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => screen.getByText("Collapsible"));
fireEvent.click(screen.getByText("Collapsible"));
await waitFor(() => expect(screen.getByText("Input")).toBeTruthy());
fireEvent.click(screen.getByText("Collapsible"));
await waitFor(() => {
expect(screen.queryByText("Input")).toBeNull();
});
});
it("has aria-expanded attribute on trace row", async () => {
_mockGet.mockResolvedValueOnce({
data: [{
id: "t-a11y",
name: "A11y trace",
timestamp: new Date().toISOString(),
}],
});
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => screen.getByText("A11y trace"));
const row = screen.getByText("A11y trace").closest("button");
expect(row?.getAttribute("aria-expanded")).toBe("false");
fireEvent.click(row!);
await waitFor(() => {
expect(row?.getAttribute("aria-expanded")).toBe("true");
});
});
});
// ─── Refresh button ───────────────────────────────────────────────────────
describe("TracesTab — refresh", () => {
it("has a Refresh button", async () => {
_mockGet.mockResolvedValueOnce({ data: [] });
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => {});
expect(screen.getByRole("button", { name: /refresh/i })).toBeTruthy();
});
it("Refresh button triggers a reload", async () => {
_mockGet.mockResolvedValueOnce({ data: [] });
render(<TracesTab workspaceId="ws-1" />);
await waitFor(() => screen.getByRole("button", { name: /refresh/i }));
fireEvent.click(screen.getByRole("button", { name: /refresh/i }));
expect(_mockGet).toHaveBeenCalled();
});
});
@@ -116,6 +116,9 @@ func (h *ApprovalsHandler) ListAll(c *gin.Context) {
"created_at": createdAt,
})
}
if err := rows.Err(); err != nil {
log.Printf("ListPendingApprovals scan error: %v", err)
}
c.JSON(http.StatusOK, approvals)
}
@@ -155,6 +158,9 @@ func (h *ApprovalsHandler) List(c *gin.Context) {
"created_at": createdAt,
})
}
if err := rows.Err(); err != nil {
log.Printf("ListApprovals scan error: %v", err)
}
c.JSON(http.StatusOK, approvals)
}
@@ -50,6 +50,14 @@ func (h *BundleHandler) Import(c *gin.Context) {
return
}
// Reject null JSON (which binds to a zero-value Bundle{}) and empty schema.
// Without this guard a POST of `null` or `{}` would INSERT a workspace row
// with name="" and tier=0 into the DB before bundle.Import() fails.
if b.Schema == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid bundle"})
return
}
ctx := c.Request.Context()
result := bundle.Import(ctx, &b, nil, h.broadcaster, h.provisioner, h.platformURL)
@@ -0,0 +1,144 @@
package handlers
import (
"bytes"
"database/sql"
"net/http"
"net/http/httptest"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/gin-gonic/gin"
)
// ─────────────────────────────────────────────────────────────────────────────
// BundleHandler Import — JSON binding error cases
// ─────────────────────────────────────────────────────────────────────────────
func TestBundleImport_InvalidJSON(t *testing.T) {
h := NewBundleHandler(nil, nil, "http://localhost:8080", t.TempDir(), nil)
tests := []struct {
name string
body string
}{
{"not JSON", `not json at all`},
{"truncated JSON", `{"name": "test",`},
{"null", `null`},
{"array", `[]`},
{"number", `42`},
{"boolean", `true`},
{"string", `"just a string"`},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("POST", "/bundles/import", bytes.NewBufferString(tc.body))
c.Request.Header.Set("Content-Type", "application/json")
h.Import(c)
if w.Code != http.StatusBadRequest {
t.Errorf("invalid JSON %q: expected status %d, got %d", tc.body, http.StatusBadRequest, w.Code)
}
})
}
}
// ─────────────────────────────────────────────────────────────────────────────
// BundleHandler Import — valid JSON routes to bundle.Import and returns 201
// ─────────────────────────────────────────────────────────────────────────────
func TestBundleImport_ValidJSON(t *testing.T) {
mock := setupTestDB(t)
broadcaster := newTestBroadcaster()
h := NewBundleHandler(broadcaster, nil, "http://localhost:8080", t.TempDir(), nil)
// bundle.Import does: INSERT workspaces (creates record), UPDATE runtime (after
// parsing config.yaml), plus a RecordAndBroadcast (not a DB call). SubWorkspaces
// recursion is a no-op for this test bundle. No workspace_schedules or
// workspace_secrets INSERT in the current importer.
mock.ExpectExec("INSERT INTO workspaces").
WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectExec("UPDATE workspaces SET runtime").
WillReturnResult(sqlmock.NewResult(0, 1))
body := `{"name": "test-workspace", "schema": "1.0", "tier": 3}`
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("POST", "/bundles/import", bytes.NewBufferString(body))
c.Request.Header.Set("Content-Type", "application/json")
h.Import(c)
if w.Code != http.StatusCreated {
t.Errorf("valid JSON: expected status %d, got %d: %s", http.StatusCreated, w.Code, w.Body.String())
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet sqlmock expectations: %v", err)
}
}
// ─────────────────────────────────────────────────────────────────────────────
// BundleHandler Export — workspace not found (ErrNoRows → 404)
// ─────────────────────────────────────────────────────────────────────────────
func TestBundleExport_NotFound(t *testing.T) {
mock := setupTestDB(t)
_ = setupTestRedis(t)
broadcaster := newTestBroadcaster()
h := NewBundleHandler(broadcaster, nil, "http://localhost:8080", t.TempDir(), nil)
// bundle.Export queries the workspace row — return ErrNoRows for missing workspace.
mock.ExpectQuery(`SELECT name, COALESCE\(role`).
WithArgs("ws-nonexistent").
WillReturnError(sql.ErrNoRows)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "ws-nonexistent"}}
c.Request = httptest.NewRequest("GET", "/bundles/export/ws-nonexistent", nil)
h.Export(c)
if w.Code != http.StatusNotFound {
t.Errorf("expected status %d, got %d: %s", http.StatusNotFound, w.Code, w.Body.String())
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet sqlmock expectations: %v", err)
}
}
// ─────────────────────────────────────────────────────────────────────────────
// BundleHandler Export — query error (DB error → 404, per bundle.Export semantics)
// ─────────────────────────────────────────────────────────────────────────────
func TestBundleExport_QueryError(t *testing.T) {
mock := setupTestDB(t)
_ = setupTestRedis(t)
broadcaster := newTestBroadcaster()
h := NewBundleHandler(broadcaster, nil, "http://localhost:8080", t.TempDir(), nil)
// Simulate a non-ErrNoRows DB error.
mock.ExpectQuery(`SELECT name, COALESCE\(role`).
WithArgs("ws-error").
WillReturnError(sql.ErrConnDone)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "ws-error"}}
c.Request = httptest.NewRequest("GET", "/bundles/export/ws-error", nil)
h.Export(c)
// bundle.Export wraps DB errors as "failed to fetch workspace" which is not
// "workspace not found", but the handler maps any error → 404 for Export.
if w.Code != http.StatusNotFound {
t.Errorf("expected status %d for DB error, got %d: %s", http.StatusNotFound, w.Code, w.Body.String())
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet sqlmock expectations: %v", err)
}
}
@@ -645,6 +645,9 @@ func (h *DelegationHandler) ListDelegations(c *gin.Context) {
}
delegations = append(delegations, entry)
}
if err := rows.Err(); err != nil {
log.Printf("ListDelegations scan error: %v", err)
}
if delegations == nil {
delegations = []map[string]interface{}{}
@@ -352,6 +352,9 @@ func queryPeerMaps(query string, args ...interface{}) ([]map[string]interface{},
result = append(result, peer)
}
if err := rows.Err(); err != nil {
log.Printf("queryPeerMaps scan error: %v", err)
}
return result, nil
}
@@ -49,6 +49,9 @@ func (h *EventsHandler) List(c *gin.Context) {
"created_at": createdAt,
})
}
if err := rows.Err(); err != nil {
log.Printf("ListEvents scan error: %v", err)
}
c.JSON(http.StatusOK, events)
}
@@ -87,5 +90,8 @@ func (h *EventsHandler) ListByWorkspace(c *gin.Context) {
"created_at": createdAt,
})
}
if err := rows.Err(); err != nil {
log.Printf("ListEventsByWorkspace scan error: %v", err)
}
c.JSON(http.StatusOK, events)
}
@@ -248,6 +248,9 @@ func (h *InstructionsHandler) Resolve(c *gin.Context) {
b.WriteString(content)
b.WriteString("\n\n")
}
if err := rows.Err(); err != nil {
log.Printf("ListInstructions scan error: %v", err)
}
c.JSON(http.StatusOK, gin.H{
"workspace_id": workspaceID,
@@ -258,6 +261,7 @@ func (h *InstructionsHandler) Resolve(c *gin.Context) {
func scanInstructions(rows interface {
Next() bool
Scan(dest ...interface{}) error
Err() error
}) []Instruction {
var instructions []Instruction
for rows.Next() {
@@ -269,6 +273,9 @@ func scanInstructions(rows interface {
}
instructions = append(instructions, inst)
}
if err := rows.Err(); err != nil {
log.Printf("Instructions scan loop error: %v", err)
}
if instructions == nil {
instructions = []Instruction{}
}
@@ -63,6 +63,9 @@ func (h *SecretsHandler) List(c *gin.Context) {
"updated_at": updatedAt,
})
}
if err := rows.Err(); err != nil {
log.Printf("ListSecrets scan error: %v", err)
}
// 2. Global secrets not overridden at workspace level
globalRows, err := db.DB.QueryContext(ctx,
@@ -324,6 +327,9 @@ func (h *SecretsHandler) ListGlobal(c *gin.Context) {
"scope": "global",
})
}
if err := rows.Err(); err != nil {
log.Printf("ListGlobalSecrets scan error: %v", err)
}
c.JSON(http.StatusOK, secrets)
}
@@ -400,6 +406,9 @@ func (h *SecretsHandler) restartAllAffectedByGlobalKey(key string) {
ids = append(ids, id)
}
}
if err := rows.Err(); err != nil {
log.Printf("notifyGlobalSecretChange scan error: %v", err)
}
if len(ids) == 0 {
return
}