Skip to content

test(frontend): add unit tests for @agenta/shared and @agenta/annotation packages#4539

Open
bekossy wants to merge 6 commits into
release/v0.102.0from
fe-test/add-unit-tests-shared-annotation-packages
Open

test(frontend): add unit tests for @agenta/shared and @agenta/annotation packages#4539
bekossy wants to merge 6 commits into
release/v0.102.0from
fe-test/add-unit-tests-shared-annotation-packages

Conversation

@bekossy
Copy link
Copy Markdown
Member

@bekossy bekossy commented Jun 3, 2026

Context

@agenta/shared and @agenta/annotation had no unit test infrastructure. Pure utility functions — formatters, validators, slug helpers, path traversal — and annotation state helpers were only exercised end-to-end, making regressions invisible until they hit the UI.

Changes

Adds Vitest with coverage reporting to both packages and 267 unit tests covering their core pure functions.

@agenta/shared (189 tests): validators and UUID converters, slug generation and parsing, number/latency/token formatters, getValueAtPath / setValueAtPath / deleteValueAtPath (including JSON-string traversal), validateTemplateVariable / extractTemplateExpression, and API error / metadata stripping utilities.

@agenta/annotation (78 tests): queue-scoped annotation selection, testcase tag merging, testset sync preview, row remapping and export helpers, and annotation form field extraction.

The @agenta/annotation vitest config stubs @agenta/ui so tests run in a fast Node environment — the real package pulls in antd and causes the transformer to time out.

The template-variable tests reflect the post-mustache QA decision: any well-formed $.x is valid in the playground; the root becomes a testcase column and slot mismatches surface as API errors at runtime rather than UI validation errors.

Tests

  • pnpm --filter @agenta/shared test:unit — 189/189 pass
  • pnpm --filter @agenta/annotation test:unit — 78/78 pass

🤖 Generated with Claude Code

- Created unit tests for data transformation utilities including error extraction, response status preservation, and metadata stripping.
- Added tests for formatting utilities covering number, currency, latency, and percentage formatting.
- Implemented tests for path utilities to validate object navigation and manipulation.
- Developed tests for slug generation and validation functions.
- Added tests for template variable validation and extraction.
- Included tests for various validators including UUID and HTTP URL validation.
- Configured Vitest for running tests with coverage reporting and JUnit output.
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jun 3, 2026
@vercel
Copy link
Copy Markdown

vercel Bot commented Jun 3, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
agenta-documentation Ready Ready Preview, Comment Jun 5, 2026 9:58am

Request Review

@dosubot dosubot Bot added the tests label Jun 3, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 3, 2026

Review Change Stack

📝 Walkthrough

Walkthrough

Adds Vitest configs, package script/devDependency updates, a lightweight @agenta/ui test mock, .gitignore entries for Vitest output, and extensive Vitest unit tests for annotation and shared utility code.

Changes

Test Infrastructure Setup

Layer / File(s) Summary
Vitest configuration and package metadata
web/packages/agenta-annotation/package.json, web/packages/agenta-shared/package.json, web/packages/agenta-annotation/vitest.config.ts, web/packages/agenta-shared/vitest.config.ts
Adds vitest.config.ts to both packages configuring Node environment, test discovery to tests/unit/**/*.test.ts, JUnit reporting to ./test-results/junit.xml, and v8 coverage collection excluding src/**/index.ts. Updates package.json scripts with lint, test, test:unit, test:watch, test:coverage, and check commands. Adds @vitest/coverage-v8 and vitest devDependencies while keeping TypeScript at 5.8.3.
Test mocks and gitignore
web/packages/agenta-annotation/tests/__mocks__/agenta-ui.ts, web/packages/agenta-annotation/.gitignore, web/packages/agenta-shared/.gitignore
Creates a lightweight @agenta/ui mock for node tests and updates .gitignore files to ignore test-results/ and coverage/.

Annotation Package Unit Tests

Layer / File(s) Summary
Annotation form helpers
web/packages/agenta-annotation/tests/unit/annotation-form-helpers.test.ts
Tests for isEmptyValue, getOutputsSchema, getMetricFieldsFromEvaluator (scalar/array/anyOf/enum handling), and getMetricsFromAnnotation (schema-based flattening and schema-free inference).
Testset sync operations
web/packages/agenta-annotation/tests/unit/testset-sync.test.ts
Tests for queue tag formatting/merging, queue-scoped annotation selection with conflict detection, evaluator column key resolution, buildTestsetSyncOperations, remapTargetRowsToBaseRevision, buildTraceTestsetRows, buildTestcaseExportRows, and buildTestsetSyncPreview conflict/row grouping behavior.

Shared Package Utilities Unit Tests

Layer / File(s) Summary
Data transforms and API utilities
web/packages/agenta-shared/tests/unit/data-transforms.test.ts
Tests for extractApiErrorMessage, preserveResponseStatus, stripAgentaMetadataDeep, and stripEnhancedWrappers across nested and array inputs.
Formatters
web/packages/agenta-shared/tests/unit/formatters.test.ts
Tests for number/compact/currency/latency/tokens/percent/significant/preview formatters and createFormatter (multiplier/prefix/suffix/compact/fallback behaviors).
Path utilities
web/packages/agenta-shared/tests/unit/path-utils.test.ts
Tests for getValueAtPath, setValueAtPath, deleteValueAtPath, and hasValueAtPath including JSON-string traversal and immutable mutations.
Slug utilities
web/packages/agenta-shared/tests/unit/slug.test.ts
Tests for slugifyName, generate/strip/regenerate 4-char suffix helpers, isValidSlug, and gateway-tool slug build/parse helpers.
Template variables
web/packages/agenta-shared/tests/unit/template-variable.test.ts
Tests for validateTemplateVariable (JSONPath/JSON Pointer/plain forms), isValidTemplateVariable, and extractTemplateExpression wrapper stripping.
Validators and identifiers
web/packages/agenta-shared/tests/unit/validators-and-ids.test.ts
Tests for UUID validators (isValidUUID, validateUUID), isValidHttpUrl, isValidRegex, uuidToTraceId, uuidToSpanId, and removeTrailingSlash.

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 60.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding unit tests for two frontend packages with specific test counts and scope.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description clearly and directly relates to the changeset: adding Vitest unit test infrastructure to two packages with detailed breakdown of test coverage by module.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fe-test/add-unit-tests-shared-annotation-packages

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7f15b7fb2c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread web/packages/agenta-shared/test-results/junit.xml Outdated
…annotation packages

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jun 3, 2026
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
web/packages/agenta-annotation/test-results/junit.xml (1)

1-164: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Do not commit generated test result files.

JUnit XML test reports are runtime artifacts produced during test execution and should not be committed to version control. These files:

  • Change on every test run with new timestamps and execution times
  • Are automatically regenerated in CI/CD pipelines
  • Pollute the repository history with ephemeral data

Please add test-results/ to your .gitignore and remove this file from the commit.

🔧 Recommended action
  1. Remove the file from git:
git rm web/packages/agenta-annotation/test-results/junit.xml
  1. Add to .gitignore (if not already present):
# Test artifacts
**/test-results/
  1. The file will be regenerated locally when running tests and in CI/CD as needed.
web/packages/agenta-shared/test-results/junit.xml (1)

1-390: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Do not commit generated test result files.

JUnit XML test reports are runtime artifacts produced during test execution and should not be committed to version control. These files:

  • Change on every test run with new timestamps and execution times
  • Are automatically regenerated in CI/CD pipelines
  • Pollute the repository history with ephemeral data

Please add test-results/ to your .gitignore and remove this file from the commit.

🔧 Recommended action
  1. Remove the file from git:
git rm web/packages/agenta-shared/test-results/junit.xml
  1. Add to .gitignore (if not already present):
# Test artifacts
**/test-results/
  1. The file will be regenerated locally when running tests and in CI/CD as needed.
🧹 Nitpick comments (1)
web/packages/agenta-shared/tests/unit/slug.test.ts (1)

69-73: ⚡ Quick win

Make random-suffix tests deterministic to avoid future flakiness.

Line 69 and Line 135 currently rely on probabilistic behavior. If Math.random is stubbed globally in another test, these can become brittle. Prefer mocking randomness in this suite and asserting exact outputs.

Proposed deterministic test pattern
 import {describe, expect, it} from "vitest"
+import {vi} from "vitest"

 describe("generateSlugWithSuffix", () => {
-    it("produces different slugs on repeated calls (randomness)", () => {
-        const slugs = new Set(Array.from({length: 10}, () => generateSlugWithSuffix("app")))
-        // With 36^4 = ~1.7M possibilities, collision probability over 10 draws is negligible
-        expect(slugs.size).toBeGreaterThan(1)
+    it("produces expected format with deterministic random source", () => {
+        const spy = vi.spyOn(Math, "random").mockReturnValue(0.123456)
+        const slug = generateSlugWithSuffix("app")
+        expect(slug).toMatch(/^app-[a-z0-9]{4}$/)
+        spy.mockRestore()
     })
 })

Also applies to: 135-140


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ca32a0b2-ecee-442d-b886-84dda4dcadbb

📥 Commits

Reviewing files that changed from the base of the PR and between 8859bf2 and 7f15b7f.

⛔ Files ignored due to path filters (1)
  • web/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (15)
  • web/packages/agenta-annotation/package.json
  • web/packages/agenta-annotation/test-results/junit.xml
  • web/packages/agenta-annotation/tests/__mocks__/agenta-ui.ts
  • web/packages/agenta-annotation/tests/unit/annotation-form-helpers.test.ts
  • web/packages/agenta-annotation/tests/unit/testset-sync.test.ts
  • web/packages/agenta-annotation/vitest.config.ts
  • web/packages/agenta-shared/package.json
  • web/packages/agenta-shared/test-results/junit.xml
  • web/packages/agenta-shared/tests/unit/data-transforms.test.ts
  • web/packages/agenta-shared/tests/unit/formatters.test.ts
  • web/packages/agenta-shared/tests/unit/path-utils.test.ts
  • web/packages/agenta-shared/tests/unit/slug.test.ts
  • web/packages/agenta-shared/tests/unit/template-variable.test.ts
  • web/packages/agenta-shared/tests/unit/validators-and-ids.test.ts
  • web/packages/agenta-shared/vitest.config.ts

Comment thread web/packages/agenta-annotation/tests/unit/annotation-form-helpers.test.ts Outdated
Comment thread web/packages/agenta-annotation/tests/unit/testset-sync.test.ts Outdated
Comment thread web/packages/agenta-shared/tests/unit/path-utils.test.ts
Comment thread web/packages/agenta-shared/tests/unit/template-variable.test.ts Outdated
…verage, template-variable alignment

- Replace `as any` fixture casts with `as unknown as T` in annotation tests
- Fix incorrect Annotation import source in testset-sync (now from @agenta/entities/annotation)
- Add Testcase type import and remove all as-any call-site casts in testset-sync
- Add falsy-root short-circuit tests for getValueAtPath (0, false, "", null)
- Realign template-variable tests to the strict envelope-slot behavior on main

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Jun 3, 2026

Railway Preview Environment

Preview URL https://gateway-production-c475.up.railway.app/w
Project agenta-oss-pr-4539
Image tag pr-4539-d9e2e52
Status Deployed
Railway logs Open logs
Workflow logs View workflow run
Updated at 2026-06-04T09:28:11.889Z

@bekossy bekossy changed the base branch from main to release/v0.102.0 June 5, 2026 09:32
…SONPath policy

The release/v0.102.0 merge updated validateTemplateVariable to accept any
well-formed $.x expression without checking against known envelope slots
(post-mustache QA: slot mismatches surface as API errors, not UI errors).
Five tests still asserted the old strict behavior and were failing. Updated
them to match the intentional permissive policy documented in the source.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:M This PR changes 30-99 lines, ignoring generated files. tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants