feat(i18n): localize Settings → Workspace (#2212)

Co-authored-by: Kandev Agent <agent@kandev.dev>
This commit is contained in:
João Salavisa
2026-08-03 20:52:09 +02:00
committed by GitHub
parent 8ae850956f
commit 957cbb910e
25 changed files with 1656 additions and 180 deletions
@@ -0,0 +1,93 @@
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { i18n } from "@/lib/i18n";
import { RepositoryBranchTemplateHelp } from "./repository-branch-template-help";
const TRIGGER_LABEL = "Branch template placeholders";
// Restoring the locale is load-bearing: `changeLanguage` mutates the shared
// instance `vitest.setup.ts` initializes, so leaving it on pseudo would leak
// into every test that runs after this file.
afterEach(async () => {
cleanup();
await i18n.changeLanguage("en");
});
/**
* The six placeholder tokens are substituted by exact string match in
* `RenderTaskBranchName` (apps/backend/internal/worktree/config.go), so they must
* stay in English while the description beside each one is translated. The
* description now arrives through a catalog key held in the table, which means a
* mistyped key renders the key itself and nothing fails — these assertions pin
* the token-to-description pairing and the interpolated example values.
*/
function openHelp() {
render(<RepositoryBranchTemplateHelp />);
// HoverCard content is only mounted while open; the trigger is a button, so
// focus is enough in happy-dom.
screen.getByRole("button", { name: TRIGGER_LABEL }).focus();
}
/**
* The trigger is icon-only, so its `aria-label` is the ONLY copy a screen-reader
* user gets from it — and attribute copy has no second check. The pseudo-locale
* oracle walks text nodes (`docs/i18n.md`, "It cannot see copy that is not a
* text node"), so reverting this to an English literal leaves no trace on
* screen. The locale-switch assertion below covers the two failures lint cannot:
* a hardcoded literal, and a `t()` frozen at module scope. Both render the same
* English forever; only a switch tells them apart.
*/
describe("RepositoryBranchTemplateHelp", () => {
it("labels the trigger for screen readers", () => {
render(<RepositoryBranchTemplateHelp />);
expect(screen.getByRole("button", { name: TRIGGER_LABEL })).toBeTruthy();
});
it("resolves the trigger label through the catalog on a locale switch", async () => {
render(<RepositoryBranchTemplateHelp />);
await i18n.changeLanguage("pseudo");
const label = screen.getByRole("button").getAttribute("aria-label") ?? "";
expect(label).not.toBe(TRIGGER_LABEL);
expect(label.length).toBeGreaterThan(0);
});
it("pairs each untranslated token with its description and example", async () => {
openHelp();
const term = await screen.findByText("{title}");
const description = term.nextElementSibling;
expect(description?.textContent).toBe(
"Task title sanitized to lowercase ASCII, hyphen-separated, max 20 chars. Example: fix-login-flow.",
);
});
it("keeps the ticket examples as interpolated values", async () => {
openHelp();
const term = await screen.findByText("{ticket}");
expect(term.nextElementSibling?.textContent).toBe(
"Task identifier first; otherwise Jira, Linear, GitHub issue, or GitHub PR metadata. Examples: KAN-123, #42.",
);
});
it("renders the alias description that carries no example", async () => {
openHelp();
const term = await screen.findByText("{issue_key}");
expect(term.nextElementSibling?.textContent).toBe(
"Alias for ticket. Use whichever name reads better in your template.",
);
});
it("keeps the literal-prefix example inside a code element", async () => {
openHelp();
const code = await screen.findByText("feature/{ticket}-{title}");
expect(code.tagName).toBe("CODE");
expect(code.parentElement?.textContent).toBe(
"Write literal prefixes directly, for example feature/{ticket}-{title}.",
);
});
});
@@ -1,39 +1,55 @@
"use client";
import { Trans, useTranslation } from "react-i18next";
import { IconInfoCircle } from "@tabler/icons-react";
import { HoverCard, HoverCardContent, HoverCardTrigger } from "@kandev/ui/hover-card";
/**
* The placeholder tokens are PROTOCOL, not copy: `RenderTaskBranchName` in
* `apps/backend/internal/worktree/config.go` substitutes each one by exact
* string match, so a translated `{title}` would be emitted into the branch name
* verbatim. Only the description beside each token is copy, and it lives in the
* catalog under `descriptionKey` so it resolves at render rather than at import.
*
* The example values are branch-name output — sanitized lowercase ASCII, a
* ticket key, a UUID — so they travel as interpolated VALUES rather than sitting
* inside the message a translator edits.
*/
const branchTemplatePlaceholders = [
[
"{title}",
"Task title sanitized to lowercase ASCII, hyphen-separated, max 20 chars. Example: fix-login-flow.",
],
[
"{title_full}",
"Same sanitizing as title, but max 80 chars. Example: fix-login-flow-after-session-timeout.",
],
[
"{ticket}",
"Task identifier first; otherwise Jira, Linear, GitHub issue, or GitHub PR metadata. Examples: KAN-123, #42.",
],
["{issue_key}", "Alias for ticket. Use whichever name reads better in your template."],
[
"{task_id}",
"Kandev task UUID, sanitized for branch names. Example: 1f1cf094-db3c-4f42-b425-2cc14a2f7c74.",
],
[
"{suffix}",
"Short random suffix. Optional, but recommended to avoid branch name clashes. Example: x7p9.",
],
{
token: "{title}",
descriptionKey: "workspaces:branchTemplateTitle",
example: "fix-login-flow",
},
{
token: "{title_full}",
descriptionKey: "workspaces:branchTemplateTitleFull",
example: "fix-login-flow-after-session-timeout",
},
{
token: "{ticket}",
descriptionKey: "workspaces:branchTemplateTicket",
example: "KAN-123, #42",
},
{ token: "{issue_key}", descriptionKey: "workspaces:branchTemplateIssueKey", example: "" },
{
token: "{task_id}",
descriptionKey: "workspaces:branchTemplateTaskId",
example: "1f1cf094-db3c-4f42-b425-2cc14a2f7c74",
},
{ token: "{suffix}", descriptionKey: "workspaces:branchTemplateSuffix", example: "x7p9" },
] as const;
const LITERAL_PREFIX_EXAMPLE = "feature/{ticket}-{title}";
export function RepositoryBranchTemplateHelp() {
const { t } = useTranslation();
return (
<HoverCard openDelay={150} closeDelay={100}>
<HoverCardTrigger asChild>
<button
type="button"
aria-label="Branch template placeholders"
aria-label={t("workspaces:branchTemplatePlaceholders")}
className="cursor-help text-muted-foreground hover:text-foreground"
>
<IconInfoCircle className="h-3.5 w-3.5" />
@@ -42,17 +58,18 @@ export function RepositoryBranchTemplateHelp() {
<HoverCardContent align="start" className="w-96 text-xs">
<div className="space-y-2">
<p className="text-muted-foreground">
Write literal prefixes directly, for example{" "}
<code className="rounded bg-muted px-1 py-0.5">
feature/{"{ticket}"}-{"{title}"}
</code>
.
<Trans
i18nKey="workspaces:branchTemplateLiteralPrefix"
values={{ example: LITERAL_PREFIX_EXAMPLE }}
>
<code className="rounded bg-muted px-1 py-0.5" />
</Trans>
</p>
<dl className="space-y-1.5">
{branchTemplatePlaceholders.map(([name, description]) => (
<div key={name} className="grid grid-cols-[5.5rem_1fr] gap-2">
<dt className="font-mono text-foreground">{name}</dt>
<dd className="text-muted-foreground">{description}</dd>
{branchTemplatePlaceholders.map(({ token, descriptionKey, example }) => (
<div key={token} className="grid grid-cols-[5.5rem_1fr] gap-2">
<dt className="font-mono text-foreground">{token}</dt>
<dd className="text-muted-foreground">{t(descriptionKey, { example })}</dd>
</div>
))}
</dl>
@@ -0,0 +1,182 @@
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { i18n } from "@/lib/i18n";
import { RepositoryCard } from "./repository-card";
import { SettingsSaveProvider } from "./settings-save-provider";
import { ToastProvider } from "@/components/toast-provider";
import type { Repository, RepositoryScript } from "@/lib/types/http";
const CLOSE_EDITOR_LABEL = "Close repository editor";
// Restoring the locale is load-bearing: `changeLanguage` mutates the shared
// instance `vitest.setup.ts` initializes, so leaving it on pseudo would leak
// into every test that runs after this file.
afterEach(async () => {
cleanup();
await i18n.changeLanguage("en");
});
type RepositoryWithScripts = Repository & { scripts: RepositoryScript[] };
/**
* The collapsed card's whole summary is built by `buildRepoPreviewData` /
* `buildRepoScriptsSummary` — plain functions holding no JSX, which
* `i18next/no-literal-string` never inspects. The script count also used to be
* inflected with an English `s` at the call site. Neither shape fails loudly, so
* these assertions pin the rendered text.
*/
function repository(overrides: Partial<RepositoryWithScripts> = {}): RepositoryWithScripts {
return {
id: "repo-1",
workspace_id: "ws-1",
name: "kandev",
source_type: "local",
local_path: "/home/dev/kandev",
provider: "",
provider_repo_id: "",
provider_host: "",
provider_owner: "",
provider_name: "",
default_branch: "main",
worktree_branch_prefix: "feature/",
worktree_branch_template: "feature/{title}-{suffix}",
pull_before_worktree: true,
setup_script: "",
cleanup_script: "",
dev_script: "",
copy_files: "",
created_at: "",
updated_at: "",
scripts: [],
...overrides,
} as RepositoryWithScripts;
}
function script(id: string): RepositoryScript {
return {
id,
repository_id: "repo-1",
name: id,
command: "echo hi",
position: 0,
created_at: "",
updated_at: "",
} as RepositoryScript;
}
function renderCard(repo: RepositoryWithScripts, autoOpen = false) {
return render(
<ToastProvider>
<SettingsSaveProvider>
<RepositoryCard
repository={repo}
savedRepository={repo}
isRepositoryDirty={false}
areScriptsDirty={false}
autoOpen={autoOpen}
onUpdate={vi.fn()}
onAddScript={vi.fn()}
onUpdateScript={vi.fn()}
onDeleteScript={vi.fn()}
onSave={vi.fn()}
onDelete={vi.fn()}
/>
</SettingsSaveProvider>
</ToastProvider>,
);
}
describe("RepositoryCard preview", () => {
it("uses the singular form for exactly one custom script", () => {
renderCard(repository({ scripts: [script("a")] }));
expect(screen.getByText("1 custom script")).toBeTruthy();
});
it("uses the plural form for more than one custom script", () => {
renderCard(repository({ scripts: [script("a"), script("b")] }));
expect(screen.getByText("2 custom scripts")).toBeTruthy();
});
it("labels a local repository and shows its path verbatim", () => {
renderCard(repository());
expect(screen.getByText("Local")).toBeTruthy();
expect(screen.getByText("/home/dev/kandev")).toBeTruthy();
});
it("falls back to translated copy when a local repository has no path", () => {
renderCard(repository({ local_path: "" }));
expect(screen.getByText("Local path not set")).toBeTruthy();
});
it("shows the owner/name slug for a remote repository", () => {
renderCard(
repository({
source_type: "remote",
provider_owner: "kdlbs",
provider_name: "kandev",
}),
);
expect(screen.getByText("Remote")).toBeTruthy();
expect(screen.getByText("kdlbs/kandev")).toBeTruthy();
});
it("falls back to translated copy when a remote repository has no slug", () => {
renderCard(repository({ source_type: "remote" }));
expect(screen.getByText("Remote repository")).toBeTruthy();
});
it("names an unnamed repository", () => {
renderCard(repository({ name: "" }));
expect(screen.getByText("Untitled repository")).toBeTruthy();
});
it("lists the three built-in script chips only when their scripts are set", () => {
renderCard(
repository({
setup_script: "npm ci",
cleanup_script: "rm -rf tmp",
dev_script: "npm run dev",
}),
);
expect(screen.getByText("build script")).toBeTruthy();
expect(screen.getByText("cleanup script")).toBeTruthy();
expect(screen.getByText("dev script")).toBeTruthy();
expect(screen.queryByText("No custom scripts")).toBeNull();
});
});
/**
* The editor's close control is icon-only, so its `aria-label` is the only copy
* a screen-reader user gets from it. Attribute copy has no second check — the
* pseudo-locale oracle walks text nodes, so reverting this to an English literal
* leaves nothing visible (`docs/i18n.md`, "It cannot see copy that is not a text
* node"). The locale-switch assertion catches the two shapes lint cannot: a
* hardcoded literal, and a `t()` frozen at module scope.
*/
describe("RepositoryCard editor close control", () => {
it("labels the close control for screen readers", () => {
renderCard(repository(), true);
expect(screen.getByRole("button", { name: CLOSE_EDITOR_LABEL })).toBeTruthy();
});
it("resolves the close label through the catalog on a locale switch", async () => {
const { container } = renderCard(repository(), true);
const close = container.querySelector(`[aria-label="${CLOSE_EDITOR_LABEL}"]`);
expect(close).toBeTruthy();
await i18n.changeLanguage("pseudo");
expect(container.querySelector(`[aria-label="${CLOSE_EDITOR_LABEL}"]`)).toBeNull();
const label = close?.getAttribute("aria-label") ?? "";
expect(label.length).toBeGreaterThan(0);
});
});
@@ -1,6 +1,8 @@
"use client";
import { useState } from "react";
import { Trans, useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
import { IconEdit, IconGitBranch, IconTrash, IconX } from "@tabler/icons-react";
import { Badge } from "@kandev/ui/badge";
import { CardContent } from "@kandev/ui/card";
@@ -25,6 +27,23 @@ import { defaultWorktreeBranchTemplate } from "@/lib/worktree-branch-template";
type RepositoryWithScripts = Repository & { scripts: RepositoryScript[] };
/**
* The environment variable the dev script reads to learn its allocated port. It
* is an identifier the user types into a shell command verbatim, so it travels
* as an interpolated value rather than sitting inside the message.
*/
const DEV_SCRIPT_PORT_VAR = "$PORT";
/**
* Shell script samples. Each is code the user edits and the executor runs
* verbatim, so none of it is copy — the same call as `DEFAULT_DOCKERFILE` in the
* executor profile editor. Hoisted out of the JSX so the intent is explicit
* rather than resting on a guard exclusion pattern.
*/
const SETUP_SCRIPT_PLACEHOLDER = "#!/bin/bash\n# any manual setup you need";
const CLEANUP_SCRIPT_PLACEHOLDER = "#!/bin/bash\n# any manual clean up you need";
const DEV_SCRIPT_PLACEHOLDER = "#!/bin/bash\nnpm run dev -- --port $PORT";
type RepoFieldsBaseProps = {
repositoryId: string;
onUpdate: (repoId: string, updates: Partial<Repository>) => void;
@@ -49,11 +68,14 @@ function RepositoryBasicFields({
worktreeBranchTemplate,
pullBeforeWorktree,
}: RepositoryBasicFieldsProps) {
const { t } = useTranslation();
return (
<>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label>Repository Name</Label>
<Label>{t("workspaces:repositoryName")}</Label>
{/* Both placeholders are value shapes — a git repository name and an
absolute filesystem path — so they stay in English. */}
<Input
value={repositoryName}
onChange={(e) => onUpdate(repositoryId, { name: e.target.value })}
@@ -62,7 +84,7 @@ function RepositoryBasicFields({
/>
</div>
<div className="space-y-2">
<Label>Local Path</Label>
<Label>{t("workspaces:localPath")}</Label>
<Input
value={repositoryLocalPath}
onChange={(e) => onUpdate(repositoryId, { local_path: e.target.value })}
@@ -75,7 +97,7 @@ function RepositoryBasicFields({
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<div className="flex items-center gap-1.5">
<Label>Worktree Branch Template</Label>
<Label>{t("workspaces:worktreeBranchTemplate")}</Label>
<RepositoryBranchTemplateHelp />
</div>
<Input
@@ -89,7 +111,7 @@ function RepositoryBasicFields({
/>
</div>
<div className="space-y-2">
<Label htmlFor={`repo-pull-before-${repositoryId}`}>Worktree Sync</Label>
<Label htmlFor={`repo-pull-before-${repositoryId}`}>{t("workspaces:worktreeSync")}</Label>
<div className="flex items-start gap-2 pt-2">
<Checkbox
id={`repo-pull-before-${repositoryId}`}
@@ -106,7 +128,7 @@ function RepositoryBasicFields({
htmlFor={`repo-pull-before-${repositoryId}`}
className="text-sm text-muted-foreground cursor-pointer"
>
Always pull before creating a new worktree
{t("workspaces:alwaysPullBeforeWorktree")}
</Label>
</div>
</div>
@@ -133,52 +155,52 @@ function RepositoryScriptFields({
devScript,
copyFiles,
}: RepositoryScriptFieldsProps) {
const { t } = useTranslation();
return (
<>
{/* Every script placeholder below is a shell sample — a shebang plus a
command the executor runs verbatim — so it is code, not copy. */}
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label>Setup Script</Label>
<Label>{t("workspaces:setupScript")}</Label>
<Textarea
value={setupScript}
onChange={(e) => onUpdate(repositoryId, { setup_script: e.target.value })}
placeholder="#!/bin/bash&#10;# any manual setup you need"
placeholder={SETUP_SCRIPT_PLACEHOLDER}
rows={3}
className="font-mono text-sm"
data-settings-dirty={setupScript !== (savedRepository?.setup_script ?? "")}
/>
<p className="text-xs text-muted-foreground">
Runs when the repo is cloned or a git worktree is created.
</p>
<p className="text-xs text-muted-foreground">{t("workspaces:setupScriptHelp")}</p>
</div>
<div className="space-y-2">
<Label>Cleanup Script</Label>
<Label>{t("workspaces:cleanupScript")}</Label>
<Textarea
value={cleanupScript}
onChange={(e) => onUpdate(repositoryId, { cleanup_script: e.target.value })}
placeholder="#!/bin/bash&#10;# any manual clean up you need"
placeholder={CLEANUP_SCRIPT_PLACEHOLDER}
rows={3}
className="font-mono text-sm"
data-settings-dirty={cleanupScript !== (savedRepository?.cleanup_script ?? "")}
/>
<p className="text-xs text-muted-foreground">
Runs when the task is completed to clean up the workspace.
</p>
<p className="text-xs text-muted-foreground">{t("workspaces:cleanupScriptHelp")}</p>
</div>
</div>
<div className="space-y-2">
<Label>Dev Script</Label>
<Label>{t("workspaces:devScript")}</Label>
<Textarea
value={devScript}
onChange={(e) => onUpdate(repositoryId, { dev_script: e.target.value })}
placeholder="#!/bin/bash&#10;npm run dev -- --port $PORT"
placeholder={DEV_SCRIPT_PLACEHOLDER}
rows={3}
className="font-mono text-sm"
data-settings-dirty={devScript !== (savedRepository?.dev_script ?? "")}
/>
<p className="text-xs text-muted-foreground">
Used to start the preview dev server for this repository. Use{" "}
<code className="px-1 py-0.5 bg-muted rounded">$PORT</code> for automatic port allocation.
<Trans i18nKey="workspaces:devScriptHelp" values={{ port: DEV_SCRIPT_PORT_VAR }}>
<code className="px-1 py-0.5 bg-muted rounded" />
</Trans>
</p>
</div>
@@ -219,6 +241,7 @@ function RepositoryEditView({
deleteLoading,
close,
}: RepositoryEditViewProps) {
const { t } = useTranslation();
return (
<SettingsCard isDirty={isDirty}>
<CardContent className="pt-6">
@@ -227,7 +250,7 @@ function RepositoryEditView({
<div className="flex items-center gap-2">
<IconGitBranch className="h-4 w-4 text-muted-foreground" />
<Label className="flex items-center gap-2">
<span>Repository</span>
<span>{t("workspaces:repository")}</span>
{isDirty && <UnsavedChangesBadge />}
</Label>
</div>
@@ -236,7 +259,7 @@ function RepositoryEditView({
variant="ghost"
size="icon"
className="cursor-pointer"
aria-label="Close repository editor"
aria-label={t("workspaces:closeRepositoryEditor")}
onClick={close}
>
<IconX className="h-4 w-4" />
@@ -284,7 +307,7 @@ function RepositoryEditView({
disabled={deleteLoading}
>
<IconTrash className="h-4 w-4 mr-2" />
Delete Repository
{t("workspaces:deleteRepository")}
</Button>
</div>
</div>
@@ -301,7 +324,11 @@ type RepositoryPreviewProps = {
open: () => void;
};
function buildRepoScriptsSummary(repository: RepositoryWithScripts) {
// These two build every string in the collapsed card, and neither holds JSX, so
// `i18next/no-literal-string` could never see any of it — the lint count for this
// file reported zero for the whole block. `t` is a parameter rather than the
// module-level import so each label resolves when the card renders.
function buildRepoScriptsSummary(t: TFunction, repository: RepositoryWithScripts) {
const setupScript = repository.setup_script ?? "";
const cleanupScript = repository.cleanup_script ?? "";
const devScript = repository.dev_script ?? "";
@@ -310,10 +337,12 @@ function buildRepoScriptsSummary(repository: RepositoryWithScripts) {
const hasCleanupScript = Boolean(cleanupScript.trim());
const hasDevScript = Boolean(devScript.trim());
const showScriptsSummary = scriptsCount > 0 || hasSetupScript || hasCleanupScript || hasDevScript;
// Was `custom script${count === 1 ? "" : "s"}` — an English morpheme built at
// the call site, which leaves a translator no way to express a third form.
const scriptsLabel =
scriptsCount === 0
? "No custom scripts"
: `${scriptsCount} custom script${scriptsCount === 1 ? "" : "s"}`;
? t("workspaces:noCustomScripts")
: t("workspaces:customScripts", { count: scriptsCount });
return {
scriptsCount,
hasSetupScript,
@@ -324,20 +353,24 @@ function buildRepoScriptsSummary(repository: RepositoryWithScripts) {
};
}
function buildRepoPreviewData(repository: RepositoryWithScripts) {
function buildRepoPreviewData(t: TFunction, repository: RepositoryWithScripts) {
const repositoryName = repository.name ?? "";
const sourceLabel = repository.source_type === "local" ? "Local" : "Remote";
// `source_type` is the wire value; only its badge label is copy.
const sourceLabel =
repository.source_type === "local" ? t("workspaces:sourceLocal") : t("workspaces:sourceRemote");
// The path and the `owner/name` slug are user data / git metadata; only the
// two "nothing recorded" fallbacks are copy.
const subtitle =
repository.source_type === "local"
? repository.local_path || "Local path not set"
? repository.local_path || t("workspaces:localPathNotSet")
: [repository.provider_owner, repository.provider_name].filter(Boolean).join("/") ||
repository.provider ||
"Remote repository";
t("workspaces:remoteRepository");
return {
repositoryName,
sourceLabel,
subtitle,
...buildRepoScriptsSummary(repository),
...buildRepoScriptsSummary(t, repository),
};
}
@@ -348,6 +381,7 @@ function RepositoryPreview({
onOpenDelete,
open,
}: RepositoryPreviewProps) {
const { t } = useTranslation();
const {
repositoryName,
scriptsCount,
@@ -358,7 +392,7 @@ function RepositoryPreview({
scriptsLabel,
sourceLabel,
subtitle,
} = buildRepoPreviewData(repository);
} = buildRepoPreviewData(t, repository);
return (
<SettingsCard isDirty={isDirty}>
@@ -370,7 +404,9 @@ function RepositoryPreview({
</div>
<div className="min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<h4 className="font-medium truncate">{repositoryName || "Untitled repository"}</h4>
<h4 className="font-medium truncate">
{repositoryName || t("workspaces:untitledRepository")}
</h4>
<Badge variant="secondary" className="text-xs">
{sourceLabel}
</Badge>
@@ -380,9 +416,9 @@ function RepositoryPreview({
{showScriptsSummary ? (
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground mt-1">
{scriptsCount > 0 && <span>{scriptsLabel}</span>}
{hasSetupScript && <span>build script</span>}
{hasCleanupScript && <span>cleanup script</span>}
{hasDevScript && <span>dev script</span>}
{hasSetupScript && <span>{t("workspaces:buildScriptChip")}</span>}
{hasCleanupScript && <span>{t("workspaces:cleanupScriptChip")}</span>}
{hasDevScript && <span>{t("workspaces:devScriptChip")}</span>}
</div>
) : null}
</div>
@@ -399,7 +435,7 @@ function RepositoryPreview({
}}
>
<IconEdit className="h-4 w-4" />
Edit
{t("workspaces:edit")}
</Button>
<Button
type="button"
@@ -413,7 +449,7 @@ function RepositoryPreview({
disabled={deleteLoading}
>
<IconTrash className="h-4 w-4" />
Delete
{t("workspaces:delete")}
</Button>
</div>
</div>
@@ -442,6 +478,7 @@ function useRepositoryDelete(
onDeleted: () => void,
) {
const { toast } = useToast();
const { t } = useTranslation();
const [deleteOpen, setDeleteOpen] = useState(false);
const [activeSessionCount, setActiveSessionCount] = useState(0);
const [checkingCount, setCheckingCount] = useState(false);
@@ -465,8 +502,8 @@ function useRepositoryDelete(
setDeleteOpen(true);
} catch (error) {
toast({
title: "Failed to check repository sessions",
description: error instanceof Error ? error.message : "Request failed",
title: t("workspaces:failedToCheckRepositorySessions"),
description: error instanceof Error ? error.message : t("common:requestFailed"),
variant: "error",
});
} finally {
@@ -481,8 +518,8 @@ function useRepositoryDelete(
onDeleted();
} catch (error) {
toast({
title: "Failed to delete repository",
description: error instanceof Error ? error.message : "Request failed",
title: t("workspaces:failedToDeleteRepository"),
description: error instanceof Error ? error.message : t("common:requestFailed"),
variant: "error",
});
}
@@ -513,6 +550,7 @@ export function RepositoryCard({
onDelete,
}: RepositoryCardProps) {
const { toast } = useToast();
const { t } = useTranslation();
const [isEditing, setIsEditing] = useState(() => autoOpen);
const saveRequest = useRequest(() => onSave(repository.id));
const isDirty = isRepositoryDirty || areScriptsDirty;
@@ -523,8 +561,8 @@ export function RepositoryCard({
await saveRequest.run();
} catch (error) {
toast({
title: "Failed to save repository",
description: error instanceof Error ? error.message : "Request failed",
title: t("workspaces:failedToSaveRepository"),
description: error instanceof Error ? error.message : t("common:requestFailed"),
variant: "error",
});
throw error;
@@ -0,0 +1,68 @@
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { CopyFilesField } from "./repository-copy-files-help";
afterEach(cleanup);
/**
* Every sentence here is a `<Trans>` whose `<n>` indices address `<code>`
* elements positionally, and each glob pattern travels as an interpolation VALUE
* so the pseudo-locale cannot accent it into a pattern that matches nothing.
* Both shapes fail silently: a drifted index renders duplicated fragments with
* empty tags, and a pattern moved into the message body would only show up in a
* translated build. These tests reconstruct the whole sentence and assert each
* pattern lands inside a `<code>`.
*/
function renderField() {
return render(<CopyFilesField repositoryId="repo-1" copyFiles="" onUpdate={vi.fn()} />).container;
}
function codeTexts(container: HTMLElement): string[] {
return Array.from(container.querySelectorAll("code")).map((el) => el.textContent);
}
describe("CopyFilesField", () => {
it("renders the symlink help as one sentence with each suffix in a code element", () => {
const container = renderField();
expect(document.getElementById("copy-files-help-repo-1")?.textContent).toBe(
"Gitignored paths copied into new worktrees. Append :symlink to an entry to link it back to the main repo. Use ::symlink for a literal filename ending in :symlink.",
);
expect(codeTexts(container)).toEqual(expect.arrayContaining([":symlink", "::symlink"]));
});
it("keeps the glob patterns out of the translated message body", () => {
const container = renderField();
expect(codeTexts(container)).toEqual(
expect.arrayContaining(["*", "?", "[abc]", "**", "**/.env", "{a,b}", ".env{,.local}"]),
);
});
it("renders each supported-pattern bullet as a complete sentence", () => {
const container = renderField();
// Each bullet is assembled from `<code>` elements and text nodes, so it has
// to be reconstructed — a drifted `<n>` index would drop a fragment here
// while every individual `<code>` still rendered.
const bullets = Array.from(container.querySelectorAll("li")).map((li) =>
li.textContent?.replace(/\s+/g, " ").trim(),
);
expect(bullets).toEqual([
".env literal file or directory (directories copy recursively)",
"*, ?, [abc] single-segment wildcards",
"** matches any number of directories, e.g. **/.env",
"{a,b} brace alternation, e.g. .env{,.local}",
]);
});
it("interpolates the remote size cap rather than baking it into the message", () => {
renderField();
expect(
screen.getByText(
"Files over 5 MiB are skipped when copying to remote executors. Local worktrees copy them without a size cap.",
),
).toBeTruthy();
});
});
@@ -1,10 +1,32 @@
"use client";
import { Trans, useTranslation } from "react-i18next";
import { IconChevronDown, IconInfoCircle } from "@tabler/icons-react";
import { Label } from "@kandev/ui/label";
import { Textarea } from "@kandev/ui/textarea";
import type { Repository } from "@/lib/types/http";
/**
* Glob/path syntax the backend parses and the user types verbatim. These are
* VALUES, not copy, so each is interpolated into its message rather than left in
* the tag body — the pseudo-locale would otherwise accent `**` or `:symlink`
* into a pattern that no longer matches anything.
*/
const SYMLINK_SUFFIX = ":symlink";
const ESCAPED_SYMLINK_SUFFIX = "::symlink";
const LITERAL_PATTERN = ".env";
const STAR_PATTERN = "*";
const QUESTION_PATTERN = "?";
const CHAR_CLASS_PATTERN = "[abc]";
const GLOBSTAR_PATTERN = "**";
const GLOBSTAR_EXAMPLE = "**/.env";
const BRACES_PATTERN = "{a,b}";
const BRACES_EXAMPLE = ".env{,.local}";
const REMOTE_COPY_SIZE_LIMIT = "5 MiB";
const COPY_FILES_PLACEHOLDER = ".env, .env.*, apps/**/.env, .env.local:symlink";
const codeClass = "px-1 py-0.5 bg-muted rounded";
type CopyFilesFieldProps = {
repositoryId: string;
copyFiles: string;
@@ -18,30 +40,36 @@ export function CopyFilesField({
isDirty = false,
onUpdate,
}: CopyFilesFieldProps) {
const { t } = useTranslation();
const inputId = `copy-files-${repositoryId}`;
const helpId = `copy-files-help-${repositoryId}`;
return (
<div className="space-y-2">
<Label htmlFor={inputId}>Copy Files</Label>
<Label htmlFor={inputId}>{t("workspaces:copyFiles")}</Label>
{/* The placeholder is a list of glob patterns — a value, not prose. */}
<Textarea
id={inputId}
data-testid={`copy-files-input-${repositoryId}`}
aria-describedby={helpId}
value={copyFiles}
onChange={(e) => onUpdate(repositoryId, { copy_files: e.target.value })}
placeholder=".env, .env.*, apps/**/.env, .env.local:symlink"
placeholder={COPY_FILES_PLACEHOLDER}
rows={2}
className="font-mono text-sm"
data-settings-dirty={isDirty}
/>
<p id={helpId} className="text-xs text-muted-foreground">
Gitignored paths copied into new worktrees. Append{" "}
<code className="px-1 py-0.5 bg-muted rounded">:symlink</code> to an entry to link it back
to the main repo. Use <code className="px-1 py-0.5 bg-muted rounded">::symlink</code> for a
literal filename ending in <code className="px-1 py-0.5 bg-muted rounded">:symlink</code>.
<Trans
i18nKey="workspaces:copyFilesHelp"
values={{ symlink: SYMLINK_SUFFIX, escapedSymlink: ESCAPED_SYMLINK_SUFFIX }}
>
<code className={codeClass} />
<code className={codeClass} />
<code className={codeClass} />
</Trans>
</p>
<p data-testid="copy-files-remote-fallback" className="text-xs text-muted-foreground">
Remote executors copy file contents instead of creating symlinks.
{t("workspaces:copyFilesRemoteFallback")}
</p>
<CopyFilesDetails />
</div>
@@ -49,44 +77,64 @@ export function CopyFilesField({
}
function CopyFilesDetails() {
const { t } = useTranslation();
return (
<details className="group text-xs text-muted-foreground">
<summary className="flex min-h-11 w-fit cursor-pointer list-none items-center gap-1.5 py-2 font-medium text-foreground">
<IconInfoCircle className="h-4 w-4 shrink-0" aria-hidden="true" />
Pattern syntax
{t("workspaces:patternSyntax")}
<IconChevronDown
className="h-4 w-4 shrink-0 transition-transform group-open:rotate-180"
aria-hidden="true"
/>
</summary>
<div className="max-w-sm space-y-2 pb-1">
<p>
Paths are resolved relative to the repository root and seeded into every new worktree,
preserving their relative location. Existing files in the worktree are not overwritten.
</p>
<p className="font-medium">Supported patterns:</p>
<p>{t("workspaces:copyFilesPathsResolved")}</p>
<p className="font-medium">{t("workspaces:supportedPatterns")}</p>
<ul className="space-y-1 pl-3 list-disc">
<li>
<code className="px-1 py-0.5 bg-muted rounded">.env</code> literal file or directory
(directories copy recursively)
<Trans
i18nKey="workspaces:copyFilesPatternLiteral"
values={{ pattern: LITERAL_PATTERN }}
>
<code className={codeClass} />
</Trans>
</li>
<li>
<code className="px-1 py-0.5 bg-muted rounded">*</code>,{" "}
<code className="px-1 py-0.5 bg-muted rounded">?</code>,{" "}
<code className="px-1 py-0.5 bg-muted rounded">[abc]</code> single-segment wildcards
<Trans
i18nKey="workspaces:copyFilesPatternWildcards"
values={{
star: STAR_PATTERN,
question: QUESTION_PATTERN,
charClass: CHAR_CLASS_PATTERN,
}}
>
<code className={codeClass} />
<code className={codeClass} />
<code className={codeClass} />
</Trans>
</li>
<li>
<code className="px-1 py-0.5 bg-muted rounded">**</code> matches any number of
directories, e.g. <code className="px-1 py-0.5 bg-muted rounded">**/.env</code>
<Trans
i18nKey="workspaces:copyFilesPatternGlobstar"
values={{ globstar: GLOBSTAR_PATTERN, example: GLOBSTAR_EXAMPLE }}
>
<code className={codeClass} />
<code className={codeClass} />
</Trans>
</li>
<li>
<code className="px-1 py-0.5 bg-muted rounded">{"{a,b}"}</code> brace alternation, e.g.{" "}
<code className="px-1 py-0.5 bg-muted rounded">.env{"{,.local}"}</code>
<Trans
i18nKey="workspaces:copyFilesPatternBraces"
values={{ braces: BRACES_PATTERN, example: BRACES_EXAMPLE }}
>
<code className={codeClass} />
<code className={codeClass} />
</Trans>
</li>
</ul>
<p className="text-muted-foreground">
Files over 5 MiB are skipped when copying to remote executors. Local worktrees copy them
without a size cap.
{t("workspaces:copyFilesSizeLimit", { limit: REMOTE_COPY_SIZE_LIMIT })}
</p>
</div>
</details>
@@ -1,3 +1,4 @@
import { useTranslation } from "react-i18next";
import { IconPlus, IconX } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Input } from "@kandev/ui/input";
@@ -6,6 +7,12 @@ import { Textarea } from "@kandev/ui/textarea";
import type { RepositoryScript } from "@/lib/types/http";
import { UnsavedChangesBadge } from "./unsaved-indicator";
/**
* A shell script sample: code the user edits and the executor runs verbatim,
* not copy.
*/
const SCRIPT_COMMAND_PLACEHOLDER = "#!/bin/bash\nnpm run dev";
type RepositoryCustomScriptsProps = {
repositoryId: string;
scripts: RepositoryScript[];
@@ -25,21 +32,22 @@ export function RepositoryCustomScripts({
onUpdateScript,
onDeleteScript,
}: RepositoryCustomScriptsProps) {
const { t } = useTranslation();
return (
<div className="space-y-3">
<div className="flex items-center justify-between gap-3">
<Label className="flex items-center gap-2">
<span>Custom Scripts</span>
<span>{t("workspaces:customScriptsLabel")}</span>
{areScriptsDirty && <UnsavedChangesBadge />}
</Label>
<Button type="button" variant="outline" size="sm" onClick={() => onAddScript(repositoryId)}>
<IconPlus className="h-4 w-4 mr-1" />
Add Script
{t("workspaces:addScript")}
</Button>
</div>
<div className="space-y-3">
{scripts.length === 0 ? (
<p className="text-sm text-muted-foreground">No scripts yet.</p>
<p className="text-sm text-muted-foreground">{t("workspaces:noScriptsYet")}</p>
) : (
scripts.map((script) => (
<RepositoryCustomScript
@@ -70,6 +78,7 @@ function RepositoryCustomScript({
onUpdate: RepositoryCustomScriptsProps["onUpdateScript"];
onDelete: RepositoryCustomScriptsProps["onDeleteScript"];
}) {
const { t } = useTranslation();
const nameIsDirty = !savedScript || script.name !== savedScript.name;
const commandIsDirty = !savedScript || script.command !== savedScript.command;
return (
@@ -82,7 +91,7 @@ function RepositoryCustomScript({
<Input
value={script.name ?? ""}
onChange={(event) => onUpdate(repositoryId, script.id, { name: event.target.value })}
placeholder="Script name"
placeholder={t("workspaces:scriptName")}
data-settings-dirty={nameIsDirty}
/>
<Button
@@ -97,7 +106,7 @@ function RepositoryCustomScript({
<Textarea
value={script.command ?? ""}
onChange={(event) => onUpdate(repositoryId, script.id, { command: event.target.value })}
placeholder="#!/bin/bash&#10;npm run dev"
placeholder={SCRIPT_COMMAND_PLACEHOLDER}
rows={3}
className="font-mono text-sm"
data-settings-dirty={commandIsDirty}
@@ -0,0 +1,70 @@
import { cleanup, render, screen, within } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { DeleteRepositoryDialog } from "./repository-delete-dialog";
afterEach(cleanup);
// `@kandev/ui`'s DialogContent renders its own sr-only "Close" control, so the
// footer has to be scoped explicitly or the dismiss button is ambiguous.
function footer(): HTMLElement {
return document.querySelector('[data-slot="dialog-footer"]') as HTMLElement;
}
/**
* The active-session sentence used to inflect both its noun and its pronoun with
* a ternary (`session`/`sessions`, `it`/`them`), so a bad `_one` / `_other` split
* would have rendered "1 active agent sessions … finish them" without failing
* anything. These assertions pin both forms and the no-sessions variant.
*/
function renderDialog(activeSessionCount: number) {
return render(
<DeleteRepositoryDialog
open
onOpenChange={vi.fn()}
onDelete={vi.fn()}
activeSessionCount={activeSessionCount}
deleteLoading={false}
/>,
);
}
describe("DeleteRepositoryDialog", () => {
it("uses the singular noun and pronoun for exactly one active session", () => {
renderDialog(1);
expect(
screen.getByText(
"This repository is used by 1 active agent session. Stop or finish it before deleting the repository.",
),
).toBeTruthy();
});
it("uses the plural noun and pronoun for more than one active session", () => {
renderDialog(3);
expect(
screen.getByText(
"This repository is used by 3 active agent sessions. Stop or finish them before deleting the repository.",
),
).toBeTruthy();
});
it("offers only a Close button while sessions are active", () => {
renderDialog(2);
expect(within(footer()).getByRole("button", { name: "Close" })).toBeTruthy();
expect(screen.queryByRole("button", { name: "Delete Repository" })).toBeNull();
});
it("offers Cancel and Delete Repository when no session is active", () => {
renderDialog(0);
expect(
screen.getByText(
"This will remove the repository and its scripts. This action cannot be undone.",
),
).toBeTruthy();
expect(screen.getByRole("button", { name: "Cancel" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Delete Repository" })).toBeTruthy();
});
});
@@ -1,5 +1,6 @@
"use client";
import { useTranslation } from "react-i18next";
import { Button } from "@kandev/ui/button";
import {
Dialog,
@@ -25,18 +26,19 @@ export function DeleteRepositoryDialog({
activeSessionCount,
deleteLoading,
}: DeleteRepositoryDialogProps) {
const { t } = useTranslation();
const hasActiveSessions = activeSessionCount > 0;
const isOne = activeSessionCount === 1;
const sessionWord = isOne ? "session" : "sessions";
const pronoun = isOne ? "it" : "them";
// The noun and the pronoun used to be inflected here with a ternary, which put
// the plural rule at the call site — untranslatable in a language with more
// than two forms. Both now fold into the `_one` / `_other` catalog entries.
const description = hasActiveSessions
? `This repository is used by ${activeSessionCount} active agent ${sessionWord}. Stop or finish ${pronoun} before deleting the repository.`
: "This will remove the repository and its scripts. This action cannot be undone.";
? t("workspaces:deleteRepositoryActiveSessions", { count: activeSessionCount })
: t("workspaces:deleteRepositoryConfirm");
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Delete repository</DialogTitle>
<DialogTitle>{t("workspaces:deleteRepositoryTitle")}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogFooter>
@@ -46,7 +48,7 @@ export function DeleteRepositoryDialog({
className="cursor-pointer"
onClick={() => onOpenChange(false)}
>
{hasActiveSessions ? "Close" : "Cancel"}
{hasActiveSessions ? t("workspaces:close") : t("common:cancel")}
</Button>
{!hasActiveSessions && (
<Button
@@ -56,7 +58,7 @@ export function DeleteRepositoryDialog({
onClick={onDelete}
disabled={deleteLoading}
>
Delete Repository
{t("workspaces:deleteRepository")}
</Button>
)}
</DialogFooter>
@@ -1,5 +1,6 @@
"use client";
import { useTranslation } from "react-i18next";
import { IconAlertCircle } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { RequestIndicator } from "@/components/request-indicator";
@@ -16,7 +17,8 @@ type UnsavedSaveButtonProps = {
const dirtyButtonClass = "border-success/60 text-success hover:bg-success/10";
export function UnsavedChangesBadge() {
return <span className="text-xs text-success">Unsaved changes</span>;
const { t } = useTranslation();
return <span className="text-xs text-success">{t("common:unsavedChanges")}</span>;
}
export function UnsavedSaveButton({
@@ -25,8 +27,12 @@ export function UnsavedSaveButton({
status,
onClick,
disabled,
cleanLabel = "Save",
cleanLabel,
}: UnsavedSaveButtonProps) {
const { t } = useTranslation();
// Defaulted here rather than in the parameter list: `t()` must resolve at
// render, and a default expression in the signature runs before the hook.
const resolvedCleanLabel = cleanLabel ?? t("common:save");
return (
<Button
type="button"
@@ -37,7 +43,7 @@ export function UnsavedSaveButton({
className={isDirty ? dirtyButtonClass : "cursor-pointer"}
>
{isDirty && <IconAlertCircle className="h-4 w-4 mr-2" />}
{isDirty ? "Save" : cleanLabel}
{isDirty ? t("common:save") : resolvedCleanLabel}
{status !== "idle" && (
<span className="ml-2">
<RequestIndicator status={status} />