Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(workspace): derive new issue prefixes from the slug, editable at create (#6815)

Bohan Jiang5e569fa38ace
diff --git a/apps/docs/content/docs/workspaces.ja.mdx b/apps/docs/content/docs/workspaces.ja.mdx
index 4250715079..3104e65b7c 100644
--- a/apps/docs/content/docs/workspaces.ja.mdx
+++ b/apps/docs/content/docs/workspaces.ja.mdx
@@ -20,12 +20,13 @@ import { Callout } from "fumadocs-ui/components/callout";
## ワークスペースの作成
-作成時に入力するのは 2 つです。
+作成時に入力するのは 3 つです。
- **名前**: メンバーに表示されます。後から変更できます。
- **ワークスペース URL**: アドレスに使われる slug です。`multica.ai/my-team` の `my-team` にあたります。小文字、数字、ハイフンのみが使え、既存のワークスペースや予約済みアドレスとは重複できず、作成後は変更できません。
+- **イシュー接頭辞**: ワークスペース URL から自動で入力され、作成前に変更できます。接頭辞が `MUL` の場合、イシュー番号は `MUL-1`、`MUL-2` と表示され、ワークスペース内で独立して増えていきます。大文字と数字のみ、最大 10 文字で、あとから設定でも変更できます。
-作成者は自動的に `owner` になります。イシュー接頭辞はワークスペース名から自動生成され、接頭辞が `MUL` の場合、イシュー番号は `MUL-1`、`MUL-2` と表示され、ワークスペース内で独立して増えていきます。
+作成者は自動的に `owner` になります。
## 設定の変更
diff --git a/apps/docs/content/docs/workspaces.ko.mdx b/apps/docs/content/docs/workspaces.ko.mdx
index e4ff4666c3..9f75cf74d6 100644
--- a/apps/docs/content/docs/workspaces.ko.mdx
+++ b/apps/docs/content/docs/workspaces.ko.mdx
@@ -20,12 +20,13 @@ import { Callout } from "fumadocs-ui/components/callout";
## 워크스페이스 만들기
-만들 때 두 항목을 입력합니다.
+만들 때 세 항목을 입력합니다.
- **이름**: 멤버에게 표시되며 나중에 변경할 수 있습니다.
- **워크스페이스 URL**: 주소에 들어가는 slug입니다. 예를 들어 `multica.ai/my-team`의 `my-team`입니다. 소문자, 숫자, 하이픈만 사용할 수 있고 기존 워크스페이스 또는 예약된 주소와 중복될 수 없으며 만든 뒤에는 변경할 수 없습니다.
+- **이슈 접두사**: 워크스페이스 URL에서 자동으로 채워지며 만들기 전에 바꿀 수 있습니다. 접두사가 `MUL`이면 이슈 번호는 `MUL-1`, `MUL-2`처럼 표시되며 워크스페이스 안에서 독립적으로 증가합니다. 대문자와 숫자만, 최대 10자이며 나중에 설정에서도 바꿀 수 있습니다.
-만든 사람은 자동으로 `owner`가 됩니다. 이슈 접두사는 워크스페이스 이름에서 자동으로 생성됩니다. 예를 들어 접두사가 `MUL`이면 이슈 번호는 `MUL-1`, `MUL-2`처럼 표시되며 워크스페이스 안에서 독립적으로 증가합니다.
+만든 사람은 자동으로 `owner`가 됩니다.
## 설정 변경
diff --git a/apps/docs/content/docs/workspaces.mdx b/apps/docs/content/docs/workspaces.mdx
index 442cc3bcf0..39d62ed4d5 100644
--- a/apps/docs/content/docs/workspaces.mdx
+++ b/apps/docs/content/docs/workspaces.mdx
@@ -20,12 +20,13 @@ A workspace is Multica's top-level boundary. Members, issues, projects, agents,
## Create a workspace
-Creating a workspace asks for two things:
+Creating a workspace asks for three things:
- **Name**: shown to members; can be changed later.
- **Workspace URL**: the slug in the address — the `my-team` in `multica.ai/my-team`. Lowercase letters, digits, and hyphens only; it cannot collide with an existing workspace or a reserved address, and it cannot be changed after creation.
+- **Issue prefix**: pre-filled from the workspace URL and editable before you create — with the prefix `MUL`, issue numbers appear as `MUL-1`, `MUL-2`, counting up independently within the workspace. Uppercase letters and digits, up to 10 characters; it can be changed later in settings.
-The creator automatically becomes an `owner`. The issue prefix is generated from the workspace name — with the prefix `MUL`, issue numbers appear as `MUL-1`, `MUL-2`, counting up independently within the workspace.
+The creator automatically becomes an `owner`.
## Change settings
diff --git a/apps/docs/content/docs/workspaces.zh.mdx b/apps/docs/content/docs/workspaces.zh.mdx
index 162118b804..e86a011944 100644
--- a/apps/docs/content/docs/workspaces.zh.mdx
+++ b/apps/docs/content/docs/workspaces.zh.mdx
@@ -20,12 +20,13 @@ import { Callout } from "fumadocs-ui/components/callout";
## 创建工作区
-创建时填两项:
+创建时填三项:
- **名称**:展示给成员,之后可以修改。
- **工作区 URL**:地址中的 slug,例如 `multica.ai/my-team` 里的 `my-team`。只能用小写字母、数字和连字符,不能与已有工作区或保留地址重复,创建后不可修改。
+- **issue 前缀**:根据工作区 URL 自动填好,创建前可以改。前缀为 `MUL` 时,issue 编号显示为 `MUL-1`、`MUL-2`,在工作区内独立递增。只能用大写字母和数字,最多 10 位,之后也可以在设置里修改。
-创建者自动成为 `owner`。issue 前缀由工作区名称自动生成,例如前缀为 `MUL` 时,issue 编号显示为 `MUL-1`、`MUL-2`,在工作区内独立递增。
+创建者自动成为 `owner`。
## 修改设置
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index d7460de6bb..994d9c2afe 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -2164,7 +2164,7 @@ export class ApiClient {
return this.fetch(`/api/workspaces/${id}`);
}
- async createWorkspace(data: { name: string; slug: string; description?: string; context?: string }): Promise<Workspace> {
+ async createWorkspace(data: { name: string; slug: string; description?: string; context?: string; issue_prefix?: string }): Promise<Workspace> {
return this.fetch("/api/workspaces", {
method: "POST",
body: JSON.stringify(data),
diff --git a/packages/core/workspace/mutations.ts b/packages/core/workspace/mutations.ts
index 0c2ed6261c..d9cef177cc 100644
--- a/packages/core/workspace/mutations.ts
+++ b/packages/core/workspace/mutations.ts
@@ -12,8 +12,13 @@ import {
export function useCreateWorkspace() {
const qc = useQueryClient();
return useMutation({
- mutationFn: (data: { name: string; slug: string; description?: string }) =>
- api.createWorkspace(data),
+ mutationFn: (data: {
+ name: string;
+ slug: string;
+ description?: string;
+ /** Omit to let the server derive it from the slug. */
+ issue_prefix?: string;
+ }) => api.createWorkspace(data),
// Seed the workspace list cache BEFORE callers navigate to /{newWs.slug}/issues.
// The destination [workspaceSlug]/layout queries by slug from this cache;
// without seeding, it would briefly show "loading" before the background
diff --git a/packages/views/onboarding/steps/step-workspace.test.tsx b/packages/views/onboarding/steps/step-workspace.test.tsx
index 6b801308b0..7299d96fe6 100644
--- a/packages/views/onboarding/steps/step-workspace.test.tsx
+++ b/packages/views/onboarding/steps/step-workspace.test.tsx
@@ -36,8 +36,10 @@ vi.mock("@multica/core/config", () => ({
mockUseConfigStore(selector),
}));
+const mockCreateMutate = vi.hoisted(() => vi.fn());
+
vi.mock("@multica/core/workspace/mutations", () => ({
- useCreateWorkspace: () => ({ mutate: vi.fn(), isPending: false }),
+ useCreateWorkspace: () => ({ mutate: mockCreateMutate, isPending: false }),
}));
vi.mock("@multica/core/api", () => ({
@@ -182,3 +184,101 @@ describe("StepWorkspace — random workspace identity", () => {
);
});
});
+
+// MUL-6050: the issue prefix used to be a read-only preview derived
+// server-side from the workspace NAME, so every workspace named in Chinese
+// (or Japanese, Korean, emoji…) was created as "WS" with no way to change it
+// in the create flow. It now derives from the slug — which the same form
+// already forces the user to pick in ASCII — and is editable here.
+describe("StepWorkspace — issue prefix", () => {
+ const prefixInput = () =>
+ screen.getByLabelText("Issue prefix") as HTMLInputElement;
+
+ it("derives the prefix from the slug, not the name", () => {
+ renderStep({ existing: null, disabled: false });
+
+ fireEvent.change(screen.getByLabelText("Workspace name"), {
+ target: { value: "Acme Inc" },
+ });
+
+ // Slug auto-filled to "acme-inc" → first 4 alphanumerics, uppercased.
+ expect(prefixInput().value).toBe("ACME");
+ expect(screen.getByText("ACME-123")).toBeInTheDocument();
+ });
+
+ it("gives a Chinese-named workspace a slug-derived prefix instead of WS", () => {
+ renderStep({ existing: null, disabled: false });
+
+ // A CJK-only name produces no slug, so the user types one — that ASCII
+ // choice is what the prefix now follows.
+ fireEvent.change(screen.getByLabelText("Workspace name"), {
+ target: { value: "前端团队" },
+ });
+ fireEvent.change(screen.getByLabelText("URL"), {
+ target: { value: "frontend" },
+ });
+
+ expect(prefixInput().value).toBe("FRON");
+ expect(prefixInput().value).not.toBe("WS");
+ });
+
+ it("stops following the slug once the user edits it, and normalizes input", () => {
+ renderStep({ existing: null, disabled: false });
+
+ fireEvent.change(screen.getByLabelText("Workspace name"), {
+ target: { value: "Acme Inc" },
+ });
+ fireEvent.change(prefixInput(), { target: { value: "fe-team!" } });
+
+ // Uppercased, non-alphanumerics dropped — matching the server's
+ // `^[A-Z0-9]{1,10}$` rule and the settings tab's guardrail.
+ expect(prefixInput().value).toBe("FETEAM");
+
+ // A later slug edit must not clobber the user's choice.
+ fireEvent.change(screen.getByLabelText("URL"), {
+ target: { value: "acme-corp" },
+ });
+ expect(prefixInput().value).toBe("FETEAM");
+ expect(screen.getByText("FETEAM-123")).toBeInTheDocument();
+ });
+
+ it("submits the prefix the user was shown", () => {
+ mockCreateMutate.mockClear();
+ renderStep({ existing: null, disabled: false });
+
+ fireEvent.change(screen.getByLabelText("Workspace name"), {
+ target: { value: "前端团队" },
+ });
+ fireEvent.change(screen.getByLabelText("URL"), {
+ target: { value: "frontend" },
+ });
+ fireEvent.change(prefixInput(), { target: { value: "fe" } });
+ fireEvent.click(screen.getByRole("button", { name: /^Create 前端团队$/ }));
+
+ expect(mockCreateMutate).toHaveBeenCalledTimes(1);
+ expect(mockCreateMutate.mock.calls[0]![0]).toEqual({
+ name: "前端团队",
+ slug: "frontend",
+ issue_prefix: "FE",
+ });
+ });
+
+ it("falls back to the slug-derived default when the field is cleared", () => {
+ mockCreateMutate.mockClear();
+ renderStep({ existing: null, disabled: false });
+
+ fireEvent.change(screen.getByLabelText("Workspace name"), {
+ target: { value: "Acme Inc" },
+ });
+ fireEvent.change(prefixInput(), { target: { value: "" } });
+
+ // Empty input doesn't block the CTA: the placeholder already shows the
+ // default that will be used, so submitting an empty field can't surprise.
+ expect(prefixInput().placeholder).toBe("ACME");
+ fireEvent.click(screen.getByRole("button", { name: /^Create Acme Inc$/ }));
+
+ expect(mockCreateMutate.mock.calls[0]![0]).toMatchObject({
+ issue_prefix: "ACME",
+ });
+ });
+});
diff --git a/packages/views/onboarding/steps/step-workspace.tsx b/packages/views/onboarding/steps/step-workspace.tsx
index 7920989bf5..171f446b4d 100644
--- a/packages/views/onboarding/steps/step-workspace.tsx
+++ b/packages/views/onboarding/steps/step-workspace.tsx
@@ -11,7 +11,6 @@ import {
FieldError,
FieldGroup,
FieldLabel,
- FieldTitle,
} from "@multica/ui/components/ui/field";
import { cn } from "@multica/ui/lib/utils";
import { useCreateWorkspace } from "@multica/core/workspace/mutations";
@@ -54,7 +53,10 @@ import { isReservedSlug } from "@multica/core/paths";
* app URL so self-hosted instances show their own domain), and a live
* `Issues will look
* like ACME-123` line shows the user what their issue IDs will read
- * like before they've created anything.
+ * like before they've created anything. The issue prefix behind that line
+ * is an editable field pre-filled from the slug (MUL-6050) — it used to be
+ * read-only, which left every non-ASCII-named workspace stuck on the
+ * server's old `WS` fallback with no in-flow way out.
*
* Resume path ships two picker cards (existing + create-new) and the
* user toggles between them. No-existing path just shows the create
@@ -62,11 +64,26 @@ import { isReservedSlug } from "@multica/core/paths";
*/
function issuePrefix(slug: string): string {
- // Mirrors the server's default prefix derivation — first 4 chars of
- // the slug, uppercased. Falls back to "WS" when the slug is empty so
- // the preview line never collapses to a single dangling "-".
- const head = slug.trim().replace(/[^a-z0-9]/g, "").slice(0, 4);
- return (head || "ws").toUpperCase();
+ // Mirrors the server's default prefix derivation
+ // (handler.defaultIssuePrefixFromSlug) — alphanumerics of the slug, first
+ // 4 chars, uppercased. Lowercase first because the server lowercases the
+ // slug before deriving, so a user who types "ACME" here sees the same
+ // "ACME" the server would produce rather than an empty strip. Returns ""
+ // for a slug with nothing to derive from; that slug can't be submitted, so
+ // only the preview has to cope with it.
+ return slug
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]/g, "")
+ .slice(0, 4)
+ .toUpperCase();
+}
+
+// Letters + digits only, uppercase, capped at 10 — the same guardrail the
+// settings tab applies, and the same shape the server now validates
+// (`^[A-Z0-9]{1,10}$`).
+function normalizePrefix(raw: string): string {
+ return raw.toUpperCase().replace(/[^A-Z0-9]/g, "").slice(0, 10);
}
export function StepWorkspace({
@@ -116,6 +133,12 @@ export function StepWorkspace({
const [slug, setSlug] = useState("");
const [slugServerError, setSlugServerError] = useState<string | null>(null);
const slugTouched = useRef(false);
+ // Prefix follows the slug the same way the slug follows the name, and stops
+ // following the moment the user edits it (MUL-6050). Editable here because
+ // settings was the only place to change it, and a user who never noticed the
+ // default would never go looking.
+ const [prefix, setPrefix] = useState("");
+ const prefixTouched = useRef(false);
const slugValidationError =
slug.length > 0 && !WORKSPACE_SLUG_REGEX.test(slug)
@@ -129,26 +152,44 @@ export function StepWorkspace({
const canCreate =
name.trim().length > 0 && slug.trim().length > 0 && !slugError;
+ // What the workspace will actually be created with. Clearing the prefix
+ // input reverts to the slug-derived default rather than blocking the CTA —
+ // the placeholder shows that default, so an empty field is never a
+ // surprise. A valid slug always derives something, so this is only empty
+ // while the form itself can't be submitted.
+ const derivedPrefix = issuePrefix(slug);
+ const effectivePrefix = prefix || derivedPrefix;
+
+ // Every slug write goes through here so the untouched prefix can't drift
+ // out of sync with the slug it is derived from.
+ const applySlug = (value: string) => {
+ setSlug(value);
+ setSlugServerError(null);
+ if (!prefixTouched.current) setPrefix(issuePrefix(value));
+ };
+
const handleNameChange = (value: string) => {
setName(value);
if (!slugTouched.current) {
- setSlug(nameToWorkspaceSlug(value));
- setSlugServerError(null);
+ applySlug(nameToWorkspaceSlug(value));
}
};
const handleSlugChange = (value: string) => {
slugTouched.current = true;
- setSlug(value);
- setSlugServerError(null);
+ applySlug(value);
+ };
+
+ const handlePrefixChange = (value: string) => {
+ prefixTouched.current = true;
+ setPrefix(normalizePrefix(value));
};
const handleRandomName = () => {
const identity = randomCelestialWorkspaceIdentity(locale);
slugTouched.current = true;
setName(identity.name);
- setSlug(identity.slug);
- setSlugServerError(null);
+ applySlug(identity.slug);
};
const createWorkspace = useCreateWorkspace();
@@ -156,7 +197,15 @@ export function StepWorkspace({
const handleCreate = () => {
if (!canCreate || createWorkspace.isPending) return;
createWorkspace.mutate(
- { name: name.trim(), slug: slug.trim() },
+ {
+ name: name.trim(),
+ slug: slug.trim(),
+ // Send what the user was shown. The server derives the same value
+ // from the slug when the field is omitted, so the preview and the
+ // created workspace agree either way — but submitting it explicitly
+ // is what makes an edited prefix stick.
+ issue_prefix: effectivePrefix,
+ },
{
onSuccess: onCreated,
onError: (error) => {
@@ -289,14 +338,32 @@ export function StepWorkspace({
</div>
{slugError ? <FieldError>{slugError}</FieldError> : null}
</Field>
- {/* Derived, not entered — FieldTitle rather than FieldLabel, since
- there is no control for a label to point at. */}
+ {/* Editable, pre-filled from the slug. Narrow input — the value is
+ capped at 10 chars, so a full-width field would read as a mistake. */}
<Field>
- <FieldTitle>{t(($) => $.step_workspace.issue_prefix_label)}</FieldTitle>
+ <FieldLabel htmlFor="ws-issue-prefix">
+ {t(($) => $.step_workspace.issue_prefix_label)}
+ </FieldLabel>
+ <Input
+ id="ws-issue-prefix"
+ type="text"
+ value={prefix}
+ onChange={(e) => handlePrefixChange(e.target.value)}
+ placeholder={derivedPrefix || "WS"}
+ autoComplete="off"
+ autoCapitalize="characters"
+ spellCheck={false}
+ maxLength={10}
+ className="w-32 font-mono uppercase"
+ onKeyDown={(e) => {
+ if (isImeComposing(e)) return;
+ if (e.key === "Enter") handleCreate();
+ }}
+ />
<FieldDescription>
{t(($) => $.step_workspace.issue_prefix_prefix)}
<span className="font-mono text-foreground">
- {issuePrefix(slug)}-123
+ {effectivePrefix || "WS"}-123
</span>
{t(($) => $.step_workspace.issue_prefix_suffix)}
</FieldDescription>
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index bfbefdaef7..f49512b6cf 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -992,11 +992,17 @@ func splitIdentifier(id string) *identifierParts {
// introduced). Split out from getIssuePrefix so callers that already hold the
// row — such as the GitHub close-intent scan, which must not re-read it — can
// reuse the rule.
+//
+// The empty-prefix fallback stays on the FROZEN name-based derivation, not the
+// slug-based one new workspaces get (MUL-6050): identifiers are computed at
+// read time, so switching this path would rewrite the identifier of every
+// issue in those legacy workspaces. New workspaces always persist a prefix at
+// creation, so they never reach this branch.
func issuePrefixForWorkspace(ws db.Workspace) string {
if ws.IssuePrefix != "" {
return ws.IssuePrefix
}
- return generateIssuePrefix(ws.Name)
+ return legacyIssuePrefixFromName(ws.Name)
}
// getIssuePrefix fetches the effective issue_prefix for a workspace, and
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index beef59b18c..ecd63b87f0 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -22,11 +22,47 @@ import (
)
var nonAlpha = regexp.MustCompile(`[^a-zA-Z]`)
+var nonAlphanumeric = regexp.MustCompile(`[^a-zA-Z0-9]`)
var workspaceSlugPattern = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
+var issuePrefixPattern = regexp.MustCompile(`^[A-Z0-9]{1,10}$`)
-// generateIssuePrefix produces a 2-5 char uppercase prefix from a workspace name.
-// Examples: "Jiayuan's Workspace" → "JIA", "My Team" → "MYT", "AB" → "AB".
-func generateIssuePrefix(name string) string {
+// defaultIssuePrefixFromSlug derives a new workspace's default issue prefix
+// from its slug: alphanumerics only, first 4 chars, uppercased.
+// Examples: "acme" → "ACME", "front-end" → "FRON", "team-2" → "TEAM".
+//
+// The slug — not the name — is the derivation source on purpose (MUL-6050).
+// Name is the one field in the create flow that accepts non-ASCII, so deriving
+// an ASCII-only prefix from it forced every CJK/emoji-named workspace onto the
+// same "WS" fallback. Slug is validated as `^[a-z0-9]+(-[a-z0-9]+)*$` and
+// required, so it always yields a non-empty, workspace-specific prefix.
+//
+// Kept byte-for-byte in sync with the client-side preview in
+// packages/views/onboarding/steps/step-workspace.tsx — what the user sees on
+// the create screen has to be what the server would derive.
+func defaultIssuePrefixFromSlug(slug string) string {
+ head := nonAlphanumeric.ReplaceAllString(slug, "")
+ if head == "" {
+ // Unreachable for a validated slug; keeps the function total so a
+ // future caller can never persist an empty prefix.
+ return "WS"
+ }
+ if len(head) > 4 {
+ head = head[:4]
+ }
+ return strings.ToUpper(head)
+}
+
+// legacyIssuePrefixFromName is the pre-MUL-6050 derivation: first 3 ASCII
+// letters of the workspace name, uppercased, "WS" when the name has none.
+//
+// FROZEN — do not "fix" this to match defaultIssuePrefixFromSlug. Its only
+// caller is getIssuePrefix's fallback for workspaces whose stored prefix is
+// empty (rows predating the column). Issue identifiers are computed at read
+// time from the current prefix, so changing what this returns would silently
+// rewrite the identifier of every historical issue in those workspaces.
+// Deliberate product decision: no backfill, existing workspaces stay as they
+// are; only newly created ones follow the slug-derived rule.
+func legacyIssuePrefixFromName(name string) string {
letters := nonAlpha.ReplaceAllString(name, "")
if len(letters) == 0 {
return "WS"
@@ -38,6 +74,24 @@ func generateIssuePrefix(name string) string {
return letters
}
+// normalizeIssuePrefix trims and uppercases a client-supplied issue prefix.
+// An all-whitespace value means "not provided" and reports ("", true) so the
+// caller can fall back to its default. Anything else must be 1-10 chars of
+// A-Z0-9, mirroring the client-side guardrail in
+// packages/views/settings/components/workspace-tab.tsx.
+func normalizeIssuePrefix(raw string) (string, bool) {
+ prefix := strings.ToUpper(strings.TrimSpace(raw))
+ if prefix == "" {
+ return "", true
+ }
+ if !issuePrefixPattern.MatchString(prefix) {
+ return "", false
+ }
+ return prefix, true
+}
+
+const issuePrefixFormatError = "issue prefix must be 1-10 uppercase letters or digits"
+
type WorkspaceResponse struct {
ID string `json:"id"`
Name string `json:"name"`
@@ -180,6 +234,21 @@ func (h *Handler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {
return
}
+ // Resolve the prefix before opening the transaction: an invalid one is a
+ // 400 that should never cost a connection.
+ issuePrefix := ""
+ if req.IssuePrefix != nil {
+ prefix, ok := normalizeIssuePrefix(*req.IssuePrefix)
+ if !ok {
+ writeError(w, http.StatusBadRequest, issuePrefixFormatError)
+ return
+ }
+ issuePrefix = prefix
+ }
+ if issuePrefix == "" {
+ issuePrefix = defaultIssuePrefixFromSlug(req.Slug)
+ }
+
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to create workspace")
@@ -187,11 +256,6 @@ func (h *Handler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {
}
defer tx.Rollback(r.Context())
- issuePrefix := generateIssuePrefix(req.Name)
- if req.IssuePrefix != nil && strings.TrimSpace(*req.IssuePrefix) != "" {
- issuePrefix = strings.ToUpper(strings.TrimSpace(*req.IssuePrefix))
- }
-
qtx := h.Queries.WithTx(tx)
ws, err := qtx.CreateWorkspace(r.Context(), db.CreateWorkspaceParams{
Name: req.Name,
@@ -339,7 +403,11 @@ func (h *Handler) UpdateWorkspace(w http.ResponseWriter, r *http.Request) {
params.Repos = reposJSON
}
if req.IssuePrefix != nil {
- prefix := strings.ToUpper(strings.TrimSpace(*req.IssuePrefix))
+ prefix, ok := normalizeIssuePrefix(*req.IssuePrefix)
+ if !ok {
+ writeError(w, http.StatusBadRequest, issuePrefixFormatError)
+ return
+ }
if prefix != "" {
params.IssuePrefix = pgtype.Text{String: prefix, Valid: true}
}
diff --git a/server/internal/handler/workspace_test.go b/server/internal/handler/workspace_test.go
index 9ec93d3609..156ea76498 100644
--- a/server/internal/handler/workspace_test.go
+++ b/server/internal/handler/workspace_test.go
@@ -12,6 +12,8 @@ import (
"strings"
"testing"
"time"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
)
func TestCreateWorkspace_RejectsReservedSlug(t *testing.T) {
@@ -1363,3 +1365,278 @@ INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'admin') RETURN
t.Fatal("member row was not deleted")
}
}
+
+// TestDefaultIssuePrefixFromSlug pins the derivation new workspaces get
+// (MUL-6050): alphanumerics of the slug, first 4, uppercased. The Chinese
+// cases are the point of the change — under the old name-based derivation
+// every one of them collapsed to "WS".
+//
+// Keep this table in sync with the client-side preview
+// (packages/views/onboarding/steps/step-workspace.tsx). If the two ever
+// disagree, the create screen lies about the identifier the user will get.
+func TestDefaultIssuePrefixFromSlug(t *testing.T) {
+ cases := []struct {
+ slug string
+ want string
+ }{
+ {"acme", "ACME"},
+ {"front-end", "FRON"},
+ {"growth", "GROW"},
+ {"team-2", "TEAM"},
+ {"a1b2c3", "A1B2"},
+ {"ab", "AB"},
+ {"x", "X"},
+ // Slugs the create handler would have rejected anyway; the function
+ // stays total so no caller can persist an empty prefix.
+ {"", "WS"},
+ {"--", "WS"},
+ }
+
+ for _, tc := range cases {
+ if got := defaultIssuePrefixFromSlug(tc.slug); got != tc.want {
+ t.Errorf("defaultIssuePrefixFromSlug(%q) = %q, want %q", tc.slug, got, tc.want)
+ }
+ }
+}
+
+// TestLegacyIssuePrefixFromName_Frozen guards the read-time fallback for
+// workspaces whose stored prefix is empty. Issue identifiers are computed
+// from the current prefix on every read, so changing what this returns would
+// silently rewrite the identifier of every historical issue in those
+// workspaces. The product decision on MUL-6050 was explicit: no backfill,
+// existing workspaces are left exactly as they are — which means this
+// function must keep returning what it always did, including "WS" for
+// non-ASCII names.
+func TestLegacyIssuePrefixFromName_Frozen(t *testing.T) {
+ cases := []struct {
+ name string
+ want string
+ }{
+ {"Jiayuan's Workspace", "JIA"},
+ {"My Team", "MYT"},
+ {"AB", "AB"},
+ {"Team 2", "TEA"},
+ {"前端团队", "WS"},
+ {"", "WS"},
+ }
+
+ for _, tc := range cases {
+ if got := legacyIssuePrefixFromName(tc.name); got != tc.want {
+ t.Errorf("legacyIssuePrefixFromName(%q) = %q, want %q — this function is frozen; changing it rewrites existing issue identifiers", tc.name, got, tc.want)
+ }
+ }
+}
+
+// TestIssuePrefixForWorkspace_LegacyFallbackFrozen guards the resolution rule
+// itself, at the seam every read-time caller goes through (getIssuePrefix and
+// the GitHub close-intent scan, which holds the row already).
+//
+// A stored prefix always wins; only an empty one falls back, and that fallback
+// must stay on the old name-based derivation. Pointing it at
+// defaultIssuePrefixFromSlug would rewrite the identifier of every issue in
+// those legacy workspaces on the next read — the exact outcome the "no
+// backfill, leave existing workspaces alone" decision on MUL-6050 rules out.
+func TestIssuePrefixForWorkspace_LegacyFallbackFrozen(t *testing.T) {
+ cases := []struct {
+ label string
+ ws db.Workspace
+ want string
+ }{
+ {"stored prefix wins", db.Workspace{Name: "前端团队", Slug: "frontend", IssuePrefix: "FE"}, "FE"},
+ {"empty prefix, CJK name", db.Workspace{Name: "前端团队", Slug: "frontend"}, "WS"},
+ {"empty prefix, ASCII name", db.Workspace{Name: "My Team", Slug: "my-team"}, "MYT"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.label, func(t *testing.T) {
+ if got := issuePrefixForWorkspace(tc.ws); got != tc.want {
+ t.Fatalf("issuePrefixForWorkspace(%+v) = %q, want %q — legacy workspaces must keep the identifiers they already have", tc.ws, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestNormalizeIssuePrefix(t *testing.T) {
+ cases := []struct {
+ raw string
+ want string
+ valid bool
+ }{
+ {"acme", "ACME", true},
+ {" acme ", "ACME", true},
+ {"AB12", "AB12", true},
+ {"ABCDEFGHIJ", "ABCDEFGHIJ", true},
+ // Absent / blank means "use the default", not "invalid".
+ {"", "", true},
+ {" ", "", true},
+ // Rejections the API accepted before MUL-6050.
+ {"ABCDEFGHIJK", "", false},
+ {"前端", "", false},
+ {"AB-CD", "", false},
+ {"AB CD", "", false},
+ {"AB_CD", "", false},
+ }
+
+ for _, tc := range cases {
+ got, ok := normalizeIssuePrefix(tc.raw)
+ if ok != tc.valid {
+ t.Errorf("normalizeIssuePrefix(%q) valid = %v, want %v", tc.raw, ok, tc.valid)
+ continue
+ }
+ if got != tc.want {
+ t.Errorf("normalizeIssuePrefix(%q) = %q, want %q", tc.raw, got, tc.want)
+ }
+ }
+}
+
+// TestCreateWorkspace_ChineseNameDerivesPrefixFromSlug is the end-to-end
+// regression for MUL-6050: a workspace whose name has no ASCII letters used
+// to be created with prefix "WS" — deterministically, for every Chinese team
+// on the instance. It must now take its prefix from the slug, which the same
+// form already forced the user to choose in ASCII.
+func TestCreateWorkspace_ChineseNameDerivesPrefixFromSlug(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ const slug = "handler-tests-frontend-team"
+ _, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE slug = $1`, slug)
+ })
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/workspaces", map[string]any{
+ "name": "前端团队",
+ "slug": slug,
+ })
+ testHandler.CreateWorkspace(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateWorkspace: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp WorkspaceResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if resp.IssuePrefix != "HAND" {
+ t.Fatalf("issue_prefix = %q, want %q (derived from the slug, not the name)", resp.IssuePrefix, "HAND")
+ }
+ if resp.IssuePrefix == "WS" {
+ t.Fatal("issue_prefix fell back to WS — the MUL-6050 regression is back")
+ }
+}
+
+// TestCreateWorkspace_HonorsExplicitIssuePrefix covers the create screen's new
+// editable prefix field: whatever the user typed is what gets persisted.
+func TestCreateWorkspace_HonorsExplicitIssuePrefix(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ const slug = "handler-tests-explicit-prefix"
+ _, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE slug = $1`, slug)
+ })
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/workspaces", map[string]any{
+ "name": "前端团队",
+ "slug": slug,
+ "issue_prefix": "fe",
+ })
+ testHandler.CreateWorkspace(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateWorkspace: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp WorkspaceResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if resp.IssuePrefix != "FE" {
+ t.Fatalf("issue_prefix = %q, want %q", resp.IssuePrefix, "FE")
+ }
+}
+
+// TestCreateWorkspace_RejectsInvalidIssuePrefix closes the API-side hole the
+// settings UI already guarded: before MUL-6050 the create and update handlers
+// only trimmed and uppercased the caller-supplied prefix, so a direct API call
+// could persist CJK text or a 100-character string as an issue prefix.
+func TestCreateWorkspace_RejectsInvalidIssuePrefix(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ invalid := map[string]string{
+ "non-ascii": "前端",
+ "too-long": "ABCDEFGHIJK",
+ "hyphenated": "AB-CD",
+ "spaced": "AB CD",
+ }
+
+ for label, prefix := range invalid {
+ t.Run(label, func(t *testing.T) {
+ slug := "handler-tests-bad-prefix-" + label
+ ctx := context.Background()
+ _, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE slug = $1`, slug)
+ })
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/workspaces", map[string]any{
+ "name": "Prefix Validation Probe",
+ "slug": slug,
+ "issue_prefix": prefix,
+ })
+ testHandler.CreateWorkspace(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("issue_prefix %q: expected 400, got %d: %s", prefix, w.Code, w.Body.String())
+ }
+
+ var count int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM workspace WHERE slug = $1`, slug).Scan(&count); err != nil {
+ t.Fatalf("count workspaces: %v", err)
+ }
+ if count != 0 {
+ t.Fatalf("expected no workspace row for a rejected prefix, found %d", count)
+ }
+ })
+ }
+}
+
+// TestUpdateWorkspace_RejectsInvalidIssuePrefix is the PATCH half of the same
+// hole: settings normalizes client-side, but the endpoint took anything.
+func TestUpdateWorkspace_RejectsInvalidIssuePrefix(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ var before string
+ if err := testPool.QueryRow(ctx, `SELECT issue_prefix FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&before); err != nil {
+ t.Fatalf("read current prefix: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := withURLParam(
+ newRequest("PATCH", "/api/workspaces/"+testWorkspaceID, map[string]any{"issue_prefix": "前端团队前端团队前端"}),
+ "id", testWorkspaceID,
+ )
+ testHandler.UpdateWorkspace(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for a non-ASCII issue_prefix, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var after string
+ if err := testPool.QueryRow(ctx, `SELECT issue_prefix FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&after); err != nil {
+ t.Fatalf("re-read prefix: %v", err)
+ }
+ if after != before {
+ t.Fatalf("issue_prefix changed on a rejected update: %q → %q", before, after)
+ }
+}