Skip to content

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

Go

fix(workspace): surface slug conflicts (#895)

Jiayuan Zhang5b4ee7c5e172
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
new file mode 100644
index 0000000000..ca21ea7466
--- /dev/null
+++ b/packages/core/api/client.test.ts
@@ -0,0 +1,35 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { ApiClient, ApiError } from "./client";
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("ApiClient", () => {
+ it("preserves HTTP status on failed requests", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ error: "workspace slug already exists" }), {
+ status: 409,
+ statusText: "Conflict",
+ headers: { "Content-Type": "application/json" },
+ }),
+ ),
+ );
+
+ const client = new ApiClient("https://api.example.test");
+
+ try {
+ await client.createWorkspace({ name: "Test", slug: "test" });
+ throw new Error("expected createWorkspace to fail");
+ } catch (error) {
+ expect(error).toBeInstanceOf(ApiError);
+ expect(error).toMatchObject({
+ message: "workspace slug already exists",
+ status: 409,
+ statusText: "Conflict",
+ });
+ }
+ });
+});
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 9aa8033ea0..4dfc6fd2d6 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -64,6 +64,18 @@ export interface LoginResponse {
user: User;
}
+export class ApiError extends Error {
+ readonly status: number;
+ readonly statusText: string;
+
+ constructor(message: string, status: number, statusText: string) {
+ super(message);
+ this.name = "ApiError";
+ this.status = status;
+ this.statusText = statusText;
+ }
+}
+
export class ApiClient {
private baseUrl: string;
private token: string | null = null;
@@ -147,7 +159,7 @@ export class ApiClient {
const message = await this.parseErrorMessage(res, `API error: ${res.status} ${res.statusText}`);
const logLevel = res.status === 404 ? "warn" : "error";
this.logger[logLevel](`← ${res.status} ${path}`, { rid, duration: `${Date.now() - start}ms`, error: message });
- throw new Error(message);
+ throw new ApiError(message, res.status, res.statusText);
}
this.logger.info(`← ${res.status} ${path}`, { rid, duration: `${Date.now() - start}ms` });
diff --git a/packages/core/api/index.ts b/packages/core/api/index.ts
index 9efbffb471..ea9372db84 100644
--- a/packages/core/api/index.ts
+++ b/packages/core/api/index.ts
@@ -1,4 +1,4 @@
-export { ApiClient } from "./client";
+export { ApiClient, ApiError } from "./client";
export type { ApiClientOptions } from "./client";
export { WSClient } from "./ws-client";
diff --git a/packages/core/modals/store.ts b/packages/core/modals/store.ts
index c434a0963b..f720be4339 100644
--- a/packages/core/modals/store.ts
+++ b/packages/core/modals/store.ts
@@ -2,7 +2,7 @@
import { create } from "zustand";
-type ModalType = "create-issue" | null;
+type ModalType = "create-workspace" | "create-issue" | null;
interface ModalStore {
modal: ModalType;
diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsx
index e797cf45e9..5fb7aa45e1 100644
--- a/packages/views/layout/app-sidebar.tsx
+++ b/packages/views/layout/app-sidebar.tsx
@@ -279,7 +279,9 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
</DropdownMenuItem>
))}
<DropdownMenuItem
- onClick={() => push("/onboarding")}
+ onClick={() =>
+ useModalStore.getState().open("create-workspace")
+ }
>
<Plus className="h-3.5 w-3.5" />
Create workspace
diff --git a/packages/views/modals/create-issue.test.tsx b/packages/views/modals/create-issue.test.tsx
index cba838dc76..76f70228c0 100644
--- a/packages/views/modals/create-issue.test.tsx
+++ b/packages/views/modals/create-issue.test.tsx
@@ -59,10 +59,8 @@ vi.mock("@multica/core/api", () => ({
api: {},
}));
-vi.mock("../editor", () => ({
- useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),
- FileDropOverlay: () => null,
- ContentEditor: forwardRef(({ defaultValue, onUpdate, placeholder }: any, ref: any) => {
+vi.mock("../editor", () => {
+ const ContentEditor = forwardRef(({ defaultValue, onUpdate, placeholder }: any, ref: any) => {
const valueRef = useRef(defaultValue || "");
const [value, setValue] = useState(defaultValue || "");
useImperativeHandle(ref, () => ({
@@ -80,24 +78,31 @@ vi.mock("../editor", () => ({
}}
/>
);
- }),
- TitleEditor: ({ defaultValue, placeholder, onChange, onSubmit }: any) => {
- const [value, setValue] = useState(defaultValue || "");
- return (
- <input
- value={value}
- placeholder={placeholder}
- onChange={(e) => {
- setValue(e.target.value);
- onChange?.(e.target.value);
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter") onSubmit?.();
- }}
- />
- );
- },
-}));
+ });
+ ContentEditor.displayName = "ContentEditor";
+
+ return {
+ useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),
+ FileDropOverlay: () => null,
+ ContentEditor,
+ TitleEditor: ({ defaultValue, placeholder, onChange, onSubmit }: any) => {
+ const [value, setValue] = useState(defaultValue || "");
+ return (
+ <input
+ value={value}
+ placeholder={placeholder}
+ onChange={(e) => {
+ setValue(e.target.value);
+ onChange?.(e.target.value);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") onSubmit?.();
+ }}
+ />
+ );
+ },
+ };
+});
vi.mock("../issues/components", () => ({
StatusIcon: ({ status }: { status: string }) => <span data-testid="status-icon">{status}</span>,
diff --git a/packages/views/modals/create-workspace.test.tsx b/packages/views/modals/create-workspace.test.tsx
new file mode 100644
index 0000000000..51bab10bd7
--- /dev/null
+++ b/packages/views/modals/create-workspace.test.tsx
@@ -0,0 +1,109 @@
+import type { ReactNode } from "react";
+import { describe, expect, it, beforeEach, vi } from "vitest";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+
+const mockPush = vi.hoisted(() => vi.fn());
+const mockCreateWorkspaceMutate = vi.hoisted(() => vi.fn());
+const mockToastError = vi.hoisted(() => vi.fn());
+
+vi.mock("../navigation", () => ({
+ useNavigation: () => ({ push: mockPush }),
+}));
+
+vi.mock("@multica/core/workspace/mutations", () => ({
+ useCreateWorkspace: () => ({
+ mutate: mockCreateWorkspaceMutate,
+ isPending: false,
+ }),
+}));
+
+vi.mock("@multica/ui/components/ui/dialog", () => ({
+ Dialog: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DialogContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DialogTitle: ({ children }: { children: ReactNode }) => <h1>{children}</h1>,
+ DialogDescription: ({ children }: { children: ReactNode }) => (
+ <p>{children}</p>
+ ),
+}));
+
+vi.mock("sonner", () => ({
+ toast: {
+ error: mockToastError,
+ },
+}));
+
+import { CreateWorkspaceModal } from "./create-workspace";
+
+describe("CreateWorkspaceModal", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("auto-generates the slug until the user edits it", async () => {
+ const user = userEvent.setup();
+ render(<CreateWorkspaceModal onClose={vi.fn()} />);
+
+ const nameInput = screen.getByPlaceholderText("My Workspace");
+ const slugInput = screen.getByPlaceholderText("my-workspace");
+
+ await user.type(nameInput, "My Team");
+ expect(slugInput).toHaveValue("my-team");
+
+ await user.clear(slugInput);
+ await user.type(slugInput, "custom-team");
+ await user.clear(nameInput);
+ await user.type(nameInput, "Renamed Team");
+
+ expect(slugInput).toHaveValue("custom-team");
+ });
+
+ it("shows a specific slug conflict error on 409 responses", async () => {
+ const user = userEvent.setup();
+ mockCreateWorkspaceMutate.mockImplementation(
+ (
+ _data: unknown,
+ options: { onError: (error: unknown) => void },
+ ) => {
+ options.onError({ status: 409 });
+ },
+ );
+
+ render(<CreateWorkspaceModal onClose={vi.fn()} />);
+
+ await user.type(screen.getByPlaceholderText("My Workspace"), "My Team");
+ await user.click(screen.getByRole("button", { name: "Create workspace" }));
+
+ await waitFor(() => {
+ expect(
+ screen.getByText("That workspace URL is already taken."),
+ ).toBeInTheDocument();
+ });
+
+ expect(mockToastError).toHaveBeenCalledWith(
+ "Choose a different workspace URL",
+ );
+ expect(mockCreateWorkspaceMutate).toHaveBeenCalledWith(
+ { name: "My Team", slug: "my-team" },
+ expect.any(Object),
+ );
+ });
+
+ it("continues onboarding after successful creation", async () => {
+ const user = userEvent.setup();
+ const onClose = vi.fn();
+ mockCreateWorkspaceMutate.mockImplementation(
+ (_data: unknown, options: { onSuccess: () => void }) => {
+ options.onSuccess();
+ },
+ );
+
+ render(<CreateWorkspaceModal onClose={onClose} />);
+
+ await user.type(screen.getByPlaceholderText("My Workspace"), "My Team");
+ await user.click(screen.getByRole("button", { name: "Create workspace" }));
+
+ expect(onClose).toHaveBeenCalled();
+ expect(mockPush).toHaveBeenCalledWith("/onboarding");
+ });
+});
diff --git a/packages/views/modals/create-workspace.tsx b/packages/views/modals/create-workspace.tsx
new file mode 100644
index 0000000000..b6f02b3ad8
--- /dev/null
+++ b/packages/views/modals/create-workspace.tsx
@@ -0,0 +1,156 @@
+"use client";
+
+import { useRef, useState } from "react";
+import { useNavigation } from "../navigation";
+import { toast } from "sonner";
+import { ArrowLeft } from "lucide-react";
+import { Input } from "@multica/ui/components/ui/input";
+import { Label } from "@multica/ui/components/ui/label";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+ DialogDescription,
+} from "@multica/ui/components/ui/dialog";
+import { Card, CardContent } from "@multica/ui/components/ui/card";
+import { useCreateWorkspace } from "@multica/core/workspace/mutations";
+import {
+ WORKSPACE_SLUG_CONFLICT_ERROR,
+ WORKSPACE_SLUG_FORMAT_ERROR,
+ WORKSPACE_SLUG_REGEX,
+ isWorkspaceSlugConflict,
+ nameToWorkspaceSlug,
+} from "../workspace/slug";
+
+export function CreateWorkspaceModal({ onClose }: { onClose: () => void }) {
+ const router = useNavigation();
+ const createWorkspace = useCreateWorkspace();
+ const [name, setName] = useState("");
+ const [slug, setSlug] = useState("");
+ const [slugServerError, setSlugServerError] = useState<string | null>(null);
+ const slugTouched = useRef(false);
+
+ const slugValidationError =
+ slug.length > 0 && !WORKSPACE_SLUG_REGEX.test(slug)
+ ? WORKSPACE_SLUG_FORMAT_ERROR
+ : null;
+ const slugError = slugValidationError ?? slugServerError;
+
+ const canSubmit =
+ name.trim().length > 0 && slug.trim().length > 0 && !slugError;
+
+ const handleNameChange = (value: string) => {
+ setName(value);
+ if (!slugTouched.current) {
+ setSlug(nameToWorkspaceSlug(value));
+ setSlugServerError(null);
+ }
+ };
+
+ const handleSlugChange = (value: string) => {
+ slugTouched.current = true;
+ setSlug(value);
+ setSlugServerError(null);
+ };
+
+ const handleCreate = () => {
+ if (!canSubmit) return;
+ createWorkspace.mutate(
+ { name: name.trim(), slug: slug.trim() },
+ {
+ onSuccess: () => {
+ onClose();
+ router.push("/onboarding");
+ },
+ onError: (error) => {
+ if (isWorkspaceSlugConflict(error)) {
+ setSlugServerError(WORKSPACE_SLUG_CONFLICT_ERROR);
+ toast.error("Choose a different workspace URL");
+ return;
+ }
+ toast.error("Failed to create workspace");
+ },
+ },
+ );
+ };
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(v) => {
+ if (!v) onClose();
+ }}
+ >
+ <DialogContent
+ showCloseButton={false}
+ className="inset-0 flex h-full w-full max-w-none sm:max-w-none translate-0 flex-col items-center justify-center rounded-none bg-background ring-0 shadow-none"
+ >
+ <Button
+ variant="ghost"
+ size="sm"
+ className="absolute top-6 left-6 text-muted-foreground"
+ onClick={onClose}
+ >
+ <ArrowLeft className="h-4 w-4" />
+ Back
+ </Button>
+
+ <div className="flex w-full max-w-md flex-col items-center gap-6">
+ <div className="text-center">
+ <DialogTitle className="text-2xl font-semibold">
+ Create a new workspace
+ </DialogTitle>
+ <DialogDescription className="mt-2">
+ Workspaces are shared environments where teams can work on
+ projects and issues.
+ </DialogDescription>
+ </div>
+
+ <Card className="w-full">
+ <CardContent className="space-y-4 pt-6">
+ <div className="space-y-1.5">
+ <Label>Workspace Name</Label>
+ <Input
+ autoFocus
+ type="text"
+ value={name}
+ onChange={(e) => handleNameChange(e.target.value)}
+ placeholder="My Workspace"
+ />
+ </div>
+ <div className="space-y-1.5">
+ <Label>Workspace URL</Label>
+ <div className="flex items-center gap-0 rounded-md border bg-background focus-within:ring-2 focus-within:ring-ring">
+ <span className="pl-3 text-sm text-muted-foreground select-none">
+ multica.ai/
+ </span>
+ <Input
+ type="text"
+ value={slug}
+ onChange={(e) => handleSlugChange(e.target.value)}
+ placeholder="my-workspace"
+ className="border-0 shadow-none focus-visible:ring-0"
+ onKeyDown={(e) => e.key === "Enter" && handleCreate()}
+ />
+ </div>
+ {slugError && (
+ <p className="text-xs text-destructive">{slugError}</p>
+ )}
+ </div>
+ </CardContent>
+ </Card>
+
+ <Button
+ className="w-full"
+ size="lg"
+ onClick={handleCreate}
+ disabled={createWorkspace.isPending || !canSubmit}
+ >
+ {createWorkspace.isPending ? "Creating..." : "Create workspace"}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/modals/registry.tsx b/packages/views/modals/registry.tsx
index 62b5f2a8a0..d97709bbcc 100644
--- a/packages/views/modals/registry.tsx
+++ b/packages/views/modals/registry.tsx
@@ -1,6 +1,7 @@
"use client";
import { useModalStore } from "@multica/core/modals";
+import { CreateWorkspaceModal } from "./create-workspace";
import { CreateIssueModal } from "./create-issue";
export function ModalRegistry() {
@@ -9,6 +10,8 @@ export function ModalRegistry() {
const close = useModalStore((s) => s.close);
switch (modal) {
+ case "create-workspace":
+ return <CreateWorkspaceModal onClose={close} />;
case "create-issue":
return <CreateIssueModal onClose={close} data={data} />;
default:
diff --git a/packages/views/onboarding/onboarding-wizard.test.tsx b/packages/views/onboarding/onboarding-wizard.test.tsx
new file mode 100644
index 0000000000..0d461cd30b
--- /dev/null
+++ b/packages/views/onboarding/onboarding-wizard.test.tsx
@@ -0,0 +1,87 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+
+const mockWorkspaceState = vi.hoisted(() => ({
+ workspace: null as { id: string } | null,
+}));
+
+vi.mock("@multica/core/workspace", () => ({
+ useWorkspaceStore: Object.assign(
+ (selector?: (state: typeof mockWorkspaceState) => unknown) =>
+ selector ? selector(mockWorkspaceState) : mockWorkspaceState,
+ {
+ getState: () => mockWorkspaceState,
+ },
+ ),
+}));
+
+vi.mock("./step-workspace", () => ({
+ StepWorkspace: ({ onNext }: { onNext: () => void }) => (
+ <button type="button" onClick={onNext}>
+ Finish workspace
+ </button>
+ ),
+}));
+
+vi.mock("./step-runtime", () => ({
+ StepRuntime: ({ wsId }: { wsId: string }) => (
+ <div>Runtime step for {wsId}</div>
+ ),
+}));
+
+vi.mock("./step-agent", () => ({
+ StepAgent: () => <div>Agent step</div>,
+}));
+
+vi.mock("./step-complete", () => ({
+ StepComplete: () => <div>Complete step</div>,
+}));
+
+import { OnboardingWizard } from "./onboarding-wizard";
+
+describe("OnboardingWizard", () => {
+ beforeEach(() => {
+ mockWorkspaceState.workspace = null;
+ });
+
+ it("starts at workspace creation when no workspace exists", () => {
+ render(<OnboardingWizard onComplete={vi.fn()} />);
+
+ expect(
+ screen.getByRole("button", { name: "Finish workspace" }),
+ ).toBeInTheDocument();
+ });
+
+ it("continues setup when a workspace already exists", () => {
+ mockWorkspaceState.workspace = { id: "ws-123" };
+
+ render(<OnboardingWizard onComplete={vi.fn()} />);
+
+ expect(screen.getByText("Runtime step for ws-123")).toBeInTheDocument();
+ });
+
+ it("continues setup when the workspace becomes available after mount", async () => {
+ const { rerender } = render(<OnboardingWizard onComplete={vi.fn()} />);
+
+ expect(
+ screen.getByRole("button", { name: "Finish workspace" }),
+ ).toBeInTheDocument();
+
+ mockWorkspaceState.workspace = { id: "ws-456" };
+ rerender(<OnboardingWizard onComplete={vi.fn()} />);
+
+ expect(
+ await screen.findByText("Runtime step for ws-456"),
+ ).toBeInTheDocument();
+ });
+
+ it("does not skip runtime when workspace creation also switches workspace", () => {
+ render(<OnboardingWizard onComplete={vi.fn()} />);
+
+ mockWorkspaceState.workspace = { id: "ws-789" };
+ fireEvent.click(screen.getByRole("button", { name: "Finish workspace" }));
+
+ expect(screen.getByText("Runtime step for ws-789")).toBeInTheDocument();
+ expect(screen.queryByText("Agent step")).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/onboarding/onboarding-wizard.tsx b/packages/views/onboarding/onboarding-wizard.tsx
index 2cec495b8f..256e75d9ac 100644
--- a/packages/views/onboarding/onboarding-wizard.tsx
+++ b/packages/views/onboarding/onboarding-wizard.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useCallback } from "react";
+import { useCallback, useEffect, useState } from "react";
import { useWorkspaceStore } from "@multica/core/workspace";
import type { Agent } from "@multica/core/types";
import { StepWorkspace } from "./step-workspace";
@@ -20,11 +20,21 @@ export interface OnboardingWizardProps {
}
export function OnboardingWizard({ onComplete }: OnboardingWizardProps) {
- const [step, setStep] = useState(0);
+ const [step, setStep] = useState(() =>
+ useWorkspaceStore.getState().workspace ? 1 : 0,
+ );
const [createdAgent, setCreatedAgent] = useState<Agent | null>(null);
const wsId = useWorkspaceStore((s) => s.workspace?.id) ?? null;
+ useEffect(() => {
+ if (step === 0 && wsId) {
+ setStep(1);
+ }
+ }, [step, wsId]);
+
+ const startWorkspaceSetup = useCallback(() => setStep(1), []);
+
const next = useCallback(
() => setStep((s) => Math.min(s + 1, STEPS.length - 1)),
[],
@@ -81,7 +91,7 @@ export function OnboardingWizard({ onComplete }: OnboardingWizardProps) {
{/* Step content */}
<div className="flex flex-1 items-center justify-center px-6 py-12">
- {step === 0 && <StepWorkspace onNext={next} />}
+ {step === 0 && <StepWorkspace onNext={startWorkspaceSetup} />}
{step === 1 && wsId && (
<StepRuntime wsId={wsId} onNext={next} />
)}
diff --git a/packages/views/onboarding/step-complete.tsx b/packages/views/onboarding/step-complete.tsx
index 927d81c029..fc8936c005 100644
--- a/packages/views/onboarding/step-complete.tsx
+++ b/packages/views/onboarding/step-complete.tsx
@@ -141,7 +141,7 @@ export function StepComplete({
<div className="text-center">
<h1 className="text-3xl font-semibold tracking-tight">
- You're all set!
+ You&apos;re all set!
</h1>
<p className="mt-2 text-muted-foreground">
{agent
diff --git a/packages/views/onboarding/step-workspace.test.tsx b/packages/views/onboarding/step-workspace.test.tsx
new file mode 100644
index 0000000000..043c773ee8
--- /dev/null
+++ b/packages/views/onboarding/step-workspace.test.tsx
@@ -0,0 +1,58 @@
+import { describe, expect, it, beforeEach, vi } from "vitest";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+
+const mockCreateWorkspaceMutate = vi.hoisted(() => vi.fn());
+const mockToastError = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/workspace/mutations", () => ({
+ useCreateWorkspace: () => ({
+ mutate: mockCreateWorkspaceMutate,
+ isPending: false,
+ }),
+}));
+
+vi.mock("sonner", () => ({
+ toast: {
+ error: mockToastError,
+ },
+}));
+
+import { StepWorkspace } from "./step-workspace";
+
+describe("StepWorkspace", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("asks the user to change the slug on conflict", async () => {
+ const user = userEvent.setup();
+ mockCreateWorkspaceMutate.mockImplementation(
+ (
+ _data: unknown,
+ options: { onError: (error: unknown) => void },
+ ) => {
+ options.onError({ status: 409 });
+ },
+ );
+
+ render(<StepWorkspace onNext={vi.fn()} />);
+
+ await user.type(screen.getByPlaceholderText("My Team"), "My Team");
+ await user.click(screen.getByRole("button", { name: "Create Workspace" }));
+
+ await waitFor(() => {
+ expect(
+ screen.getByText("That workspace URL is already taken."),
+ ).toBeInTheDocument();
+ });
+
+ expect(mockToastError).toHaveBeenCalledWith(
+ "Choose a different workspace URL",
+ );
+ expect(mockCreateWorkspaceMutate).toHaveBeenCalledWith(
+ { name: "My Team", slug: "my-team" },
+ expect.any(Object),
+ );
+ });
+});
diff --git a/packages/views/onboarding/step-workspace.tsx b/packages/views/onboarding/step-workspace.tsx
index 1044832232..470887b523 100644
--- a/packages/views/onboarding/step-workspace.tsx
+++ b/packages/views/onboarding/step-workspace.tsx
@@ -1,35 +1,33 @@
"use client";
-import { useState, useRef } from "react";
+import { useRef, useState } from "react";
import { toast } from "sonner";
import { Input } from "@multica/ui/components/ui/input";
import { Label } from "@multica/ui/components/ui/label";
import { Button } from "@multica/ui/components/ui/button";
import { Card, CardContent } from "@multica/ui/components/ui/card";
import { useCreateWorkspace } from "@multica/core/workspace/mutations";
-
-const SLUG_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
-
-function nameToSlug(name: string): string {
- return (
- name
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-|-$/g, "") || "workspace"
- );
-}
+import {
+ WORKSPACE_SLUG_CONFLICT_ERROR,
+ WORKSPACE_SLUG_FORMAT_ERROR,
+ WORKSPACE_SLUG_REGEX,
+ isWorkspaceSlugConflict,
+ nameToWorkspaceSlug,
+} from "../workspace/slug";
export function StepWorkspace({ onNext }: { onNext: () => void }) {
const createWorkspace = useCreateWorkspace();
const [name, setName] = useState("");
const [slug, setSlug] = useState("");
+ const [slugServerError, setSlugServerError] = useState<string | null>(null);
// Track whether the user has manually edited the slug field.
const slugTouched = useRef(false);
- const slugError =
- slug.length > 0 && !SLUG_REGEX.test(slug)
- ? "Only lowercase letters, numbers, and hyphens"
+ const slugValidationError =
+ slug.length > 0 && !WORKSPACE_SLUG_REGEX.test(slug)
+ ? WORKSPACE_SLUG_FORMAT_ERROR
: null;
+ const slugError = slugValidationError ?? slugServerError;
const canSubmit =
name.trim().length > 0 && slug.trim().length > 0 && !slugError;
@@ -37,13 +35,15 @@ export function StepWorkspace({ onNext }: { onNext: () => void }) {
const handleNameChange = (value: string) => {
setName(value);
if (!slugTouched.current) {
- setSlug(nameToSlug(value));
+ setSlug(nameToWorkspaceSlug(value));
+ setSlugServerError(null);
}
};
const handleSlugChange = (value: string) => {
slugTouched.current = true;
setSlug(value);
+ setSlugServerError(null);
};
const handleCreate = () => {
@@ -52,7 +52,14 @@ export function StepWorkspace({ onNext }: { onNext: () => void }) {
{ name: name.trim(), slug: slug.trim() },
{
onSuccess: () => onNext(),
- onError: () => toast.error("Failed to create workspace"),
+ onError: (error) => {
+ if (isWorkspaceSlugConflict(error)) {
+ setSlugServerError(WORKSPACE_SLUG_CONFLICT_ERROR);
+ toast.error("Choose a different workspace URL");
+ return;
+ }
+ toast.error("Failed to create workspace");
+ },
},
);
};
diff --git a/packages/views/test/setup.ts b/packages/views/test/setup.ts
index efb4154e31..7501438744 100644
--- a/packages/views/test/setup.ts
+++ b/packages/views/test/setup.ts
@@ -1,5 +1,36 @@
import "@testing-library/jest-dom/vitest";
+function createMemoryStorage(): Storage {
+ const values = new Map<string, string>();
+
+ return {
+ get length() {
+ return values.size;
+ },
+ clear: () => values.clear(),
+ getItem: (key: string) => values.get(key) ?? null,
+ key: (index: number) => Array.from(values.keys())[index] ?? null,
+ removeItem: (key: string) => {
+ values.delete(key);
+ },
+ setItem: (key: string, value: string) => {
+ values.set(key, value);
+ },
+ };
+}
+
+if (typeof globalThis.localStorage?.clear !== "function") {
+ const storage = createMemoryStorage();
+ Object.defineProperty(globalThis, "localStorage", {
+ configurable: true,
+ value: storage,
+ });
+ Object.defineProperty(window, "localStorage", {
+ configurable: true,
+ value: storage,
+ });
+}
+
// jsdom doesn't provide ResizeObserver; stub it so components that rely on it
// (e.g. input-otp) can render in tests.
if (typeof globalThis.ResizeObserver === "undefined") {
diff --git a/packages/views/workspace/slug.ts b/packages/views/workspace/slug.ts
new file mode 100644
index 0000000000..040efe27a5
--- /dev/null
+++ b/packages/views/workspace/slug.ts
@@ -0,0 +1,25 @@
+export const WORKSPACE_SLUG_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+
+export const WORKSPACE_SLUG_FORMAT_ERROR =
+ "Only lowercase letters, numbers, and hyphens";
+
+export const WORKSPACE_SLUG_CONFLICT_ERROR =
+ "That workspace URL is already taken.";
+
+export function nameToWorkspaceSlug(name: string): string {
+ return (
+ name
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-|-$/g, "") || "workspace"
+ );
+}
+
+export function isWorkspaceSlugConflict(error: unknown): boolean {
+ return (
+ typeof error === "object" &&
+ error !== null &&
+ "status" in error &&
+ (error as { status?: unknown }).status === 409
+ );
+}
diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.go
index ae929c9793..449712a7ff 100644
--- a/server/internal/handler/handler_test.go
+++ b/server/internal/handler/handler_test.go
@@ -412,6 +412,72 @@ func TestWorkspaceCRUD(t *testing.T) {
}
}
+func TestCreateWorkspaceUsesRequestedSlug(t *testing.T) {
+ const slug = "handler-create-workspace-requested"
+ ctx := context.Background()
+
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)
+ })
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/workspaces", map[string]string{
+ "name": "Handler Create Workspace Requested",
+ "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 created WorkspaceResponse
+ if err := json.NewDecoder(w.Body).Decode(&created); err != nil {
+ t.Fatalf("CreateWorkspace: decode response: %v", err)
+ }
+ if created.Slug != slug {
+ t.Fatalf("CreateWorkspace: expected slug %q, got %q", slug, created.Slug)
+ }
+}
+
+func TestCreateWorkspaceSlugConflictReturnsConflict(t *testing.T) {
+ ctx := context.Background()
+ retriedSlug := handlerTestWorkspaceSlug + "-2"
+
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, retriedSlug)
+ })
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/workspaces", map[string]string{
+ "name": "Duplicate Handler Workspace",
+ "slug": handlerTestWorkspaceSlug,
+ })
+ testHandler.CreateWorkspace(w, req)
+ if w.Code != http.StatusConflict {
+ t.Fatalf("CreateWorkspace: expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var count int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM workspace WHERE slug = $1`, retriedSlug).Scan(&count); err != nil {
+ t.Fatalf("CreateWorkspace: check retried slug: %v", err)
+ }
+ if count != 0 {
+ t.Fatalf("CreateWorkspace: expected no fallback slug %q, got %d rows", retriedSlug, count)
+ }
+}
+
+func TestCreateWorkspaceInvalidSlugReturnsBadRequest(t *testing.T) {
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/workspaces", map[string]string{
+ "name": "Invalid Slug Workspace",
+ "slug": "invalid slug",
+ })
+ testHandler.CreateWorkspace(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("CreateWorkspace: expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
func TestSendCode(t *testing.T) {
w := httptest.NewRecorder()
body := map[string]string{"email": "[email protected]"}
@@ -695,11 +761,11 @@ func TestResolveActor(t *testing.T) {
})
tests := []struct {
- name string
- agentIDHeader string
- taskIDHeader string
- wantActorType string
- wantIsAgent bool
+ name string
+ agentIDHeader string
+ taskIDHeader string
+ wantActorType string
+ wantIsAgent bool
}{
{
name: "no headers returns member",
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index fdd1156583..068076bb0e 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -2,7 +2,6 @@ package handler
import (
"encoding/json"
- "fmt"
"log/slog"
"net/http"
"regexp"
@@ -16,6 +15,7 @@ import (
)
var nonAlpha = regexp.MustCompile(`[^a-zA-Z]`)
+var workspaceSlugPattern = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
// generateIssuePrefix produces a 2-5 char uppercase prefix from a workspace name.
// Examples: "Jiayuan's Workspace" → "JIA", "My Team" → "MYT", "AB" → "AB".
@@ -148,6 +148,10 @@ func (h *Handler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "name and slug are required")
return
}
+ if !workspaceSlugPattern.MatchString(req.Slug) {
+ writeError(w, http.StatusBadRequest, "slug must contain only lowercase letters, numbers, and hyphens")
+ return
+ }
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
@@ -162,31 +166,19 @@ func (h *Handler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {
}
qtx := h.Queries.WithTx(tx)
-
- // Try the requested slug first, then append -2, -3, … on conflict.
- const maxSlugAttempts = 10
- var ws db.Workspace
- slug := req.Slug
- for attempt := 1; attempt <= maxSlugAttempts; attempt++ {
- ws, err = qtx.CreateWorkspace(r.Context(), db.CreateWorkspaceParams{
- Name: req.Name,
- Slug: slug,
- Description: ptrToText(req.Description),
- Context: ptrToText(req.Context),
- IssuePrefix: issuePrefix,
- })
- if err == nil {
- break
- }
- if !isUniqueViolation(err) {
- writeError(w, http.StatusInternalServerError, "failed to create workspace: "+err.Error())
+ ws, err := qtx.CreateWorkspace(r.Context(), db.CreateWorkspaceParams{
+ Name: req.Name,
+ Slug: req.Slug,
+ Description: ptrToText(req.Description),
+ Context: ptrToText(req.Context),
+ IssuePrefix: issuePrefix,
+ })
+ if err != nil {
+ if isUniqueViolation(err) {
+ writeError(w, http.StatusConflict, "workspace slug already exists")
return
}
- // Slug taken — try next suffix.
- slug = fmt.Sprintf("%s-%d", req.Slug, attempt+1)
- }
- if err != nil {
- writeError(w, http.StatusConflict, "workspace slug already exists")
+ writeError(w, http.StatusInternalServerError, "failed to create workspace: "+err.Error())
return
}