fix(i18n): preserve remaining Vietnamese localization (#7935)

* fix(i18n): preserve remaining Vietnamese localization

* chore(quality): rebaseline file-size cap for 9 dashboard components (i18n wiring)

Restoring the Vietnamese localization on 9 dashboard components (useTranslations
wiring + t()/tc() call-site swaps for previously hardcoded strings) grows each
file by a small, irreducible amount. Bumps the frozen file-size-baseline.json
caps to match, with a justification entry per the project's own ratchet policy.

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

* fix(i18n): wire weekday localization + add missing qwen CLI description

Two gaps left by this PR's own new contract tests, caught while
reconciling the branch against the release tip:

- CostOverviewTab.tsx added formatWeekdayLabel() but never called it;
  the Weekly Usage Pattern chart still showed raw English day
  abbreviations regardless of locale. Now maps weeklyPattern rows
  through it before handing them to WeeklyPatternCard.
- cliTools.toolDescriptions was missing an entry for "qwen" (a
  baseUrlSupport:"full" tool) in both en.json and vi.json, failing
  the PR's own cli-catalog-display-contract.test.ts.

Covered by the PR's existing tests/unit/dashboard-localization-contract.test.ts
and tests/unit/cli-catalog-display-contract.test.ts (both now pass).

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

* i18n(vi): backfill the 4 proxySubscription keys #7299 added to en.json

#7299 (proxy subscriptions) merged while this branch was rebasing, adding
settings.proxySubscriptionsTab and settings.proxySubscription.error.{LOCAL_CORE_ENDPOINT_INVALID,
NEEDS_CORE_NOT_CONFIGURED,NO_USABLE_NODES} to en.json. This PR's own
i18n-vi-completeness contract asserts full en↔vi key parity, so the merge of the
current release tip surfaced them as missing. Adds the Vietnamese translations,
keeping the SS/VMess/Trojan/VLESS/SOCKS5 technical terms verbatim.

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

---------

Co-authored-by: nguyenha935 <208228297+nguyenha935@users.noreply.github.com>
Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouza.pw@gmail.com>
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
Co-authored-by: nguyenha935 <nguyenha935@users.noreply.github.com>
This commit is contained in:
nguyenha935
2026-07-21 23:41:02 +07:00
committed by GitHub
parent eab59d4048
commit 4012bac41d
207 changed files with 12021 additions and 5221 deletions

View File

@@ -0,0 +1,35 @@
import assert from "node:assert/strict";
import { existsSync } from "node:fs";
import test from "node:test";
import en from "../../src/i18n/messages/en.json" with { type: "json" };
import vi from "../../src/i18n/messages/vi.json" with { type: "json" };
import { CLI_TOOLS } from "../../src/shared/constants/cliTools";
test("every CLI catalog image points to a bundled public asset", () => {
const missing = Object.values(CLI_TOOLS).flatMap((tool) =>
[tool.image, tool.imageLight, tool.imageDark]
.filter((asset): asset is string => Boolean(asset))
.filter((asset) => !existsSync(`public${asset}`))
.map((asset) => `${tool.id}: ${asset}`)
);
assert.deepEqual(missing, []);
});
test("every visible CLI catalog entry has English and Vietnamese descriptions", () => {
const visibleToolIds = Object.values(CLI_TOOLS)
.filter((tool) => tool.baseUrlSupport !== "none")
.map((tool) => tool.id);
const englishDescriptions = en.cliTools.toolDescriptions as Record<string, string>;
const vietnameseDescriptions = vi.cliTools.toolDescriptions as Record<string, string>;
assert.deepEqual(
visibleToolIds.filter((id) => !englishDescriptions[id]?.trim()),
[]
);
assert.deepEqual(
visibleToolIds.filter((id) => !vietnameseDescriptions[id]?.trim()),
[]
);
});

View File

@@ -0,0 +1,199 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
function readSource(path: string): string {
return readFileSync(path, "utf8");
}
test("shared provider playground uses localized visible copy", () => {
const source = readSource(
"src/app/(dashboard)/dashboard/media-providers/components/LlmChatCard.tsx"
);
for (const rawText of [
"Send a message to start the conversation",
"Shift+Enter for newline",
">Clear<",
'title="Stop"',
]) {
assert.equal(source.includes(rawText), false, `raw playground copy: ${rawText}`);
}
});
test("CLI guide fallback checks key existence before translating", () => {
const source = readSource(
"src/app/(dashboard)/dashboard/cli-code/components/DefaultToolCard.tsx"
);
assert.match(source, /if \(!t\.has\(key\)\) return fallback;/);
});
test("known provider PNGs resolve locally before the external CDN", () => {
const source = readSource("src/shared/components/ProviderIcon.tsx");
assert.match(source, /"poe-web": "poe"/);
assert.match(source, /"opencode-go": "opencode"/);
assert.match(source, /"opencode-zen": "opencode"/);
assert.ok(source.indexOf("if (hasPng && !pngFailed)") < source.indexOf("if (!theSvgFailed)"));
});
test("provider onboarding renders provider logos instead of treating catalog ids as glyphs", () => {
const source = readSource(
"src/app/(dashboard)/dashboard/providers/components/onboarding/ProviderOnboardingWizard.tsx"
);
assert.match(source, /<ProviderIcon/);
assert.equal(source.includes("{option.icon}"), false);
});
test("shared empty states render Material Symbol ids as icons", () => {
const source = readSource("src/shared/components/EmptyState.tsx");
assert.match(source, /usesMaterialSymbol/);
assert.match(source, /className="material-symbols-outlined"/);
});
test("compression engine pages localize API-driven labels and normalize icon ids", () => {
const source = readSource("src/shared/components/compression/EngineConfigPage.tsx");
assert.match(source, /useTranslations\("compressionEngineConfig"\)/);
assert.match(source, /brain: "psychology"/);
assert.equal(source.includes(">Last 7 days<"), false);
assert.equal(source.includes("Turn this layer on/off"), false);
});
test("budget management does not expose deferred English-only states", () => {
const source = readSource("src/app/(dashboard)/dashboard/usage/components/BudgetTab.tsx");
for (const rawText of [
">Budget<",
">Templates:<",
">Projection<",
">Cost breakdown (30d)<",
">Limits<",
">Daily<",
"No keys selected",
"Failed to apply template",
]) {
assert.equal(source.includes(rawText), false, `raw budget copy: ${rawText}`);
}
});
test("feature-flag descriptions are localized without changing flag values", () => {
const card = readSource("src/app/(dashboard)/dashboard/settings/components/FeatureFlagCard.tsx");
const messages = JSON.parse(readSource("src/i18n/messages/vi.json"));
assert.match(card, /enumValues\.\$\{val\}/);
assert.ok(messages.featureFlags.definitions.REQUIRE_API_KEY.description.includes("khóa API"));
assert.ok(
messages.featureFlags.definitions.OMNIROUTE_AUTO_SYNC_CLAUDE_PROFILES.description.includes(
"Claude Code"
)
);
});
test("analytics charts localize calendar, account, and diversity labels", () => {
const sources = [
readSource("src/shared/components/analytics/charts.tsx"),
readSource("src/shared/components/analytics/rechartsDonuts.tsx"),
readSource("src/app/(dashboard)/dashboard/analytics/components/DiversityScoreCard.tsx"),
].join("\n");
for (const rawText of [
">Less<",
">More<",
">Most Active Day<",
">By Account<",
">By API Key<",
'"Healthy Distribution"',
]) {
assert.equal(sources.includes(rawText), false, `raw analytics copy: ${rawText}`);
}
});
test("no-auth provider controls contain no raw English headings", () => {
const sources = [
readSource("src/shared/components/NoAuthAccountCard.tsx"),
readSource("src/shared/components/NoAuthProviderCard.tsx"),
].join("\n");
assert.equal(sources.includes(">No authentication required<"), false);
assert.equal(sources.includes(">Configure proxy<"), false);
assert.equal(sources.includes(">Remove account<"), false);
});
test("Vietnamese navigation preserves engine and product names", () => {
const messages = JSON.parse(readSource("src/i18n/messages/vi.json"));
assert.equal(messages.sidebar.contextLite, "Lite");
assert.equal(messages.sidebar.contextAggressive, "Aggressive");
assert.equal(messages.sidebar.contextHeadroom, "Headroom");
assert.equal(messages.sidebar.contextSessionDedup, "Session Dedup");
assert.equal(messages.sidebar.compressionStudio, "Compression Studio");
assert.equal(messages.sidebar.cliCode, "CLI Code");
assert.equal(messages.sidebar.trafficInspector, "Traffic Inspector");
});
test("CLI cards use packaged brand icons whenever an asset exists", () => {
const catalog = readSource("src/shared/constants/cliTools.ts");
for (const image of [
"/providers/claude.svg",
"/providers/codex.svg",
"/providers/cline.svg",
"/providers/qwen.svg",
"/providers/cursor.svg",
"/providers/roocode.svg",
"/providers/deepseek.svg",
]) {
assert.ok(catalog.includes(`image: "${image}"`), `missing CLI icon mapping: ${image}`);
}
const card = readSource("src/shared/components/cli/CliToolCard.tsx");
assert.match(card, /tool\.imageDark \|\| tool\.imageLight/);
assert.match(card, /tool\.imageLight \|\| tool\.imageDark/);
});
test("changelog and settings breadcrumbs use localized labels", () => {
const changelog = [
readSource("src/app/(dashboard)/dashboard/changelog/page.tsx"),
readSource("src/app/(dashboard)/dashboard/changelog/components/NewsViewer.tsx"),
readSource("src/app/(dashboard)/dashboard/changelog/components/ChangelogViewer.tsx"),
].join("\n");
for (const rawText of [
'label: "News"',
'label: "Changelog"',
"No new announcements at this time.",
"Could not load the changelog.",
"View Full History on GitHub",
]) {
assert.equal(changelog.includes(rawText), false, `raw changelog copy: ${rawText}`);
}
const breadcrumbs = readSource("src/shared/components/Breadcrumbs.tsx");
assert.match(breadcrumbs, /general: "general"/);
assert.match(breadcrumbs, /"feature-flags": "featureFlags"/);
});
test("production audit regressions stay localized and provider icons stay bounded", () => {
const costs = readSource("src/app/(dashboard)/dashboard/costs/CostOverviewTab.tsx");
assert.match(costs, /formatWeekdayLabel\(row\.day, locale\)/);
assert.equal(costs.includes("} tokens`"), false);
const storage = [
readSource("src/app/(dashboard)/dashboard/settings/components/SystemStorageTab.tsx"),
readSource("src/app/(dashboard)/dashboard/settings/components/DatabaseBackupRetentionCard.tsx"),
].join("\n");
for (const rawText of [
">Database Statistics<",
"Automatic SQLite backups are stored",
">Keep latest backups<",
">Save retention<",
]) {
assert.equal(storage.includes(rawText), false, `raw storage copy: ${rawText}`);
}
const endpoint = readSource("src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.tsx");
for (const rawText of [
'label: "Context Sources"',
">Active Endpoints<",
">Running<",
">Tunnels<",
">Not configured<",
]) {
assert.equal(endpoint.includes(rawText), false, `raw endpoint copy: ${rawText}`);
}
const security = readSource("src/app/(dashboard)/dashboard/settings/components/SecurityTab.tsx");
assert.match(security, /<ProviderIcon/);
assert.equal(security.includes('{isBlocked ? "block" : provider.icon}'), false);
});

View File

@@ -10,15 +10,16 @@ test("analytics page exposes the restored analytics tab shell", () => {
const source = readSource("src/app/(dashboard)/dashboard/analytics/page.tsx");
assert.ok(source.includes('role="tablist"'));
assert.ok(source.includes('aria-label="Analytics sections"'));
for (const label of [
"Overview",
"Evals",
"Search",
"Utilization",
"Combo Health",
"Route Trace",
assert.ok(source.includes('aria-label={t("sectionsAria")}'));
for (const [labelKey, label] of [
["overview", "Overview"],
["evals", "Evals"],
["search", "Search"],
["utilization", "Utilization"],
["comboHealth", "Combo Health"],
["routeTrace", "Route Trace"],
]) {
assert.ok(source.includes('labelKey: "' + labelKey + '"'));
assert.ok(source.includes('label: "' + label + '"'));
}
for (const tabId of [
@@ -36,13 +37,16 @@ test("analytics page exposes the restored analytics tab shell", () => {
test("endpoint page keeps APIs, MCP, and A2A as in-page tabs", () => {
const source = readSource("src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.tsx");
assert.ok(source.includes('type EndpointTab = "apis" | "mcp" | "a2a"'));
for (const label of ["APIs", "MCP", "A2A"]) {
assert.ok(source.includes('label: "' + label + '"'));
assert.ok(source.includes('type EndpointTab = "apis" | "mcp" | "a2a" | "context-sources"'));
for (const labelKey of ["tabApis", "tabMcp", "tabA2a", "tabContextSources"]) {
assert.ok(source.includes('labelKey: "' + labelKey + '"'));
}
assert.ok(source.includes("label: t(tab.labelKey)"));
assert.ok(source.includes('aria-label={t("endpointSections")}'));
assert.ok(source.includes('useState<EndpointTab>("apis")'));
assert.ok(source.includes('activeEndpointTab === "mcp" ? <McpDashboardPage /> : null'));
assert.ok(source.includes('activeEndpointTab === "a2a" ? <A2ADashboardPage /> : null'));
assert.ok(source.includes('activeEndpointTab === "context-sources"'));
});
test("endpoint page exposes context-sources tab with Notion and Obsidian source cards", () => {
@@ -53,7 +57,7 @@ test("endpoint page exposes context-sources tab with Notion and Obsidian source
// Verify context-sources tab label is in ENDPOINT_TABS
assert.ok(
source.includes('{ value: "context-sources", label: "Context Sources", icon: "database" }')
source.includes('{ value: "context-sources", labelKey: "tabContextSources", icon: "database" }')
);
// Verify both source card components are imported

View File

@@ -0,0 +1,51 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import en from "../../src/i18n/messages/en.json" with { type: "json" };
import vi from "../../src/i18n/messages/vi.json" with { type: "json" };
import { BUILTIN_BADGES } from "../../src/lib/gamification/badges";
const profileSource = readFileSync("src/app/(dashboard)/dashboard/profile/page.tsx", "utf8");
const tokensSource = readFileSync("src/app/(dashboard)/dashboard/tokens/page.tsx", "utf8");
const topListSource = readFileSync(
"src/app/(dashboard)/dashboard/costs/components/TopListCard.tsx",
"utf8"
);
const englishBadges = en.gamification.badges as Record<string, Record<string, string>>;
const vietnameseBadges = vi.gamification.badges as Record<string, Record<string, string>>;
test("every built-in badge has complete English and Vietnamese display copy", () => {
for (const badge of BUILTIN_BADGES) {
for (const field of ["name", "description", "criteria"] as const) {
const englishValue = englishBadges[badge.id]?.[field];
const vietnameseValue = vietnameseBadges[badge.id]?.[field];
assert.ok(englishValue?.trim(), `en missing gamification.badges.${badge.id}.${field}`);
assert.ok(vietnameseValue?.trim(), `vi missing gamification.badges.${badge.id}.${field}`);
}
}
});
test("profile renders mapped icons and localized badge criteria", () => {
assert.match(profileSource, /function BadgeIcon/);
assert.match(profileSource, /translateBadge\(selectedBadge, "criteria"\)/);
assert.doesNotMatch(profileSource, /<p className="text-sm">\{selectedBadge\.criteria\}<\/p>/);
});
test("token page no longer contains known raw English controls", () => {
for (const rawText of [
"Send Tokens",
"Create Invite",
"Connect Server",
"No servers connected",
"Last sync:",
"Disconnect",
]) {
assert.equal(tokensSource.includes(`>${rawText}<`), false, `raw token copy: ${rawText}`);
}
});
test("cost list component receives its localized legacy-free label", () => {
assert.match(topListSource, /legacyFreeLabel: string;/);
assert.match(topListSource, /\{legacyFreeLabel\}/);
});

View File

@@ -1,4 +1,5 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { parse } from "@formatjs/icu-messageformat-parser";
@@ -81,3 +82,17 @@ test("Vietnamese locale introduces no ICU parse regression", () => {
});
assert.deepEqual(regressions, []);
});
test("no-auth provider controls keep locale translators unambiguous", () => {
const source = readFileSync(
new URL(
"../../src/app/(dashboard)/dashboard/providers/[id]/components/NoAuthProviderControls.tsx",
import.meta.url
),
"utf8"
);
assert.equal(source.match(/import \{ useTranslations \} from "next-intl";/g)?.length, 1);
assert.match(source, /const noAuthT = useTranslations\("noAuthProvider"\);/);
assert.match(source, /const t = useTranslations\("providers"\);/);
});

View File

@@ -17,6 +17,8 @@ import React from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { NextIntlClientProvider } from "next-intl";
import messages from "../../../src/i18n/messages/en.json";
// ── Mocks ─────────────────────────────────────────────────────────────────────
@@ -43,9 +45,7 @@ import CompressionHub from "../../../src/app/(dashboard)/dashboard/context/combo
// ── Helpers ───────────────────────────────────────────────────────────────────
function getLastPutBody(): Record<string, unknown> | null {
const putCall = [...fetchCalls].reverse().find(
(c) => c.init?.method === "PUT"
);
const putCall = [...fetchCalls].reverse().find((c) => c.init?.method === "PUT");
if (!putCall) return null;
return JSON.parse(putCall.init.body as string);
}
@@ -95,13 +95,19 @@ describe("CompressionHub — PUT sends patch only, not full settings", () => {
});
afterEach(() => {
act(() => { root.unmount(); });
act(() => {
root.unmount();
});
document.body.removeChild(container);
});
it("sends only the changed field when activeComboId is updated", async () => {
await act(async () => {
root.render(<CompressionHub />);
root.render(
<NextIntlClientProvider locale="en" messages={{ contextCombos: messages.contextCombos }}>
<CompressionHub />
</NextIntlClientProvider>
);
});
// Find the combo selector and change it to "c1"
@@ -131,7 +137,11 @@ describe("CompressionHub — PUT sends patch only, not full settings", () => {
it("sends only the toggle field when contextEditing is toggled", async () => {
await act(async () => {
root.render(<CompressionHub />);
root.render(
<NextIntlClientProvider locale="en" messages={{ contextCombos: messages.contextCombos }}>
<CompressionHub />
</NextIntlClientProvider>
);
});
// Find the context editing toggle button

View File

@@ -7,10 +7,11 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { NextIntlClientProvider } from "next-intl";
import messages from "../../../src/i18n/messages/en.json";
const { CompressionPipelineEditor } = await import(
"../../../src/shared/components/compression/CompressionPipelineEditor"
);
const { CompressionPipelineEditor } =
await import("../../../src/shared/components/compression/CompressionPipelineEditor");
const TABLE = {
rtk: ["standard", "aggressive"],
@@ -34,11 +35,13 @@ afterEach(() => {
function render(steps: { engine: string; intensity?: string }[], onChange: (s: unknown) => void) {
act(() => {
root.render(
<CompressionPipelineEditor
steps={steps}
onChange={onChange}
engineIntensities={TABLE as unknown as Record<string, readonly string[]>}
/>
<NextIntlClientProvider locale="en" messages={{ contextCombos: messages.contextCombos }}>
<CompressionPipelineEditor
steps={steps}
onChange={onChange}
engineIntensities={TABLE as unknown as Record<string, readonly string[]>}
/>
</NextIntlClientProvider>
);
});
}
@@ -63,7 +66,9 @@ describe("CompressionPipelineEditor (T06)", () => {
render([{ engine: "rtk", intensity: "standard" }], (s) => {
received = s as typeof received;
});
const addBtn = container.querySelector('[data-testid="pipeline-add-step"]') as HTMLButtonElement;
const addBtn = container.querySelector(
'[data-testid="pipeline-add-step"]'
) as HTMLButtonElement;
act(() => addBtn.dispatchEvent(new MouseEvent("click", { bubbles: true })));
expect(received).not.toBeNull();
expect(received!.length).toBe(2);

View File

@@ -2,6 +2,8 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from "vitest";
import { NextIntlClientProvider } from "next-intl";
import messages from "../../../src/i18n/messages/en.json";
import type { CompressionRunModel } from "@/app/(dashboard)/dashboard/compression/studio/compressionFlowModel";
// ── Polyfill ResizeObserver (required by ReactFlow) ───────────────────────
@@ -41,7 +43,14 @@ function mount(ui: React.ReactElement): HTMLElement {
containers.push(container);
const root = createRoot(container);
act(() => {
root.render(ui);
root.render(
<NextIntlClientProvider
locale="en"
messages={{ compressionStudio: messages.compressionStudio }}
>
{ui}
</NextIntlClientProvider>
);
});
return container;
}

View File

@@ -2,6 +2,8 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { NextIntlClientProvider } from "next-intl";
import messages from "../../../src/i18n/messages/en.json";
const containers: HTMLElement[] = [];
const roots: Array<{ unmount: () => void }> = [];
@@ -13,13 +15,19 @@ function mount(ui: React.ReactElement): HTMLElement {
const root = createRoot(container);
roots.push(root);
act(() => {
root.render(ui);
root.render(
<NextIntlClientProvider locale="en" messages={{ contextCombos: messages.contextCombos }}>
{ui}
</NextIntlClientProvider>
);
});
return container;
}
beforeEach(() => {
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
(
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
});
afterEach(async () => {
@@ -89,9 +97,8 @@ function setSelectValue(select: HTMLSelectElement, value: string) {
describe("CompressionHub — active-profile selector", () => {
async function render() {
const { default: CompressionHub } = await import(
"../../../src/app/(dashboard)/dashboard/context/combos/CompressionHub"
);
const { default: CompressionHub } =
await import("../../../src/app/(dashboard)/dashboard/context/combos/CompressionHub");
let container!: HTMLElement;
await act(async () => {
container = mount(<CompressionHub />);
@@ -103,7 +110,9 @@ describe("CompressionHub — active-profile selector", () => {
it("renders the active-profile select with Default + each named combo", async () => {
setupFetchMock();
const container = await render();
const select = container.querySelector('[data-testid="active-profile-select"]') as HTMLSelectElement | null;
const select = container.querySelector(
'[data-testid="active-profile-select"]'
) as HTMLSelectElement | null;
expect(select).toBeTruthy();
expect(container.textContent).toContain("Default (from panel)");
expect(container.textContent).toContain("RTK only");
@@ -112,7 +121,9 @@ describe("CompressionHub — active-profile selector", () => {
it("changing the select to a combo PUTs activeComboId === that id", async () => {
const { puts } = setupFetchMock();
const container = await render();
const select = container.querySelector('[data-testid="active-profile-select"]') as HTMLSelectElement;
const select = container.querySelector(
'[data-testid="active-profile-select"]'
) as HTMLSelectElement;
await act(async () => {
setSelectValue(select, "c1");
});
@@ -128,7 +139,9 @@ describe("CompressionHub — active-profile selector", () => {
const preview = () => container.querySelector('[data-testid="active-profile-preview"]');
expect(preview()).toBeTruthy();
expect(preview()!.textContent).toContain("Default");
const select = container.querySelector('[data-testid="active-profile-select"]') as HTMLSelectElement;
const select = container.querySelector(
'[data-testid="active-profile-select"]'
) as HTMLSelectElement;
await act(async () => {
setSelectValue(select, "c1");
});

View File

@@ -2,6 +2,8 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { NextIntlClientProvider } from "next-intl";
import messages from "../../../src/i18n/messages/en.json";
// ── Helpers ───────────────────────────────────────────────────────────────
@@ -15,7 +17,11 @@ function mountInContainer(ui: React.ReactElement): HTMLElement {
const root = createRoot(container);
roots.push(root);
act(() => {
root.render(ui);
root.render(
<NextIntlClientProvider locale="en" messages={{ contextCombos: messages.contextCombos }}>
{ui}
</NextIntlClientProvider>
);
});
return container;
}
@@ -139,9 +145,6 @@ describe("CompressionHub — Context Editing", () => {
});
await flush();
// CompressionHub deliberately does NOT use useTranslations (see the
// hydration note at the top of CompressionHub.tsx) — its strings are
// literal English text, exactly like EngineConfigPage.
const text = container.textContent ?? "";
expect(text).toContain("Provider-delegated compression");
expect(text).toContain("Context Editing (Claude)");

View File

@@ -2,6 +2,8 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { NextIntlClientProvider } from "next-intl";
import messages from "../../../src/i18n/messages/en.json";
// ── Helpers ───────────────────────────────────────────────────────────────
@@ -15,7 +17,11 @@ function mountInContainer(ui: React.ReactElement): HTMLElement {
const root = createRoot(container);
roots.push(root);
act(() => {
root.render(ui);
root.render(
<NextIntlClientProvider locale="en" messages={{ contextCombos: messages.contextCombos }}>
{ui}
</NextIntlClientProvider>
);
});
return container;
}
@@ -119,58 +125,62 @@ describe("CompressionHub", () => {
// that the master toggle/mode selector/reorder buttons no longer render, is
// covered by compressionHub-active-selector.test.tsx.
it("INVARIANT #1: no per-layer control issues a PUT/POST to /api/context/combos/default", { timeout: 20000 }, async () => {
const comboWrites: { method: string }[] = [];
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json" },
});
vi.spyOn(globalThis, "fetch").mockImplementation(
async (input: RequestInfo | URL, init?: RequestInit) => {
const url = input.toString();
if (url.includes("/api/context/combos/default")) {
if (init?.method === "PUT" || init?.method === "POST") {
comboWrites.push({ method: init.method });
it(
"INVARIANT #1: no per-layer control issues a PUT/POST to /api/context/combos/default",
{ timeout: 20000 },
async () => {
const comboWrites: { method: string }[] = [];
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json" },
});
vi.spyOn(globalThis, "fetch").mockImplementation(
async (input: RequestInfo | URL, init?: RequestInit) => {
const url = input.toString();
if (url.includes("/api/context/combos/default")) {
if (init?.method === "PUT" || init?.method === "POST") {
comboWrites.push({ method: init.method });
}
return json({ id: "default", name: "Default", pipeline: [{ engine: "rtk" }] });
}
return json({ id: "default", name: "Default", pipeline: [{ engine: "rtk" }] });
if (url.includes("/api/settings/compression")) {
return json({ enabled: true, defaultMode: "stacked" });
}
if (url.includes("/api/compression/engines")) {
return json(enginePayload());
}
if (url.includes("/api/context/combos") || url.includes("/api/combos")) {
return json({ combos: [] });
}
if (url.includes("/api/compression/language-packs")) {
return json({ packs: [] });
}
return json({}, 404);
}
if (url.includes("/api/settings/compression")) {
return json({ enabled: true, defaultMode: "stacked" });
}
if (url.includes("/api/compression/engines")) {
return json(enginePayload());
}
if (url.includes("/api/context/combos") || url.includes("/api/combos")) {
return json({ combos: [] });
}
if (url.includes("/api/compression/language-packs")) {
return json({ packs: [] });
}
return json({}, 404);
}
);
);
const { default: CompressionHub } =
await import("../../../src/app/(dashboard)/dashboard/context/combos/CompressionHub");
const { default: CompressionHub } =
await import("../../../src/app/(dashboard)/dashboard/context/combos/CompressionHub");
let container!: HTMLElement;
await act(async () => {
container = mountInContainer(<CompressionHub />);
});
await flush();
// Click every on/off switch in the Hub (master + any layer controls that remain).
const switches = Array.from(container.querySelectorAll('[role="switch"]'));
for (const sw of switches) {
let container!: HTMLElement;
await act(async () => {
(sw as HTMLElement).click();
container = mountInContainer(<CompressionHub />);
});
await flush();
}
expect(comboWrites).toHaveLength(0);
});
// Click every on/off switch in the Hub (master + any layer controls that remain).
const switches = Array.from(container.querySelectorAll('[role="switch"]'));
for (const sw of switches) {
await act(async () => {
(sw as HTMLElement).click();
});
await flush();
}
expect(comboWrites).toHaveLength(0);
}
);
});
describe("CompressionCombosPageClient", () => {

View File

@@ -2,16 +2,14 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import {
ENGINE_IDS,
engineMeta,
} from "../../../open-sse/services/compression/engineCatalog.ts";
import { ENGINE_IDS } from "../../../open-sse/services/compression/engineCatalog.ts";
// i18n does not resolve to a real locale in vitest/jsdom, so mock next-intl to echo
// the key. This test therefore asserts ONLY on i18n-independent strings: catalog
// labels/descriptions, engine ids, data-testid hooks, and the PUT request body.
// the key. This test therefore asserts on translation keys, engine ids,
// data-testid hooks, and the PUT request body.
vi.mock("next-intl", () => ({
useTranslations: () => (key: string) => key,
useTranslations: () => (key: string, values?: Record<string, unknown>) =>
values ? `${key} ${Object.values(values).join(" ")}` : key,
useLocale: () => "en",
}));
@@ -125,9 +123,8 @@ function setupFetchMock(): { puts: CapturedPut[] } {
describe("CompressionPanel", () => {
it("renders a row for every engine id in the catalog", async () => {
setupFetchMock();
const { default: CompressionPanel } = await import(
"../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel"
);
const { default: CompressionPanel } =
await import("../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel");
let container!: HTMLElement;
await act(async () => {
@@ -138,16 +135,14 @@ describe("CompressionPanel", () => {
for (const id of ENGINE_IDS) {
const row = container.querySelector(`[data-testid="engine-row-${id}"]`);
expect(row, `expected a row for engine "${id}"`).toBeTruthy();
// Catalog label/description are hardcoded English (i18n-independent).
expect(container.textContent).toContain(engineMeta(id).label);
expect(container.textContent).toContain(`compressionEngine.${id}.label`);
}
});
it("shows the rtk level 'standard' as selected", async () => {
setupFetchMock();
const { default: CompressionPanel } = await import(
"../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel"
);
const { default: CompressionPanel } =
await import("../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel");
let container!: HTMLElement;
await act(async () => {
@@ -164,9 +159,8 @@ describe("CompressionPanel", () => {
it("toggling caveman PUTs engines.caveman.enabled === true", async () => {
const { puts } = setupFetchMock();
const { default: CompressionPanel } = await import(
"../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel"
);
const { default: CompressionPanel } =
await import("../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel");
let container!: HTMLElement;
await act(async () => {
@@ -202,9 +196,8 @@ describe("CompressionPanel", () => {
it("derived-pipeline preview reflects the enabled engines", async () => {
setupFetchMock();
const { default: CompressionPanel } = await import(
"../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel"
);
const { default: CompressionPanel } =
await import("../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel");
let container!: HTMLElement;
await act(async () => {

View File

@@ -2,10 +2,7 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import {
OUTPUT_STYLE_IDS,
outputStyleMeta,
} from "../../../open-sse/services/compression/outputStyles/catalog.ts";
import { OUTPUT_STYLE_IDS } from "../../../open-sse/services/compression/outputStyles/catalog.ts";
// Locale is mutable per-test so we can exercise the locale gate (terse-cjk → zh only).
const intl = vi.hoisted(() => ({ locale: "en" }));
@@ -28,8 +25,9 @@ function mount(ui: React.ReactElement): HTMLElement {
}
beforeEach(() => {
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT =
true;
(
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
intl.locale = "en";
});
@@ -65,7 +63,8 @@ function setupFetchMock() {
async (input: RequestInfo | URL, init?: RequestInit) => {
const url = input.toString();
const method = (init?.method ?? "GET").toUpperCase();
if (url.includes("/api/settings/compression/mcp-accessibility")) return json({ enabled: true });
if (url.includes("/api/settings/compression/mcp-accessibility"))
return json({ enabled: true });
if (url.includes("/api/settings/compression")) {
if (method === "PUT") {
const body = JSON.parse(String(init?.body ?? "{}"));
@@ -84,9 +83,8 @@ describe("CompressionPanel output styles", () => {
it("renders one row per catalog style", async () => {
setupFetchMock();
intl.locale = "zh-CN"; // a locale that matches every gated style, so all rows render
const { default: CompressionPanel } = await import(
"../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel"
);
const { default: CompressionPanel } =
await import("../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel");
let container!: HTMLElement;
await act(async () => {
container = mount(<CompressionPanel />);
@@ -95,16 +93,15 @@ describe("CompressionPanel output styles", () => {
for (const id of OUTPUT_STYLE_IDS) {
const row = container.querySelector(`[data-testid="output-style-row-${id}"]`);
expect(row, `expected a row for style "${id}"`).toBeTruthy();
expect(container.textContent).toContain(outputStyleMeta(id).label);
expect(row?.textContent).toContain(`compressionOutputStyle.${id}.label`);
}
});
it("locale-gates terse-cjk: hidden under a non-zh locale", async () => {
setupFetchMock();
intl.locale = "en";
const { default: CompressionPanel } = await import(
"../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel"
);
const { default: CompressionPanel } =
await import("../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel");
let container!: HTMLElement;
await act(async () => {
container = mount(<CompressionPanel />);
@@ -120,9 +117,8 @@ describe("CompressionPanel output styles", () => {
it("locale-gates terse-cjk: offered under a zh locale (zh-CN base matches)", async () => {
setupFetchMock();
intl.locale = "zh-CN";
const { default: CompressionPanel } = await import(
"../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel"
);
const { default: CompressionPanel } =
await import("../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel");
let container!: HTMLElement;
await act(async () => {
container = mount(<CompressionPanel />);
@@ -133,9 +129,8 @@ describe("CompressionPanel output styles", () => {
it("toggling a style PUTs an outputStyles selection", async () => {
const { puts } = setupFetchMock();
const { default: CompressionPanel } = await import(
"../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel"
);
const { default: CompressionPanel } =
await import("../../../src/app/(dashboard)/dashboard/context/settings/CompressionPanel");
let container!: HTMLElement;
await act(async () => {
container = mount(<CompressionPanel />);

View File

@@ -3,7 +3,10 @@ import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
vi.mock("next-intl", () => ({ useTranslations: () => (key: string) => key }));
vi.mock("next-intl", () => ({
useTranslations: () => (key: string) => key,
useLocale: () => "en",
}));
const containers: HTMLElement[] = [];
const roots: Array<{ unmount: () => void }> = [];
@@ -19,8 +22,9 @@ function mount(ui: React.ReactElement): HTMLElement {
}
beforeEach(() => {
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT =
true;
(
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
});
afterEach(async () => {
@@ -53,9 +57,8 @@ describe("CompressionStylesTile", () => {
{ status: 200, headers: { "Content-Type": "application/json" } }
)
);
const { default: CompressionStylesTile } = await import(
"../../../src/app/(dashboard)/dashboard/context/CompressionStylesTile"
);
const { default: CompressionStylesTile } =
await import("../../../src/app/(dashboard)/dashboard/context/CompressionStylesTile");
let container!: HTMLElement;
await act(async () => {
container = mount(<CompressionStylesTile />);