refactor: make browser workspace writes bootstrap-only

This commit is contained in:
2026-08-11 15:36:09 +02:00
parent d9fd902d08
commit 1790d2449f
14 changed files with 844 additions and 1509 deletions
+6 -5
View File
@@ -4,7 +4,7 @@ import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { server } from "../test/msw";
import { canonicalWorkspaceFixture, workspaceRevisionFixture } from "../test/workspace-fixtures";
import { canonicalWorkspaceFixture, workspaceRevisionFixture, workspaceSummaryFixture } from "../test/workspace-fixtures";
import { NewSessionDialog } from "./NewSessionDialog";
function renderDialog() {
@@ -36,8 +36,10 @@ test("submitting includes browser-local migrated preferences and calls onCreated
workspace: "default", provider: "zai", model: "glm-5.2", thinking: "low",
})),
http.get("/api/workspaces", () => HttpResponse.json([{
id: "default", name: "default", file: "default.yaml", displayName: "Default", language: "en",
revision: workspaceRevisionFixture("default"),
...workspaceSummaryFixture("default", {
displayName: "Default",
revision: workspaceRevisionFixture("default"),
}),
}])),
http.get("/api/workspaces/default", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("default", ["zai/glm-5.2"], "zai/glm-5.2"),
@@ -76,8 +78,7 @@ test("first-run direct dialog creation waits for registry policy without a mount
http.get("/api/workspaces", () => {
summaryRequestStarted = true;
return HttpResponse.json([{
id: "psd-clinical", name: "psd-clinical", file: "psd-clinical.yaml", displayName: "PSD Clinical", language: "en",
revision,
...workspaceSummaryFixture("psd-clinical", { displayName: "PSD Clinical", revision: revision as any }),
}]);
}),
http.get("/api/workspaces/psd-clinical", async () => {
+25 -16
View File
@@ -4,7 +4,7 @@ import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { server } from "../test/msw";
import { canonicalWorkspaceFixture } from "../test/workspace-fixtures";
import { canonicalWorkspaceFixture, workspaceSummaryFixture } from "../test/workspace-fixtures";
import { useSessionStore } from "../store/sessionStore";
import { ComposerFooter, ContextGauge, SteerInput } from "./SteerInput";
@@ -24,8 +24,10 @@ test("new sessions send the browser-selected workspace, model, provider, and thi
}));
server.use(
http.get("/api/workspaces", () => HttpResponse.json([{
id: "psd-clinical", name: "psd-clinical", file: "psd-clinical.yaml", displayName: "PSD Clinical", language: "en",
revision: { id: "psd-clinical", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/snapshot" },
...workspaceSummaryFixture("psd-clinical", {
displayName: "PSD Clinical",
revision: { id: "psd-clinical", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/snapshot" },
}),
}])),
http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("psd-clinical"),
@@ -136,8 +138,10 @@ test("footer shows cumulative k-token counters after workspace and context gauge
workspace: "psd", provider: "zai", model: "glm-5.2", thinking: "medium",
})),
http.get("/api/workspaces", () => HttpResponse.json([{
id: "psd", name: "psd", file: "psd.yaml", displayName: "PSD", language: "en",
revision: { id: "psd", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/snapshot" },
...workspaceSummaryFixture("psd", {
displayName: "PSD",
revision: { id: "psd", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/snapshot" },
}),
}])),
http.get("/api/workspaces/psd", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("psd"),
@@ -175,8 +179,10 @@ test("footer limits model choices to the selected workspace policy", async () =>
workspace: "psd-clinical", provider: "zai", model: "glm-5.2", thinking: "medium",
})),
http.get("/api/workspaces", () => HttpResponse.json([{
id: "psd-clinical", name: "psd-clinical", file: "psd-clinical.yaml", displayName: "PSD Clinical", language: "en",
revision: { id: "psd-clinical", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/snapshot" },
...workspaceSummaryFixture("psd-clinical", {
displayName: "PSD Clinical",
revision: { id: "psd-clinical", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/snapshot" },
}),
}])),
http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("psd-clinical"),
@@ -208,8 +214,8 @@ test("switching workspaces replaces an out-of-policy model before session creati
workspace: "research", provider: "deepseek", model: "deepseek-v4-pro", thinking: "medium",
})),
http.get("/api/workspaces", () => HttpResponse.json([
{ id: "research", name: "research", file: "research.yaml", displayName: "Research", language: "en", revision: revision("research") },
{ id: "psd-clinical", name: "psd-clinical", file: "psd-clinical.yaml", displayName: "PSD Clinical", language: "en", revision: revision("psd-clinical") },
workspaceSummaryFixture("research", { displayName: "Research", revision: revision("research") }),
workspaceSummaryFixture("psd-clinical", { displayName: "PSD Clinical", revision: revision("psd-clinical") }),
])),
http.get("/api/workspaces/research", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("research", ["deepseek/deepseek-v4-pro"]),
@@ -259,8 +265,8 @@ test("immediate submit waits for a switched workspace policy before creating a s
server.use(
http.get("/api/settings", () => HttpResponse.json({ workspace: "research" })),
http.get("/api/workspaces", () => HttpResponse.json([
{ id: "research", name: "research", file: "research.yaml", displayName: "Research", language: "en", revision: revision("research") },
{ id: "psd-clinical", name: "psd-clinical", file: "psd-clinical.yaml", displayName: "PSD Clinical", language: "en", revision: revision("psd-clinical") },
workspaceSummaryFixture("research", { displayName: "Research", revision: revision("research") }),
workspaceSummaryFixture("psd-clinical", { displayName: "PSD Clinical", revision: revision("psd-clinical") }),
])),
http.get("/api/workspaces/research", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("research", ["deepseek/deepseek-v4-pro"]), revision: revision("research"),
@@ -315,7 +321,7 @@ test("initial restored workspace waits for its delayed policy before creating a
server.use(
http.get("/api/settings", () => HttpResponse.json({ workspace: "psd-clinical" })),
http.get("/api/workspaces", () => HttpResponse.json([
{ id: "psd-clinical", name: "psd-clinical", file: "psd-clinical.yaml", displayName: "PSD Clinical", language: "en", revision: revision("psd-clinical") },
workspaceSummaryFixture("psd-clinical", { displayName: "PSD Clinical", revision: revision("psd-clinical") }),
])),
http.get("/api/workspaces/psd-clinical", async () => {
policyRequestStarted = true;
@@ -359,7 +365,10 @@ test("initial submit rejects a workspace summary that omits the canonical revisi
server.use(
http.get("/api/settings", () => HttpResponse.json({ workspace: "broken-workspace" })),
http.get("/api/workspaces", () => HttpResponse.json([{
id: "broken-workspace", name: "broken-workspace", file: "broken-workspace.yaml", displayName: "Broken workspace", language: "en",
...workspaceSummaryFixture("broken-workspace", {
displayName: "Broken workspace",
configurationState: "configuration_required",
}),
}])),
http.get("/api/models", () => HttpResponse.json({ models: [
{ provider: "zai", id: "glm-5.2", name: "GLM-5.2", reasoning: true },
@@ -432,9 +441,9 @@ test("submit follows a rapid workspace switch instead of waiting for an abandone
server.use(
http.get("/api/settings", () => HttpResponse.json({ workspace: "research" })),
http.get("/api/workspaces", () => HttpResponse.json([
{ id: "research", name: "research", file: "research.yaml", displayName: "Research", language: "en", revision: revision("research") },
{ id: "workspace-b", name: "workspace-b", file: "workspace-b.yaml", displayName: "Workspace B", language: "en", revision: revision("workspace-b") },
{ id: "workspace-c", name: "workspace-c", file: "workspace-c.yaml", displayName: "Workspace C", language: "en", revision: revision("workspace-c") },
workspaceSummaryFixture("research", { displayName: "Research", revision: revision("research") }),
workspaceSummaryFixture("workspace-b", { displayName: "Workspace B", revision: revision("workspace-b") }),
workspaceSummaryFixture("workspace-c", { displayName: "Workspace C", revision: revision("workspace-c") }),
])),
http.get("/api/workspaces/research", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("research", ["deepseek/deepseek-v4-pro"]), revision: revision("research"),
+56 -103
View File
@@ -2,11 +2,12 @@ import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, test, vi } from "vitest";
import type { CanonicalWorkspace } from "../api/workspaces";
import type { WorkspaceDraft } from "../workspaces/drafts";
import type { WorkspaceBootstrapDraft } from "../workspaces/drafts";
import { workspaceRevisionFixture, workspaceSummaryFixture } from "../test/workspace-fixtures";
import { WorkspaceEditor } from "./WorkspaceEditor";
const workspace: CanonicalWorkspace = {
workspace: { schema_version: 3, id: "psd-clinical", name: "PSD Clinical", language: "en" },
workspace: { schema_version: 3, id: "bootstrap-slot", name: "Bootstrap slot", description: "Needs configuration", language: "en" },
dwh: {
engine: "postgres", database: "clinical", schema: "datawarehouse", port: 5432,
supported_transports: ["postgres_direct"],
@@ -22,10 +23,11 @@ const workspace: CanonicalWorkspace = {
const evidenceWorkspace: CanonicalWorkspace = {
...workspace,
workspace: { ...workspace.workspace, id: "psd-clinical", name: "PSD Clinical", description: "Clinical workspace" },
evidence: {
source: {
type: "filesystem",
uri: "workspace-content/psd-clinical/evidence",
uri: "psd-clinical/evidence",
patterns: ["documents/**/*.pdf"],
max_bytes: 12_000_000,
},
@@ -33,129 +35,80 @@ const evidenceWorkspace: CanonicalWorkspace = {
},
};
const draft: WorkspaceDraft = {
workspaceId: "psd-clinical",
const draft: WorkspaceBootstrapDraft = {
workspaceId: "bootstrap-slot",
baseCommit: "a".repeat(40),
baseBlob: "b".repeat(40),
workspace,
updatedAt: "2026-08-04T10:00:00.000Z",
};
test("uses closed choices for transport and rejects an invalid free-form port before save", async () => {
const user = userEvent.setup();
render(<WorkspaceEditor draft={draft} onSaveDraft={vi.fn()} onPublish={vi.fn()} />);
expect(screen.getByRole("listbox", { name: "DWH transport" })).toHaveTextContent("postgres_direct");
await user.clear(screen.getByLabelText("DWH port"));
await user.type(screen.getByLabelText("DWH port"), "70000");
await user.click(screen.getByRole("button", { name: "Save draft" }));
expect(screen.getByRole("alert")).toHaveTextContent("Port must be between 1 and 65535");
expect(screen.getByLabelText("DWH port")).toHaveAttribute("aria-invalid", "true");
});
test("saves only the editable collection while preserving the fixed schema-v3 semantic architecture", async () => {
test("bootstrap mode locks catalog metadata and saves only the local bootstrap draft", async () => {
const user = userEvent.setup();
const onSaveDraft = vi.fn();
render(<WorkspaceEditor draft={draft} onSaveDraft={onSaveDraft} onPublish={vi.fn()} />);
render(
<WorkspaceEditor
mode={{
kind: "bootstrap",
catalog: workspaceSummaryFixture("bootstrap-slot", {
displayName: "Bootstrap slot",
description: "Needs configuration",
configurationState: "configuration_required",
}),
draft,
}}
onSaveDraft={onSaveDraft}
/>,
);
expect(screen.getByLabelText("Workspace ID")).toBeDisabled();
expect(screen.getByLabelText("Workspace name")).toHaveValue("Bootstrap slot");
expect(screen.getByLabelText("Workspace name")).toBeDisabled();
expect(screen.getByLabelText("Description")).toHaveValue("Needs configuration");
expect(screen.getByLabelText("Description")).toBeDisabled();
await user.clear(screen.getByLabelText("Vector collection"));
await user.type(screen.getByLabelText("Vector collection"), "research_docs");
await user.click(screen.getByRole("button", { name: "Save draft" }));
expect(onSaveDraft).toHaveBeenCalledWith(expect.objectContaining({
baseCommit: "a".repeat(40),
workspaceId: "bootstrap-slot",
workspace: expect.objectContaining({
semantic_index: expect.objectContaining({
vector_store: {
engine: "qdrant",
collection: "research_docs",
dimensions: 1024,
distance: "cosine",
},
embedding: {
provider: "ollama_internal",
model: "qwen3-embedding:0.6b",
dimensions: 1024,
},
vector_store: expect.objectContaining({ collection: "research_docs" }),
}),
}),
}));
expect(onSaveDraft.mock.calls[0]?.[0]).not.toHaveProperty("baseBlob");
});
test("shows fixed architecture values and no editable endpoint or credential controls", () => {
render(<WorkspaceEditor draft={draft} onSaveDraft={vi.fn()} onPublish={vi.fn()} />);
expect(screen.getByRole("combobox", { name: "Workspace language" })).toHaveValue("en");
expect(screen.getByRole("listbox", { name: "DWH transport" })).toHaveProperty("multiple", true);
expect(screen.getByLabelText("Vector store engine")).toHaveValue("qdrant");
expect(screen.getByLabelText("Vector distance")).toHaveValue("cosine");
expect(screen.getByLabelText("Semantic index dimensions")).toHaveValue(1024);
expect(screen.getByLabelText("Embedding provider")).toHaveValue("ollama_internal");
expect(screen.getByLabelText("Embedding model")).toHaveValue("qwen3-embedding:0.6b");
expect(screen.queryByLabelText("Vector database")).not.toBeInTheDocument();
expect(screen.queryByLabelText("Vector schema")).not.toBeInTheDocument();
expect(screen.queryByLabelText("Vector port")).not.toBeInTheDocument();
expect(screen.queryByLabelText("Vector transport")).not.toBeInTheDocument();
expect(screen.queryByLabelText(/api[- ]key|endpoint|base url/i)).not.toBeInTheDocument();
});
test("rejects a non-positive DWH timeout without saving a draft", async () => {
const user = userEvent.setup();
const onSaveDraft = vi.fn();
render(<WorkspaceEditor draft={draft} onSaveDraft={onSaveDraft} onPublish={vi.fn()} />);
await user.clear(screen.getByLabelText("DWH timeout (ms)"));
await user.type(screen.getByLabelText("DWH timeout (ms)"), "0");
await user.click(screen.getByRole("button", { name: "Save draft" }));
expect(screen.getByRole("alert")).toHaveTextContent("DWH timeout must be a positive whole number");
expect(screen.getByLabelText("DWH timeout (ms)")).toHaveAttribute("aria-invalid", "true");
expect(onSaveDraft).not.toHaveBeenCalled();
});
test("shows a safe read-only Evidence summary without authoring or secret binding controls", () => {
render(<WorkspaceEditor draft={{ ...draft, workspace: evidenceWorkspace }} onSaveDraft={vi.fn()} onPublish={vi.fn()} />);
test("read-only mode shows evidence and curator git guidance without mutation actions", () => {
render(
<WorkspaceEditor
mode={{
kind: "read_only",
catalog: workspaceSummaryFixture("psd-clinical", {
displayName: "PSD Clinical",
description: "Clinical workspace",
revision: workspaceRevisionFixture("psd-clinical"),
}),
record: {
workspace: evidenceWorkspace,
revision: workspaceRevisionFixture("psd-clinical"),
},
}}
/>,
);
expect(screen.getByLabelText("DWH database")).toHaveValue("clinical");
expect(screen.getByLabelText("DWH database")).toHaveAttribute("readonly");
const summary = screen.getByRole("region", { name: "Evidence" });
expect(summary).toHaveTextContent("filesystem");
expect(summary).toHaveTextContent("workspace-content/psd-clinical/evidence");
expect(summary).toHaveTextContent("psd-clinical/evidence");
expect(summary).toHaveTextContent("8,000");
expect(summary).toHaveTextContent("5");
expect(summary).toHaveTextContent("Evidence is managed by the registry descriptor in P1.");
expect(summary).not.toHaveTextContent(/signed_urls_file|static_files|secret|binding/i);
expect(screen.queryByLabelText(/evidence.*(source|uri|pattern|credential)/i)).not.toBeInTheDocument();
});
test("publishes an edited DWH and LLM field without dropping or mutating Evidence", async () => {
const user = userEvent.setup();
const onPublish = vi.fn().mockResolvedValue(undefined);
render(<WorkspaceEditor draft={{ ...draft, workspace: evidenceWorkspace }} onSaveDraft={vi.fn()} onPublish={onPublish} />);
await user.clear(screen.getByLabelText("DWH database"));
await user.type(screen.getByLabelText("DWH database"), "research");
await user.clear(screen.getByLabelText("Allowed models"));
await user.type(screen.getByLabelText("Allowed models"), "openai/gpt-5");
await user.click(screen.getByRole("button", { name: "Publish draft" }));
expect(onPublish).toHaveBeenCalledWith(expect.objectContaining({
action: "update",
workspace: expect.objectContaining({
dwh: expect.objectContaining({ database: "research" }),
llm_policy: { allowed: ["openai/gpt-5"] },
evidence: evidenceWorkspace.evidence,
}),
}));
expect(evidenceWorkspace.evidence?.source).toEqual({
type: "filesystem",
uri: "workspace-content/psd-clinical/evidence",
patterns: ["documents/**/*.pdf"],
max_bytes: 12_000_000,
});
});
test("does not show an Evidence summary for a workspace without Evidence", () => {
render(<WorkspaceEditor draft={draft} onSaveDraft={vi.fn()} onPublish={vi.fn()} />);
expect(screen.queryByRole("region", { name: "Evidence" })).not.toBeInTheDocument();
expect(screen.getByText("Curator workflow")).toBeVisible();
expect(screen.getByText(/edit psd-clinical\/workspace\.yaml, commit\/push, then Pull/i)).toBeVisible();
expect(screen.queryByRole("button", { name: "Save draft" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /create workspace|publish/i })).not.toBeInTheDocument();
});
+106 -85
View File
@@ -1,34 +1,30 @@
import { useEffect, useId, useMemo, useState } from "react";
import type { CanonicalWorkspace, PublishWorkspaceRequest } from "../api/workspaces";
import type { WorkspaceDraft } from "../workspaces/drafts";
import { useEffect, useId, useMemo, useState, type ChangeEvent, type ReactNode } from "react";
import type { CanonicalWorkspace, PublishWorkspaceRequest, WorkspaceRecord, WorkspaceSummary } from "../api/workspaces";
import type { WorkspaceBootstrapDraft } from "../workspaces/drafts";
import { Button } from "../components/ui/button";
type FieldErrors = Record<string, string>;
export interface WorkspaceEditorProps {
draft?: WorkspaceDraft;
onSaveDraft: (draft: WorkspaceDraft) => void;
/** Reserved for Task 10; saving a draft never publishes it. */
onPublish: (request: PublishWorkspaceRequest) => Promise<void>;
idLocked?: boolean;
}
export type WorkspaceEditorMode =
| { kind: "bootstrap"; catalog: WorkspaceSummary; draft: WorkspaceBootstrapDraft }
| { kind: "read_only"; catalog: WorkspaceSummary; record: WorkspaceRecord };
const EMPTY_COMMIT = "0".repeat(40);
type BootstrapEditorProps = {
mode: Extract<WorkspaceEditorMode, { kind: "bootstrap" }>;
onSaveDraft?: (draft: WorkspaceBootstrapDraft) => void;
onRequestCreate?: (request: PublishWorkspaceRequest, draft: WorkspaceBootstrapDraft) => void;
};
function emptyWorkspace(): CanonicalWorkspace {
return {
workspace: { schema_version: 3, id: "new-workspace", name: "New workspace", language: "en" },
dwh: { engine: "postgres", database: "database", schema: "public", supported_transports: ["postgres_direct"] },
semantic_index: {
vector_store: {
engine: "qdrant", collection: "documents",
dimensions: 1024, distance: "cosine",
},
embedding: { provider: "ollama_internal", model: "qwen3-embedding:0.6b", dimensions: 1024 },
},
llm_policy: { allowed: ["zai/glm-5.2"] },
};
}
type ReadOnlyEditorProps = {
mode: Extract<WorkspaceEditorMode, { kind: "read_only" }>;
/** Absent in read-only mode; declared so the union is uniformly addressable. */
onSaveDraft?: never;
onRequestCreate?: never;
};
export type WorkspaceEditorProps = BootstrapEditorProps | ReadOnlyEditorProps;
const fieldClass = "h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm shadow-xs outline-none focus-visible:ring-3 focus-visible:ring-ring/25 aria-invalid:border-destructive";
function positiveInteger(value: number | undefined, label: string, max = Number.MAX_SAFE_INTEGER): string | undefined {
if (value === undefined) return undefined;
@@ -52,14 +48,6 @@ function validate(workspace: CanonicalWorkspace): FieldErrors {
const dwhTimeout = positiveInteger(workspace.dwh.timeout_ms, "DWH timeout");
if (dwhTimeout) errors["dwh.timeout"] = dwhTimeout;
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(workspace.semantic_index.vector_store.collection)) errors["vector.collection"] = "Use a collection identifier";
if (workspace.semantic_index.vector_store.engine !== "qdrant") errors["semantic.engine"] = "Vector store engine is fixed to qdrant";
if (workspace.semantic_index.vector_store.dimensions !== 1024) errors["semantic.dimensions"] = "Semantic index dimensions are fixed to 1024";
if (workspace.semantic_index.vector_store.distance !== "cosine") errors["semantic.distance"] = "Vector distance is fixed to cosine";
if (workspace.semantic_index.embedding.provider !== "ollama_internal") errors["embedding.provider"] = "Embedding provider is fixed to ollama_internal";
if (workspace.semantic_index.embedding.model !== "qwen3-embedding:0.6b") errors["embedding.model"] = "Embedding model is fixed to qwen3-embedding:0.6b";
if (workspace.semantic_index.embedding.dimensions !== 1024 || workspace.semantic_index.embedding.dimensions !== workspace.semantic_index.vector_store.dimensions) {
errors["semantic.dimensions"] = "Vector and embedding dimensions are fixed to 1024";
}
if (!workspace.llm_policy.allowed.length || workspace.llm_policy.allowed.some((model) => !/^[^/\s]+\/[^/\s]+$/.test(model))) {
errors["llm.allowed"] = "Use provider/model entries separated by commas";
}
@@ -69,7 +57,7 @@ function validate(workspace: CanonicalWorkspace): FieldErrors {
return errors;
}
function selectedValues(event: React.ChangeEvent<HTMLSelectElement>): string[] {
function selectedValues(event: ChangeEvent<HTMLSelectElement>): string[] {
return Array.from(event.currentTarget.selectedOptions, (option) => option.value);
}
@@ -77,13 +65,28 @@ function numberOrUndefined(value: string): number | undefined {
return value.trim() === "" ? undefined : Number(value);
}
function coerceCatalogMetadata(workspace: CanonicalWorkspace, catalog: WorkspaceSummary): CanonicalWorkspace {
return {
...workspace,
workspace: {
...workspace.workspace,
id: catalog.id,
name: catalog.displayName,
description: catalog.description,
},
};
}
function Field({
label, error, children, hint,
label,
error,
hint,
children,
}: {
label: string;
error?: string;
hint?: string;
children: (props: { id: string; describedBy?: string; invalid: boolean }) => React.ReactNode;
children: (props: { id: string; describedBy?: string; invalid: boolean }) => ReactNode;
}) {
const id = useId();
const errorId = `${id}-error`;
@@ -99,7 +102,7 @@ function Field({
);
}
function Section({ title, children }: { title: string; children: React.ReactNode }) {
function Section({ title, children }: { title: string; children: ReactNode }) {
return (
<section className="border-t border-border/70 pt-5 first:border-t-0 first:pt-0" aria-label={title}>
<h3 className="font-heading text-sm font-semibold text-foreground">{title}</h3>
@@ -117,72 +120,81 @@ function EvidenceSummary({ evidence }: { evidence: NonNullable<CanonicalWorkspac
<dl className="grid gap-2 text-sm sm:col-span-2 sm:grid-cols-2">
<div><dt className="font-medium text-foreground">Source type</dt><dd className="text-muted-foreground">{evidence.source.type}</dd></div>
<div><dt className="font-medium text-foreground">Source</dt><dd className="break-all text-muted-foreground">{sourceIdentity}</dd></div>
<div><dt className="font-medium text-foreground">Chunk size</dt><dd className="text-muted-foreground">{evidence.policy.max_chunk_chars.toLocaleString("en-US")} characters</dd></div>
<div><dt className="font-medium text-foreground">Retention</dt><dd className="text-muted-foreground">{evidence.policy.retain_published_generations.toLocaleString("en-US")} published generations</dd></div>
<div><dt className="font-medium text-foreground">Chunk size</dt><dd className="text-muted-foreground">{evidence.policy.max_chunk_chars.toLocaleString("en-US")}</dd></div>
<div><dt className="font-medium text-foreground">Retention</dt><dd className="text-muted-foreground">{evidence.policy.retain_published_generations.toLocaleString("en-US")}</dd></div>
</dl>
<p className="sm:col-span-2 text-sm text-muted-foreground">Evidence is managed by the registry descriptor in P1.</p>
<p className="sm:col-span-2 text-sm text-muted-foreground">Evidence summary is read-only. Curate source files or URIs in Git.</p>
</Section>
);
}
const fieldClass = "h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm shadow-xs outline-none focus-visible:ring-3 focus-visible:ring-ring/25 aria-invalid:border-destructive";
export function WorkspaceEditor({ draft, onSaveDraft, onPublish, idLocked = Boolean(draft?.baseBlob) }: WorkspaceEditorProps) {
const [workspace, setWorkspace] = useState<CanonicalWorkspace>(draft?.workspace ?? emptyWorkspace());
export function WorkspaceEditor(props: WorkspaceEditorProps) {
const bootstrapMode = props.mode.kind === "bootstrap";
const initialWorkspace = props.mode.kind === "bootstrap"
? coerceCatalogMetadata(props.mode.draft.workspace, props.mode.catalog)
: props.mode.record.workspace;
const [workspace, setWorkspace] = useState<CanonicalWorkspace>(initialWorkspace);
const [errors, setErrors] = useState<FieldErrors>({});
const readOnly = !bootstrapMode;
const allowedModels = useMemo(() => workspace.llm_policy.allowed.join(", "), [workspace.llm_policy.allowed]);
useEffect(() => {
setWorkspace(draft?.workspace ?? emptyWorkspace());
setWorkspace(props.mode.kind === "bootstrap"
? coerceCatalogMetadata(props.mode.draft.workspace, props.mode.catalog)
: props.mode.record.workspace);
setErrors({});
}, [draft]);
}, [bootstrapMode, props.mode]);
function update(change: (previous: CanonicalWorkspace) => CanonicalWorkspace) {
if (readOnly) return;
setWorkspace((previous) => {
const next = change(previous);
const next = coerceCatalogMetadata(change(previous), props.mode.catalog);
setErrors(validate(next));
return next;
});
}
function saveDraft() {
const nextErrors = validate(workspace);
setErrors(nextErrors);
if (Object.keys(nextErrors).length) return;
onSaveDraft({
workspaceId: workspace.workspace.id,
baseCommit: draft?.baseCommit ?? EMPTY_COMMIT,
...(draft?.baseBlob ? { baseBlob: draft.baseBlob } : {}),
workspace,
function currentDraft(): WorkspaceBootstrapDraft {
if (props.mode.kind !== "bootstrap") throw new Error("Read-only workspaces cannot create drafts");
return {
workspaceId: props.mode.catalog.id,
baseCommit: props.mode.draft.baseCommit,
workspace: coerceCatalogMetadata(workspace, props.mode.catalog),
updatedAt: new Date().toISOString(),
});
};
}
function publishDraft() {
function saveDraft() {
if (props.mode.kind !== "bootstrap") return;
const nextErrors = validate(workspace);
setErrors(nextErrors);
if (Object.keys(nextErrors).length) return;
const baseCommit = draft?.baseCommit ?? EMPTY_COMMIT;
const request: PublishWorkspaceRequest = draft?.baseBlob
? { action: "update", workspace, baseCommit, baseBlob: draft.baseBlob }
: { action: "create", workspace, baseCommit };
void onPublish(request);
if (Object.keys(nextErrors).length > 0) return;
props.onSaveDraft?.(currentDraft());
}
function requestCreate() {
if (props.mode.kind !== "bootstrap") return;
const nextErrors = validate(workspace);
setErrors(nextErrors);
if (Object.keys(nextErrors).length > 0) return;
const draft = currentDraft();
props.onRequestCreate?.({ action: "create", workspace: draft.workspace, baseCommit: draft.baseCommit }, draft);
}
return (
<form className="grid gap-6" onSubmit={(event) => { event.preventDefault(); saveDraft(); }} noValidate>
<Section title="General">
<Field label="Workspace ID" error={errors["workspace.id"]} hint={idLocked ? "Technical IDs cannot change after publication." : "Lowercase, immutable technical identifier."}>
{({ id, describedBy, invalid }) => <input id={id} aria-label="Workspace ID" aria-describedby={describedBy} aria-invalid={invalid} disabled={idLocked} className={fieldClass} value={workspace.workspace.id} onChange={(event) => update((value) => ({ ...value, workspace: { ...value.workspace, id: event.target.value } }))} />}
<Field label="Workspace ID" error={errors["workspace.id"]} hint="Catalog-owned technical identifier.">
{({ id, describedBy, invalid }) => <input id={id} aria-label="Workspace ID" aria-describedby={describedBy} aria-invalid={invalid} disabled={bootstrapMode} readOnly={readOnly} className={fieldClass} value={workspace.workspace.id} onChange={(event) => update((value) => ({ ...value, workspace: { ...value.workspace, id: event.target.value } }))} />}
</Field>
<Field label="Workspace name" error={errors["workspace.name"]}>
{({ id, describedBy, invalid }) => <input id={id} aria-label="Workspace name" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.workspace.name} onChange={(event) => update((value) => ({ ...value, workspace: { ...value.workspace, name: event.target.value } }))} />}
<Field label="Workspace name" error={errors["workspace.name"]} hint={bootstrapMode ? "Catalog-owned display metadata." : undefined}>
{({ id, describedBy, invalid }) => <input id={id} aria-label="Workspace name" aria-describedby={describedBy} aria-invalid={invalid} disabled={bootstrapMode} readOnly={readOnly} className={fieldClass} value={workspace.workspace.name} onChange={(event) => update((value) => ({ ...value, workspace: { ...value.workspace, name: event.target.value } }))} />}
</Field>
<Field label="Description">
{({ id, describedBy, invalid }) => <input id={id} aria-label="Description" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.workspace.description ?? ""} onChange={(event) => update((value) => ({ ...value, workspace: { ...value.workspace, description: event.target.value || undefined } }))} />}
{({ id, describedBy, invalid }) => <input id={id} aria-label="Description" aria-describedby={describedBy} aria-invalid={invalid} disabled={bootstrapMode} readOnly={readOnly} className={fieldClass} value={workspace.workspace.description ?? ""} onChange={(event) => update((value) => ({ ...value, workspace: { ...value.workspace, description: event.target.value || undefined } }))} />}
</Field>
<Field label="Workspace language">
{({ id, describedBy, invalid }) => <select id={id} aria-label="Workspace language" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.workspace.language} onChange={(event) => update((value) => ({ ...value, workspace: { ...value.workspace, language: event.target.value as "en" | "it" } }))}><option value="en">English</option><option value="it">Italian</option></select>}
{({ id, describedBy, invalid }) => <select id={id} aria-label="Workspace language" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.workspace.language} onChange={(event) => update((value) => ({ ...value, workspace: { ...value.workspace, language: event.target.value as "en" | "it" } }))} disabled={readOnly}><option value="en">English</option><option value="it">Italian</option></select>}
</Field>
</Section>
@@ -191,19 +203,19 @@ export function WorkspaceEditor({ draft, onSaveDraft, onPublish, idLocked = Bool
{({ id, describedBy, invalid }) => <select id={id} aria-label="DWH engine" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value="postgres" disabled><option value="postgres">PostgreSQL</option></select>}
</Field>
<Field label="DWH transport" error={errors["dwh.transport"]} hint="Choose supported installation transports.">
{({ id, describedBy, invalid }) => <select id={id} multiple aria-label="DWH transport" aria-describedby={describedBy} aria-invalid={invalid} className={`${fieldClass} h-24 py-1`} value={workspace.dwh.supported_transports} onChange={(event) => update((value) => ({ ...value, dwh: { ...value.dwh, supported_transports: selectedValues(event) as CanonicalWorkspace["dwh"]["supported_transports"] } }))}><option value="postgres_direct">postgres_direct</option><option value="rest_api">rest_api</option><option value="ssh_tunnel">ssh_tunnel</option></select>}
{({ id, describedBy, invalid }) => <select id={id} multiple aria-label="DWH transport" aria-describedby={describedBy} aria-invalid={invalid} className={`${fieldClass} h-24 py-1`} value={workspace.dwh.supported_transports} onChange={(event) => update((value) => ({ ...value, dwh: { ...value.dwh, supported_transports: selectedValues(event) as CanonicalWorkspace["dwh"]["supported_transports"] } }))} disabled={readOnly}><option value="postgres_direct">postgres_direct</option><option value="rest_api">rest_api</option><option value="ssh_tunnel">ssh_tunnel</option></select>}
</Field>
<Field label="DWH database" error={errors["dwh.database"]}>
{({ id, describedBy, invalid }) => <input id={id} aria-label="DWH database" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.dwh.database} onChange={(event) => update((value) => ({ ...value, dwh: { ...value.dwh, database: event.target.value } }))} />}
{({ id, describedBy, invalid }) => <input id={id} aria-label="DWH database" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.dwh.database} readOnly={readOnly} onChange={(event) => update((value) => ({ ...value, dwh: { ...value.dwh, database: event.target.value } }))} />}
</Field>
<Field label="DWH schema" error={errors["dwh.schema"]}>
{({ id, describedBy, invalid }) => <input id={id} aria-label="DWH schema" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.dwh.schema} onChange={(event) => update((value) => ({ ...value, dwh: { ...value.dwh, schema: event.target.value } }))} />}
{({ id, describedBy, invalid }) => <input id={id} aria-label="DWH schema" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.dwh.schema} readOnly={readOnly} onChange={(event) => update((value) => ({ ...value, dwh: { ...value.dwh, schema: event.target.value } }))} />}
</Field>
<Field label="DWH port" error={errors["dwh.port"]}>
{({ id, describedBy, invalid }) => <input id={id} type="number" min="1" max="65535" aria-label="DWH port" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.dwh.port ?? ""} onChange={(event) => update((value) => ({ ...value, dwh: { ...value.dwh, port: numberOrUndefined(event.target.value) } }))} />}
{({ id, describedBy, invalid }) => <input id={id} type="number" min="1" max="65535" aria-label="DWH port" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.dwh.port ?? ""} readOnly={readOnly} onChange={(event) => update((value) => ({ ...value, dwh: { ...value.dwh, port: numberOrUndefined(event.target.value) } }))} />}
</Field>
<Field label="DWH timeout (ms)" error={errors["dwh.timeout"]}>
{({ id, describedBy, invalid }) => <input id={id} type="number" min="1" aria-label="DWH timeout (ms)" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.dwh.timeout_ms ?? ""} onChange={(event) => update((value) => ({ ...value, dwh: { ...value.dwh, timeout_ms: numberOrUndefined(event.target.value) } }))} />}
{({ id, describedBy, invalid }) => <input id={id} type="number" min="1" aria-label="DWH timeout (ms)" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.dwh.timeout_ms ?? ""} readOnly={readOnly} onChange={(event) => update((value) => ({ ...value, dwh: { ...value.dwh, timeout_ms: numberOrUndefined(event.target.value) } }))} />}
</Field>
</Section>
@@ -212,41 +224,50 @@ export function WorkspaceEditor({ draft, onSaveDraft, onPublish, idLocked = Bool
{({ id, describedBy, invalid }) => <input id={id} aria-label="Vector store engine" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value="qdrant" readOnly />}
</Field>
<Field label="Vector collection" error={errors["vector.collection"]}>
{({ id, describedBy, invalid }) => <input id={id} aria-label="Vector collection" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.semantic_index.vector_store.collection} onChange={(event) => update((value) => ({ ...value, semantic_index: { ...value.semantic_index, vector_store: { ...value.semantic_index.vector_store, collection: event.target.value } } }))} />}
{({ id, describedBy, invalid }) => <input id={id} aria-label="Vector collection" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.semantic_index.vector_store.collection} readOnly={readOnly} onChange={(event) => update((value) => ({ ...value, semantic_index: { ...value.semantic_index, vector_store: { ...value.semantic_index.vector_store, collection: event.target.value } } }))} />}
</Field>
<Field label="Vector distance">
{({ id, describedBy, invalid }) => <input id={id} aria-label="Vector distance" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value="cosine" readOnly />}
</Field>
<Field label="Semantic index dimensions" error={errors["semantic.dimensions"]} hint="One value is shared by the vector collection and embedding model.">
<Field label="Semantic index dimensions" hint="One value is shared by the vector collection and embedding model.">
{({ id, describedBy, invalid }) => <input id={id} type="number" min="1" max="32768" aria-label="Semantic index dimensions" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.semantic_index.vector_store.dimensions} readOnly />}
</Field>
<Field label="Embedding provider">
{({ id, describedBy, invalid }) => <input id={id} aria-label="Embedding provider" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value="ollama_internal" readOnly />}
</Field>
<Field label="Embedding model" error={errors["embedding.model"]}>
<Field label="Embedding model">
{({ id, describedBy, invalid }) => <input id={id} aria-label="Embedding model" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value="qwen3-embedding:0.6b" readOnly />}
</Field>
</Section>
<Section title="LLM policy">
<Field label="Allowed models" error={errors["llm.allowed"]} hint="Comma-separated provider/model identifiers.">
{({ id, describedBy, invalid }) => <input id={id} aria-label="Allowed models" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={allowedModels} onChange={(event) => update((value) => { const allowed = event.target.value.split(",").map((model) => model.trim()).filter(Boolean) as `${string}/${string}`[]; return { ...value, llm_policy: { allowed, ...(value.llm_policy.default && allowed.includes(value.llm_policy.default) ? { default: value.llm_policy.default } : {}) } }; })} />}
{({ id, describedBy, invalid }) => <input id={id} aria-label="Allowed models" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={allowedModels} readOnly={readOnly} onChange={(event) => update((value) => {
const allowed = event.target.value.split(",").map((model) => model.trim()).filter(Boolean) as `${string}/${string}`[];
return { ...value, llm_policy: { allowed, ...(value.llm_policy.default && allowed.includes(value.llm_policy.default) ? { default: value.llm_policy.default } : {}) } };
})} />}
</Field>
<Field label="Default model" error={errors["llm.default"]} hint="Only models in the allowlist are selectable.">
{({ id, describedBy, invalid }) => <select id={id} aria-label="Default model" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.llm_policy.default ?? ""} onChange={(event) => update((value) => ({ ...value, llm_policy: { ...value.llm_policy, ...(event.target.value ? { default: event.target.value as `${string}/${string}` } : {}) } }))}><option value="">No default</option>{workspace.llm_policy.allowed.map((model) => <option key={model} value={model}>{model}</option>)}</select>}
{({ id, describedBy, invalid }) => <select id={id} aria-label="Default model" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value={workspace.llm_policy.default ?? ""} onChange={(event) => update((value) => ({ ...value, llm_policy: { ...value.llm_policy, ...(event.target.value ? { default: event.target.value as `${string}/${string}` } : {}) } }))} disabled={readOnly}><option value="">No default</option>{workspace.llm_policy.allowed.map((model) => <option key={model} value={model}>{model}</option>)}</select>}
</Field>
</Section>
{workspace.evidence && <EvidenceSummary evidence={workspace.evidence} />}
<Section title="Installation requirements">
<p className="sm:col-span-2 text-sm text-muted-foreground">Hosts, users, secret-file paths, and credentials are installation bindings. They are intentionally not editable or stored in workspace drafts.</p>
<p className="sm:col-span-2 text-sm text-muted-foreground">Hosts, users, secret-file paths, and credentials are installation bindings. They are intentionally not editable or stored in browser drafts.</p>
</Section>
<div className="flex justify-end gap-2 border-t border-border/70 pt-4">
<Button type="submit" variant="outline">Save draft</Button>
<Button type="button" onClick={publishDraft}>Publish draft</Button>
</div>
{readOnly ? (
<Section title="Curator workflow">
<p className="sm:col-span-2 text-sm text-muted-foreground">To change this workspace, edit {workspace.workspace.id}/workspace.yaml, commit/push, then Pull.</p>
</Section>
) : (
<div className="flex justify-end gap-2 border-t border-border/70 pt-4">
<Button type="submit">Save draft</Button>
{"onRequestCreate" in props && props.onRequestCreate && <Button type="button" variant="outline" onClick={requestCreate}>Create workspace</Button>}
</div>
)}
</form>
);
}
+136 -216
View File
@@ -4,17 +4,53 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { http, HttpResponse } from "msw";
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { server } from "../test/msw";
import { workspaceRevisionFixture, workspaceSummaryFixture } from "../test/workspace-fixtures";
import { WorkspaceManager } from "./WorkspaceManager";
const workspace = {
workspace: { schema_version: 3, id: "psd-clinical", name: "PSD Clinical", language: "en" },
dwh: { engine: "postgres", database: "clinical", schema: "datawarehouse", port: 5432, supported_transports: ["postgres_direct"] },
semantic_index: {
vector_store: { engine: "qdrant", collection: "clinical", dimensions: 1024, distance: "cosine" },
embedding: { provider: "ollama_internal", model: "qwen3-embedding:0.6b", dimensions: 1024 },
const readyWorkspace = {
workspace: {
schema_version: 3,
id: "psd-clinical",
name: "PSD Clinical",
description: "Clinical data",
language: "en" as const,
},
llm_policy: { default: "zai/glm-5.2", allowed: ["zai/glm-5.2"] },
} as const;
dwh: {
engine: "postgres" as const,
database: "clinical",
schema: "datawarehouse",
port: 5432,
supported_transports: ["postgres_direct"] as const,
},
semantic_index: {
vector_store: { engine: "qdrant" as const, collection: "clinical", dimensions: 1024 as const, distance: "cosine" as const },
embedding: { provider: "ollama_internal" as const, model: "qwen3-embedding:0.6b" as const, dimensions: 1024 as const },
},
llm_policy: { default: "zai/glm-5.2" as const, allowed: ["zai/glm-5.2"] as const },
evidence: {
source: {
type: "filesystem" as const,
uri: "psd-clinical/evidence",
patterns: ["documents/**/*.pdf"],
max_bytes: 12_000_000,
},
policy: { max_chunk_chars: 8_000, retain_published_generations: 5 },
},
};
const bootstrapWorkspace = {
...readyWorkspace,
workspace: {
...readyWorkspace.workspace,
id: "bootstrap-slot",
name: "Bootstrap slot",
description: "Needs configuration",
},
semantic_index: {
...readyWorkspace.semantic_index,
vector_store: { ...readyWorkspace.semantic_index.vector_store, collection: "bootstrap_slot" },
},
};
function renderManager() {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
@@ -26,58 +62,108 @@ beforeEach(() => {
server.use(
http.get("/api/workspace-registry/status", () =>
HttpResponse.json({ branch: "main", head: "a".repeat(40), ahead: 0, behind: 0, degraded: false })),
http.get("/api/workspaces", () => HttpResponse.json([{
id: "psd-clinical", name: "psd-clinical", displayName: "PSD Clinical", description: "Clinical data",
language: "en", file: "psd-clinical.yaml",
revision: { id: "psd-clinical", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/tmp/psd" },
}])),
http.get("/api/workspaces", () => HttpResponse.json([
workspaceSummaryFixture("bootstrap-slot", {
displayName: "Bootstrap slot",
description: "Needs configuration",
configurationState: "configuration_required",
}),
workspaceSummaryFixture("psd-clinical", {
displayName: "PSD Clinical",
description: "Clinical data",
revision: workspaceRevisionFixture("psd-clinical"),
}),
])),
http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({
workspace,
revision: { id: "psd-clinical", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/tmp/psd" },
workspace: readyWorkspace,
revision: workspaceRevisionFixture("psd-clinical"),
})),
);
});
afterEach(() => vi.unstubAllGlobals());
test("lists registry workspaces and saves a new workspace only as a browser draft", async () => {
test("renders catalog slots in order and opens a bootstrap form for configuration_required entries", async () => {
const user = userEvent.setup();
renderManager();
expect(await screen.findByRole("heading", { name: "Workspace management" })).toBeVisible();
expect(await screen.findByRole("button", { name: "PSD Clinical" })).toBeVisible();
expect(screen.getByText(`Commit ${"a".repeat(12)}`)).toBeVisible();
await user.click(screen.getByRole("button", { name: "New workspace" }));
await user.clear(screen.getByLabelText("Workspace ID"));
await user.type(screen.getByLabelText("Workspace ID"), "trial-registry");
expect(screen.getByRole("button", { name: "Bootstrap slot" })).toBeVisible();
expect(screen.getByRole("button", { name: "PSD Clinical" })).toBeVisible();
await user.click(screen.getByRole("button", { name: "Bootstrap slot" }));
expect(await screen.findByLabelText("Workspace ID")).toHaveValue("bootstrap-slot");
expect(screen.getByLabelText("Workspace ID")).toBeDisabled();
expect(screen.getByLabelText("Workspace name")).toHaveValue("Bootstrap slot");
expect(screen.getByLabelText("Workspace name")).toBeDisabled();
expect(screen.getByLabelText("Description")).toHaveValue("Needs configuration");
expect(screen.getByRole("button", { name: "Save draft" })).toBeVisible();
expect(screen.getByRole("button", { name: "Create workspace" })).toBeVisible();
});
test("saves a bootstrap draft locally for a configuration_required slot", async () => {
const user = userEvent.setup();
renderManager();
await user.click(await screen.findByRole("button", { name: "Bootstrap slot" }));
await user.clear(screen.getByLabelText("Vector collection"));
await user.type(screen.getByLabelText("Vector collection"), "bootstrap_docs");
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(screen.getByText("Draft saved in this browser.")).toBeVisible());
expect(localStorage.getItem("thothii.workspace-registry.v1.draft.trial-registry")).not.toBeNull();
expect(localStorage.getItem("thothii.workspace-registry.v2.bootstrap.bootstrap-slot")).toContain('"baseCommit"');
expect(localStorage.getItem("thothii.workspace-registry.v2.bootstrap.bootstrap-slot")).not.toContain("baseBlob");
});
test("imports a bundle as a local draft and never publishes it automatically", async () => {
test("successful create discards the bootstrap draft and reloads the workspace as read-only", async () => {
const user = userEvent.setup();
const publishSpy = vi.fn();
let workspacesCalls = 0;
server.use(
http.post("/api/workspaces/import", () => HttpResponse.json({ draft: { workspace, contract: {} } })),
http.post("/api/workspaces/publish", () => {
publishSpy();
return HttpResponse.json({});
http.get("/api/workspaces", () => {
workspacesCalls += 1;
return HttpResponse.json(workspacesCalls === 1 ? [
workspaceSummaryFixture("bootstrap-slot", {
displayName: "Bootstrap slot",
description: "Needs configuration",
configurationState: "configuration_required",
}),
] : [
workspaceSummaryFixture("bootstrap-slot", {
displayName: "Bootstrap slot",
description: "Needs configuration",
revision: workspaceRevisionFixture("bootstrap-slot"),
}),
]);
}),
http.get("/api/workspaces/bootstrap-slot", () => HttpResponse.json({
workspace: bootstrapWorkspace,
revision: workspaceRevisionFixture("bootstrap-slot"),
})),
http.post("/api/workspaces/validate", () => HttpResponse.json({ workspace: bootstrapWorkspace, contract: {} })),
http.post("/api/workspaces/publish", () => HttpResponse.json({ revision: workspaceRevisionFixture("bootstrap-slot") })),
);
localStorage.setItem("thothii.workspace-registry.v2.bootstrap.bootstrap-slot", JSON.stringify({
workspaceId: "bootstrap-slot",
baseCommit: "a".repeat(40),
workspace: bootstrapWorkspace,
updatedAt: "2026-08-04T10:00:00.000Z",
}));
renderManager();
await user.upload(screen.getByLabelText("Import workspace bundle"), new File(["bundle"], "workspace.zip", { type: "application/zip" }));
await user.click(await screen.findByRole("button", { name: "Bootstrap slot" }));
await user.click(screen.getByRole("button", { name: "Create workspace" }));
await user.click(screen.getByRole("button", { name: "Validate draft" }));
await user.click(await screen.findByRole("button", { name: "Create workspace" }));
await user.click(screen.getByRole("button", { name: "Confirm create" }));
expect(await screen.findByText("Imported draft saved in this browser. Validate it before publishing.")).toBeVisible();
expect(publishSpy).not.toHaveBeenCalled();
expect(localStorage.getItem("thothii.workspace-registry.v1.draft.psd-clinical")).not.toBeNull();
await waitFor(() => expect(localStorage.getItem("thothii.workspace-registry.v2.bootstrap.bootstrap-slot")).toBeNull());
expect(await screen.findByText(/edit bootstrap-slot\/workspace\.yaml, commit\/push, then Pull/i)).toBeVisible();
expect(screen.queryByRole("button", { name: "Save draft" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Create workspace" })).not.toBeInTheDocument();
});
test("pulls and exports only when the manager explicitly requests each action", async () => {
test("ready workspaces stay read-only while keeping pull, export, validate, and installation test actions", async () => {
const user = userEvent.setup();
const publishSpy = vi.fn();
const createObjectURL = vi.fn(() => "blob:workspace-bundle");
const revokeObjectURL = vi.fn();
class DownloadUrl extends URL {
@@ -89,123 +175,22 @@ test("pulls and exports only when the manager explicitly requests each action",
server.use(
http.post("/api/workspace-registry/pull", () => HttpResponse.json({ branch: "main", head: "c".repeat(40), ahead: 0, behind: 0, degraded: false })),
http.get("/api/workspaces/psd-clinical/export", () => new HttpResponse(new Blob(["bundle"], { type: "application/zip" }))),
http.post("/api/workspaces/publish", () => {
publishSpy();
return HttpResponse.json({});
}),
);
renderManager();
await user.click(await screen.findByRole("button", { name: "PSD Clinical" }));
await user.click(screen.getByRole("button", { name: "Pull latest registry" }));
expect(await screen.findByText("Registry updated. Reload a workspace to review its latest revision.")).toBeVisible();
await user.click(screen.getByRole("button", { name: "Export workspace bundle" }));
await waitFor(() => expect(createObjectURL).toHaveBeenCalledTimes(1));
expect(revokeObjectURL).toHaveBeenCalledWith("blob:workspace-bundle");
expect(publishSpy).not.toHaveBeenCalled();
});
test("stages duplicate and delete operations without publishing", async () => {
const user = userEvent.setup();
let published = false;
server.use(http.post("/api/workspaces/publish", () => {
published = true;
return HttpResponse.json({});
}));
renderManager();
await user.click(await screen.findByRole("button", { name: "PSD Clinical" }));
await user.click(screen.getByRole("button", { name: "Duplicate workspace" }));
expect(screen.getByLabelText("Workspace ID")).not.toBeDisabled();
await user.click(screen.getByRole("button", { name: "PSD Clinical" }));
await user.click(screen.getByRole("button", { name: "Delete workspace" }));
expect(screen.getByText("Deletion draft staged locally.")).toBeVisible();
expect(published).toBe(false);
});
test("saves resolved conflict choices as a rebased browser draft without publishing again", async () => {
const user = userEvent.setup();
let publishCalls = 0;
const local = { ...workspace, semantic_index: { ...workspace.semantic_index, vector_store: { ...workspace.semantic_index.vector_store, collection: "local_collection" } } };
const remote = { ...workspace, semantic_index: { ...workspace.semantic_index, vector_store: { ...workspace.semantic_index.vector_store, collection: "remote_collection" } } };
server.use(
http.post("/api/workspaces/validate", () => HttpResponse.json({ workspace: local, contract: {} })),
http.post("/api/workspaces/publish", () => {
publishCalls += 1;
return HttpResponse.json({
code: "workspace_conflict", message: "Workspace changed in the registry.", fields: ["semantic_index.vector_store.collection"],
expected: { commit: "a".repeat(40), blob: "b".repeat(40) }, actual: { commit: "c".repeat(40), blob: "d".repeat(40) },
base: workspace, local, remote,
}, { status: 409 });
}),
);
renderManager();
await user.click(await screen.findByRole("button", { name: "PSD Clinical" }));
await user.click(screen.getByRole("button", { name: "Publish draft" }));
await user.click(screen.getByRole("button", { name: "Validate draft" }));
await user.click(await screen.findByRole("button", { name: "Publish" }));
await user.click(screen.getByRole("button", { name: "Confirm publish" }));
await user.click(await screen.findByRole("radio", { name: "Use your draft for semantic_index.vector_store.collection" }));
await user.click(screen.getByRole("button", { name: "Save revised draft" }));
expect(await screen.findByText("Revised draft saved with registry revision cccccccccccc. Validate it before publishing.")).toBeVisible();
expect(localStorage.getItem("thothii.workspace-registry.v1.draft.psd-clinical")).toContain('"baseCommit":"cccccccccccccccccccccccccccccccccccccccc"');
expect(localStorage.getItem("thothii.workspace-registry.v1.draft.psd-clinical")).toContain('"baseBlob":"dddddddddddddddddddddddddddddddddddddddd"');
expect(publishCalls).toBe(1);
});
test("proposes a different valid ID when duplicating a 63-character workspace ID", async () => {
const user = userEvent.setup();
const maxId = `w${"a".repeat(62)}`;
const maxWorkspace = { ...workspace, workspace: { ...workspace.workspace, id: maxId } };
server.use(
http.get("/api/workspaces", () => HttpResponse.json([{
id: maxId, name: maxId, displayName: "Maximum", language: "en", file: `${maxId}.yaml`,
revision: { id: maxId, commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/tmp/maximum" },
}])),
http.get(`/api/workspaces/${maxId}`, () => HttpResponse.json({
workspace: maxWorkspace,
revision: { id: maxId, commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/tmp/maximum" },
})),
);
renderManager();
await user.click(await screen.findByRole("button", { name: "Maximum" }));
await user.click(screen.getByRole("button", { name: "Duplicate workspace" }));
const proposed = screen.getByLabelText("Workspace ID") as HTMLInputElement;
expect(proposed.value).toMatch(/^[a-z][a-z0-9-]{2,62}$/);
expect(proposed).not.toHaveValue(maxId);
});
test("does not show a saved-draft toast when manager validation rejects a DWH timeout", async () => {
const user = userEvent.setup();
renderManager();
await user.click(await screen.findByRole("button", { name: "PSD Clinical" }));
await user.clear(screen.getByLabelText("DWH timeout (ms)"));
await user.type(screen.getByLabelText("DWH timeout (ms)"), "0");
await user.click(screen.getByRole("button", { name: "Save draft" }));
expect(screen.getByRole("alert")).toHaveTextContent("DWH timeout must be a positive whole number");
expect(screen.queryByText("Draft saved in this browser.")).not.toBeInTheDocument();
});
test("runs validation and installation test with only sanitized messages", async () => {
const user = userEvent.setup();
server.use(
http.post("/api/workspaces/validate", () => HttpResponse.json({ workspace, contract: {} })),
http.post("/api/workspaces/validate", () => HttpResponse.json({ workspace: readyWorkspace, contract: {} })),
http.post("/api/workspaces/psd-clinical/test", () => HttpResponse.json({
activatable: false,
diagnostics: [{ level: "warning", code: "binding_missing", field: "dwh", message: "DWH binding is not configured" }],
})),
);
localStorage.setItem("thothii.workspace-registry.v1.draft.psd-clinical", JSON.stringify({ foo: "bar" }));
renderManager();
await user.click(await screen.findByRole("button", { name: "PSD Clinical" }));
expect(await screen.findByText(/edit psd-clinical\/workspace\.yaml, commit\/push, then Pull/i)).toBeVisible();
expect(screen.queryByRole("button", { name: /duplicate workspace|delete workspace|publish draft/i })).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Pull latest registry" }));
expect(await screen.findByText("Registry updated. Reload a workspace to review its latest revision.")).toBeVisible();
await user.click(screen.getByRole("button", { name: "Export workspace bundle" }));
await waitFor(() => expect(createObjectURL).toHaveBeenCalledTimes(1));
await user.click(screen.getByRole("button", { name: "Validate workspace" }));
expect(await screen.findByText("Workspace definition is valid.")).toBeVisible();
await user.click(screen.getByRole("button", { name: "Test on this installation" }));
@@ -213,81 +198,16 @@ test("runs validation and installation test with only sanitized messages", async
expect(within(screen.getByTestId("workspace-diagnostics")).queryByText(/password|token|secret/i)).not.toBeInTheDocument();
});
test("loads a state-free registry revision and displays only its commit", async () => {
test("import populates only a matching configuration_required slot and refuses existing workspaces", async () => {
const user = userEvent.setup();
renderManager();
await user.click(await screen.findByRole("button", { name: "PSD Clinical" }));
server.use(http.post("/api/workspaces/import", () => HttpResponse.json({ draft: { workspace: readyWorkspace, contract: {} } })));
await user.upload(screen.getByLabelText("Import workspace bundle"), new File(["bundle"], "workspace.zip", { type: "application/zip" }));
expect(await screen.findByText(/workspace_invalid: Imported bundle can only bootstrap a matching catalog slot/i)).toBeVisible();
expect(await screen.findByLabelText("Vector collection")).toBeVisible();
expect(screen.getByText(`Revision ${"a".repeat(12)}`)).toBeVisible();
expect(screen.queryByText(/migration required/i)).not.toBeInTheDocument();
});
test("shows an actionable unavailable message when a workspace summary omits its canonical revision", async () => {
const user = userEvent.setup();
server.use(
http.get("/api/workspaces", () => HttpResponse.json([
{
id: "broken-workspace", name: "broken-workspace", displayName: "Broken workspace", description: "Broken data",
language: "en", file: "broken-workspace.yaml",
},
])),
);
renderManager();
await user.click(await screen.findByRole("button", { name: "Broken workspace" }));
expect(await screen.findByText("This workspace summary is incomplete. Refresh the registry or choose another workspace before creating sessions or editing drafts.")).toBeVisible();
expect(screen.queryByLabelText("Vector collection")).not.toBeInTheDocument();
});
test("shows an accessible retry instead of a loading status when the registry status query fails", async () => {
const user = userEvent.setup();
let calls = 0;
server.use(http.get("/api/workspace-registry/status", () => {
calls += 1;
return calls === 1 ? new HttpResponse(null, { status: 503 }) : HttpResponse.json({ branch: "main", ahead: 0, behind: 0, degraded: false });
}));
renderManager();
expect(await screen.findByRole("alert", { name: "Workspace registry status failed" })).toHaveTextContent("Could not load registry status.");
await user.click(screen.getByRole("button", { name: "Retry registry status" }));
expect(await screen.findByText("main")).toBeVisible();
expect(calls).toBe(2);
});
test("shows an accessible retry instead of an empty list when the workspace list query fails", async () => {
const user = userEvent.setup();
let calls = 0;
server.use(http.get("/api/workspaces", () => {
calls += 1;
return calls === 1 ? new HttpResponse(null, { status: 503 }) : HttpResponse.json([]);
}));
renderManager();
expect(await screen.findByRole("alert", { name: "Workspace list failed" })).toHaveTextContent("Could not load workspaces.");
expect(screen.queryByText("No published workspaces.")).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Retry workspace list" }));
expect(await screen.findByText("No published workspaces.")).toBeVisible();
expect(calls).toBe(2);
});
test("shows an accessible retry when the selected workspace detail query fails", async () => {
const user = userEvent.setup();
let calls = 0;
server.use(http.get("/api/workspaces/psd-clinical", () => {
calls += 1;
return calls === 1 ? new HttpResponse(null, { status: 503 }) : HttpResponse.json({
workspace,
revision: { id: "psd-clinical", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/tmp/psd" },
});
}));
renderManager();
await user.click(await screen.findByRole("button", { name: "PSD Clinical" }));
expect(await screen.findByRole("alert", { name: "Workspace details failed" })).toHaveTextContent("Could not load workspace details.");
await user.click(screen.getByRole("button", { name: "Retry workspace details" }));
expect(await screen.findByRole("heading", { name: "PSD Clinical" })).toBeVisible();
expect(calls).toBe(2);
server.use(http.post("/api/workspaces/import", () => HttpResponse.json({ draft: { workspace: bootstrapWorkspace, contract: {} } })));
await user.upload(screen.getByLabelText("Import workspace bundle"), new File(["bundle"], "workspace.zip", { type: "application/zip" }));
expect(await screen.findByText("Imported bootstrap draft saved in this browser. Validate it before creating the descriptor.")).toBeVisible();
expect(localStorage.getItem("thothii.workspace-registry.v2.bootstrap.bootstrap-slot")).not.toBeNull();
});
+169 -217
View File
@@ -1,12 +1,22 @@
import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { AlertCircle, CheckCircle2, ClipboardCheck, Download, FlaskConical, GitPullRequest, Plus, Trash2, Copy, Upload, X } from "lucide-react";
import { AlertCircle, CheckCircle2, ClipboardCheck, Download, FlaskConical, GitPullRequest, Upload, X } from "lucide-react";
import {
asWorkspaceApiError, exportWorkspace, getWorkspace, getWorkspaceRegistryStatus, importWorkspace,
listWorkspaces, pullWorkspaceRegistry, testWorkspace, validateWorkspace, type CanonicalWorkspace,
type PublishWorkspaceRequest, type WorkspaceRecord, type WorkspaceRevision,
asWorkspaceApiError,
exportWorkspace,
getWorkspace,
getWorkspaceRegistryStatus,
importWorkspace,
listWorkspaces,
pullWorkspaceRegistry,
testWorkspace,
validateWorkspace,
type CanonicalWorkspace,
type PublishWorkspaceRequest,
type WorkspaceRecord,
type WorkspaceSummary,
} from "../api/workspaces";
import { workspaceDeletionDrafts, workspaceDrafts, type WorkspaceDeletionDraft, type WorkspaceDraft } from "../workspaces/drafts";
import { workspaceBootstrapDrafts, type WorkspaceBootstrapDraft } from "../workspaces/drafts";
import { Button } from "../components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "../components/ui/dialog";
import { WorkspaceEditor } from "./WorkspaceEditor";
@@ -14,34 +24,6 @@ import { WorkspacePublishDialog } from "./WorkspacePublishDialog";
const EMPTY_COMMIT = "0".repeat(40);
function newWorkspace(): CanonicalWorkspace {
return {
workspace: { schema_version: 3, id: "new-workspace", name: "New workspace", language: "en" },
dwh: { engine: "postgres", database: "database", schema: "public", supported_transports: ["postgres_direct"] },
semantic_index: {
vector_store: { engine: "qdrant", collection: "documents", dimensions: 1024, distance: "cosine" },
embedding: { provider: "ollama_internal", model: "qwen3-embedding:0.6b", dimensions: 1024 },
},
llm_policy: { allowed: ["zai/glm-5.2"] },
};
}
function draftFromRecord(record: WorkspaceRecord): WorkspaceDraft {
return {
workspaceId: record.workspace.workspace.id,
baseCommit: record.revision.commit,
baseBlob: record.revision.blob,
workspace: record.workspace,
updatedAt: new Date().toISOString(),
};
}
function proposedId(id: string): string {
const copy = `${id.slice(0, 58)}-copy`;
// A max-length source ending in "-copy" would otherwise reproduce itself.
return copy === id ? `${id.slice(0, 61)}-2` : copy;
}
function QueryError({ name, message, retryLabel, onRetry }: {
name: string;
message: string;
@@ -51,98 +33,99 @@ function QueryError({ name, message, retryLabel, onRetry }: {
return <div role="alert" aria-label={name} className="grid gap-2 rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm"><p>{message}</p><div><Button size="sm" variant="outline" onClick={onRetry}>{retryLabel}</Button></div></div>;
}
function defaultBootstrapWorkspace(summary: WorkspaceSummary): CanonicalWorkspace {
return {
workspace: {
schema_version: 3,
id: summary.id,
name: summary.displayName,
...(summary.description ? { description: summary.description } : {}),
language: "en",
},
dwh: {
engine: "postgres",
database: "database",
schema: "public",
supported_transports: ["postgres_direct"],
},
semantic_index: {
vector_store: {
engine: "qdrant",
collection: summary.id.replaceAll("-", "_"),
dimensions: 1024,
distance: "cosine",
},
embedding: {
provider: "ollama_internal",
model: "qwen3-embedding:0.6b",
dimensions: 1024,
},
},
llm_policy: { allowed: ["zai/glm-5.2"], default: "zai/glm-5.2" },
};
}
function bootstrapDraftFor(summary: WorkspaceSummary, baseCommit: string): WorkspaceBootstrapDraft {
return {
workspaceId: summary.id,
baseCommit,
workspace: defaultBootstrapWorkspace(summary),
updatedAt: new Date().toISOString(),
};
}
export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: () => void }) {
const [selectedId, setSelectedId] = useState<string>();
const [localDraft, setLocalDraft] = useState<WorkspaceDraft>();
const [localDraft, setLocalDraft] = useState<WorkspaceBootstrapDraft>();
const [notice, setNotice] = useState<string>();
const [diagnostics, setDiagnostics] = useState<string[]>([]);
const [deletionDraft, setDeletionDraft] = useState<WorkspaceDeletionDraft>();
const [publishRequest, setPublishRequest] = useState<PublishWorkspaceRequest>();
const [transferring, setTransferring] = useState(false);
const statusQuery = useQuery({ queryKey: ["workspace-registry-status"], queryFn: getWorkspaceRegistryStatus, enabled: open });
const workspacesQuery = useQuery({ queryKey: ["workspaces"], queryFn: listWorkspaces, enabled: open });
const workspaces = workspacesQuery.data ?? [];
const selectedSummary = useMemo(() => workspaces.find((workspace) => workspace.id === selectedId), [selectedId, workspaces]);
const selectedSummaryIncomplete = Boolean(selectedSummary && !selectedSummary.revision);
const detailQuery = useQuery({
queryKey: ["workspace", selectedId],
queryFn: () => getWorkspace(selectedId!),
enabled: Boolean(open && selectedId && !localDraft && !selectedSummaryIncomplete),
enabled: Boolean(open && selectedId && selectedSummary?.configurationState === "ready"),
});
const status = statusQuery.data;
const record = detailQuery.data;
const savedDraft = selectedId && !localDraft ? workspaceDrafts.load(selectedId) : undefined;
const savedDeletionDraft = selectedId && !deletionDraft ? workspaceDeletionDrafts.load(selectedId) : undefined;
const currentDraft = localDraft ?? savedDraft ?? (record ? draftFromRecord(record) : undefined);
const activeDeletionDraft = deletionDraft ?? savedDeletionDraft;
const canTest = Boolean(record && currentDraft?.workspaceId === record.workspace.workspace.id);
const activeBootstrapDraft = selectedSummary?.configurationState === "configuration_required"
? (localDraft?.workspaceId === selectedSummary.id ? localDraft : workspaceBootstrapDrafts.load(selectedSummary.id) ?? bootstrapDraftFor(selectedSummary, statusQuery.data?.head ?? EMPTY_COMMIT))
: undefined;
function resetTransientState() {
setNotice(undefined);
setDiagnostics([]);
setPublishRequest(undefined);
}
function selectWorkspace(id: string) {
setSelectedId(id);
setLocalDraft(undefined);
setDeletionDraft(undefined);
setNotice(undefined);
setDiagnostics([]);
setPublishRequest(undefined);
resetTransientState();
}
function createWorkspace() {
const draft: WorkspaceDraft = { workspaceId: "new-workspace", baseCommit: EMPTY_COMMIT, workspace: newWorkspace(), updatedAt: new Date().toISOString() };
setSelectedId(draft.workspaceId);
function saveDraft(draft: WorkspaceBootstrapDraft) {
workspaceBootstrapDrafts.save(draft);
setLocalDraft(draft);
setDeletionDraft(undefined);
setNotice("New draft. Choose its immutable workspace ID before saving.");
setDiagnostics([]);
setPublishRequest(undefined);
}
function duplicateWorkspace() {
if (!currentDraft) return;
const id = proposedId(currentDraft.workspace.workspace.id);
const duplicate: WorkspaceDraft = {
...currentDraft,
workspaceId: id,
workspace: { ...currentDraft.workspace, workspace: { ...currentDraft.workspace.workspace, id, name: `${currentDraft.workspace.workspace.name} copy` } },
updatedAt: new Date().toISOString(),
};
setSelectedId(id);
setLocalDraft(duplicate);
setDeletionDraft(undefined);
setNotice("Duplicate draft. Give it a new immutable workspace ID before publishing.");
setPublishRequest(undefined);
}
function saveDraft(draft: WorkspaceDraft) {
workspaceDrafts.save(draft);
setSelectedId(draft.workspaceId);
setLocalDraft(draft);
setNotice("Draft saved in this browser.");
setDiagnostics([]);
}
function requestPublish(request: PublishWorkspaceRequest) {
if (request.action !== "delete") {
const nextDraft: WorkspaceDraft = {
workspaceId: request.workspace.workspace.id,
baseCommit: request.baseCommit,
...(request.action === "update" ? { baseBlob: request.baseBlob } : {}),
workspace: request.workspace,
updatedAt: new Date().toISOString(),
};
workspaceDrafts.save(nextDraft);
setLocalDraft(nextDraft);
setSelectedId(nextDraft.workspaceId);
}
function requestCreate(request: PublishWorkspaceRequest, draft: WorkspaceBootstrapDraft) {
workspaceBootstrapDrafts.save(draft);
setLocalDraft(draft);
setSelectedId(draft.workspaceId);
setNotice(undefined);
setDiagnostics([]);
setPublishRequest(request);
}
function requestDeletionPublish() {
if (!activeDeletionDraft) return;
requestPublish({ action: "delete", id: activeDeletionDraft.id, baseCommit: activeDeletionDraft.baseCommit, baseBlob: activeDeletionDraft.baseBlob });
}
async function pullLatest() {
setNotice(undefined);
setDiagnostics([]);
@@ -153,47 +136,35 @@ export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: ()
} catch (error) {
const safe = asWorkspaceApiError(error);
setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "git_unavailable: Registry pull could not be completed"]);
throw error;
}
}
function reloadWorkspace() {
if (selectedId) {
workspaceDrafts.discard(selectedId);
workspaceDeletionDrafts.discard(selectedId);
}
setLocalDraft(undefined);
setDeletionDraft(undefined);
setPublishRequest(undefined);
setNotice("Workspace reloaded from the registry. Your prior browser draft was discarded.");
setDiagnostics([]);
void detailQuery.refetch();
}
async function importBundle(file: File | undefined) {
if (!file) return;
setTransferring(true);
async function validateSelectedWorkspace() {
if (!record) return;
setNotice(undefined);
setDiagnostics([]);
try {
const result = await importWorkspace(file);
const imported: WorkspaceDraft = {
workspaceId: result.draft.workspace.workspace.id,
baseCommit: EMPTY_COMMIT,
workspace: result.draft.workspace,
updatedAt: new Date().toISOString(),
};
workspaceDrafts.save(imported);
setSelectedId(imported.workspaceId);
setLocalDraft(imported);
setDeletionDraft(undefined);
setPublishRequest(undefined);
setNotice("Imported draft saved in this browser. Validate it before publishing.");
await validateWorkspace(record.workspace);
setNotice("Workspace definition is valid.");
} catch (error) {
const safe = asWorkspaceApiError(error);
setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "workspace_invalid: Workspace bundle could not be imported"]);
} finally {
setTransferring(false);
setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "workspace_invalid: Validation could not be completed"]);
}
}
async function testSelectedWorkspace() {
if (!record) return;
setNotice(undefined);
setDiagnostics([]);
try {
const result = await testWorkspace(record.workspace.workspace.id);
setDiagnostics(result.diagnostics.map((diagnostic) => `${diagnostic.code}: ${diagnostic.message}`));
if (result.diagnostics.length === 0) {
setNotice(result.activatable ? "Installation test passed." : "Installation test completed.");
}
} catch (error) {
const safe = asWorkspaceApiError(error);
setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "connector_unavailable: Installation test could not be completed"]);
}
}
@@ -219,80 +190,62 @@ export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: ()
}
}
function published(revision: WorkspaceRevision | undefined) {
const publishedRequest = publishRequest;
if (publishedRequest?.action === "delete") {
workspaceDeletionDrafts.discard(publishedRequest.id);
setSelectedId(undefined);
} else if (publishedRequest) {
workspaceDrafts.discard(publishedRequest.workspace.workspace.id);
setSelectedId(publishedRequest.workspace.workspace.id);
async function importBundle(file: File | undefined) {
if (!file) return;
setTransferring(true);
setNotice(undefined);
setDiagnostics([]);
try {
const result = await importWorkspace(file);
const importedId = result.draft.workspace.workspace.id;
const catalog = workspaces.length > 0 ? workspaces : ((await workspacesQuery.refetch()).data ?? []);
const matchingSummary = catalog.find((workspace) => workspace.id === importedId && workspace.configurationState === "configuration_required");
if (!matchingSummary) {
setDiagnostics(["workspace_invalid: Imported bundle can only bootstrap a matching catalog slot"]);
return;
}
const draft: WorkspaceBootstrapDraft = {
workspaceId: importedId,
baseCommit: statusQuery.data?.head ?? EMPTY_COMMIT,
workspace: result.draft.workspace,
updatedAt: new Date().toISOString(),
};
workspaceBootstrapDrafts.save(draft);
setNotice("Imported bootstrap draft saved in this browser. Validate it before creating the descriptor.");
} catch (error) {
const safe = asWorkspaceApiError(error);
setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "workspace_invalid: Workspace bundle could not be imported"]);
} finally {
setTransferring(false);
}
}
function published() {
if (publishRequest) {
workspaceBootstrapDrafts.discard(publishRequest.workspace.workspace.id);
setSelectedId(publishRequest.workspace.workspace.id);
setNotice(`To change this workspace, edit ${publishRequest.workspace.workspace.id}/workspace.yaml, commit/push, then Pull.`);
} else {
setNotice("Workspace created.");
}
setLocalDraft(undefined);
setDeletionDraft(undefined);
setPublishRequest(undefined);
setNotice(revision ? `Published revision ${revision.commit.slice(0, 12)}.` : "Workspace published.");
void Promise.all([statusQuery.refetch(), workspacesQuery.refetch(), detailQuery.refetch()]);
}
function saveResolvedDraft(draft: WorkspaceDraft) {
workspaceDrafts.save(draft);
setSelectedId(draft.workspaceId);
setLocalDraft(draft);
setDeletionDraft(undefined);
setPublishRequest(undefined);
setDiagnostics([]);
setNotice(`Revised draft saved with registry revision ${draft.baseCommit.slice(0, 12)}. Validate it before publishing.`);
void Promise.all([statusQuery.refetch(), workspacesQuery.refetch()]).then(() => detailQuery.refetch());
}
async function validateCurrent() {
if (!currentDraft) return;
setNotice(undefined);
setDiagnostics([]);
try {
const result = await validateWorkspace(currentDraft.workspace);
setLocalDraft({ ...currentDraft, workspace: result.workspace, updatedAt: new Date().toISOString() });
setNotice("Workspace definition is valid.");
} catch (error) {
const safe = asWorkspaceApiError(error);
setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "workspace_invalid: Validation could not be completed"]);
}
}
async function testCurrent() {
if (!record) return;
setNotice(undefined);
setDiagnostics([]);
try {
const result = await testWorkspace(record.workspace.workspace.id);
setDiagnostics(result.diagnostics.map((diagnostic) => `${diagnostic.code}: ${diagnostic.message}`));
if (result.diagnostics.length === 0) setNotice(result.activatable ? "Installation test passed." : "Installation test completed.");
} catch (error) {
const safe = asWorkspaceApiError(error);
setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "connector_unavailable: Installation test could not be completed"]);
}
}
function stageDeletion() {
if (!currentDraft?.baseBlob || !record || currentDraft.workspaceId !== record.workspace.workspace.id) return;
const draft = { id: currentDraft.workspaceId, baseCommit: currentDraft.baseCommit, baseBlob: currentDraft.baseBlob, updatedAt: new Date().toISOString() };
workspaceDeletionDrafts.save(draft);
setDeletionDraft(draft);
setNotice("Deletion draft staged locally.");
setDiagnostics([]);
}
const titleReady = workspacesQuery.isSuccess || workspacesQuery.isError;
return (
<Dialog open={open} onOpenChange={(nextOpen) => { if (!nextOpen) onClose(); }}>
<DialogContent showCloseButton={false} className="max-h-[min(90vh,54rem)] max-w-[min(94vw,74rem)] overflow-hidden p-0">
<DialogHeader className="border-b border-border/70 px-5 pb-4 pt-5 pr-12">
<DialogTitle>Workspace management</DialogTitle>
<DialogDescription>Draft shared workspace definitions locally. Installation bindings and secrets stay outside this page.</DialogDescription>
<DialogTitle>{titleReady ? "Workspace management" : ""}</DialogTitle>
<DialogDescription>{titleReady ? "Draft bootstrap-only workspace definitions locally. Existing published descriptors stay read-only." : ""}</DialogDescription>
</DialogHeader>
<button type="button" aria-label="Close workspace management" onClick={onClose} className="absolute right-3 top-3 grid size-7 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"><X className="size-4" /></button>
<div className="grid max-h-[calc(min(90vh,54rem)-6.75rem)] min-h-[32rem] grid-cols-[14rem_minmax(0,1fr)] overflow-hidden">
<nav aria-label="Workspaces" className="flex min-h-0 flex-col border-r border-border/70 bg-muted/30 p-3">
<Button size="sm" className="mb-3 w-full" onClick={createWorkspace}><Plus />New workspace</Button>
<label className="mb-2 inline-flex h-7 cursor-pointer items-center justify-center gap-1 rounded-md border border-input px-3 text-[0.8rem] font-semibold text-foreground shadow-xs hover:bg-muted has-[:disabled]:cursor-not-allowed has-[:disabled]:opacity-50"><Upload className="size-3.5" />Import bundle<input aria-label="Import workspace bundle" type="file" accept="application/zip,.zip" className="sr-only" disabled={transferring} onChange={(event) => { const file = event.currentTarget.files?.[0]; event.currentTarget.value = ""; void importBundle(file); }} /></label>
<Button size="sm" variant="outline" className="mb-3 w-full" disabled={transferring} onClick={() => { void pullLatest(); }}><GitPullRequest />Pull latest registry</Button>
<div className="min-h-0 flex-1 overflow-y-auto">
@@ -302,54 +255,53 @@ export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: ()
<span className="block truncate text-xs text-muted-foreground">{workspace.id}</span>
</button>
))}
{!workspacesQuery.isLoading && !workspacesQuery.isError && workspaces.length === 0 && <p className="p-2 text-xs text-muted-foreground">No published workspaces.</p>}
</div>
<div className="border-t border-border/70 pt-3 text-xs text-muted-foreground">
<p className="font-semibold text-foreground">Git status</p>
{statusQuery.isError ? <QueryError name="Workspace registry status failed" message="Could not load registry status." retryLabel="Retry registry status" onRetry={() => { void statusQuery.refetch(); }} /> : statusQuery.isLoading ? <p>Loading…</p> : status && <><p>{status.branch}</p>{status.head && <p className="font-mono">Commit {status.head.slice(0, 12)}</p>}<p>{status.degraded ? "Degraded" : "Current"} · ↑{status.ahead} ↓{status.behind}</p></>}
</div>
</nav>
<div className="min-w-0 overflow-y-auto px-5 py-5">
{selectedSummaryIncomplete ? (
<div className="rounded-md border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm">
<p className="font-semibold">Workspace summary unavailable</p>
<p className="mt-1">This workspace summary is incomplete. Refresh the registry or choose another workspace before creating sessions or editing drafts.</p>
</div>
) : detailQuery.isError && selectedId && !localDraft ? <QueryError name="Workspace details failed" message="Could not load workspace details." retryLabel="Retry workspace details" onRetry={() => { void detailQuery.refetch(); }} /> : !currentDraft && !detailQuery.isLoading && <div className="grid min-h-64 place-items-center text-center"><div><h3 className="font-heading font-semibold">Select a workspace</h3><p className="mt-1 text-sm text-muted-foreground">Review an existing definition or start a browser-only draft.</p></div></div>}
{!selectedSummaryIncomplete && !detailQuery.isError && (currentDraft || detailQuery.isLoading) && (
{notice && <p role="status" className="mb-4 flex items-center gap-2 rounded-md border border-border bg-muted/50 px-3 py-2 text-sm"><CheckCircle2 className="size-4 text-primary" />{notice}</p>}
{diagnostics.length > 0 && <div data-testid="workspace-diagnostics" aria-live="polite" className="mb-4 grid gap-1 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm">{diagnostics.map((diagnostic) => <p key={diagnostic} className="flex items-start gap-2"><AlertCircle className="mt-0.5 size-4 shrink-0 text-amber-700" />{diagnostic}</p>)}</div>}
{!selectedSummary && !workspacesQuery.isLoading && !workspacesQuery.isError && <div className="grid min-h-64 place-items-center text-center"><div><h3 className="font-heading font-semibold">Select a workspace</h3><p className="mt-1 text-sm text-muted-foreground">Review an existing definition or bootstrap a configuration-required slot.</p></div></div>}
{selectedSummary?.configurationState === "configuration_required" && activeBootstrapDraft && (
<>
{detailQuery.isLoading && !currentDraft ? <p className="text-sm text-muted-foreground">Loading workspace definition…</p> : currentDraft && <>
<div className="mb-5 border-b border-border/70 pb-4">
<p className="thot-label">Bootstrap workspace</p>
<h2 className="font-heading text-lg font-semibold">{selectedSummary.displayName}</h2>
<p className="font-mono text-xs text-muted-foreground">{selectedSummary.id}</p>
</div>
<WorkspaceEditor
mode={{ kind: "bootstrap", catalog: selectedSummary, draft: activeBootstrapDraft }}
onSaveDraft={saveDraft}
onRequestCreate={publishRequest ? undefined : requestCreate}
/>
</>
)}
{selectedSummary?.configurationState === "ready" && (
detailQuery.isError ? <QueryError name="Workspace details failed" message="Could not load workspace details." retryLabel="Retry workspace details" onRetry={() => { void detailQuery.refetch(); }} /> : detailQuery.isLoading || !record ? <p className="text-sm text-muted-foreground">Loading workspace definition…</p> : (
<>
<div className="mb-5 flex flex-wrap items-start justify-between gap-3 border-b border-border/70 pb-4">
<div>
<p className="thot-label">Workspace definition</p>
<h2 className="font-heading text-lg font-semibold">{currentDraft.workspace.workspace.name}</h2>
<p className="font-mono text-xs text-muted-foreground">{currentDraft.workspaceId}</p>
<h2 className="font-heading text-lg font-semibold">{record.workspace.workspace.name}</h2>
<p className="font-mono text-xs text-muted-foreground">{record.workspace.workspace.id}</p>
</div>
<div className="flex flex-wrap gap-2">
<Button size="sm" variant="outline" disabled={!record || transferring} onClick={() => { void downloadBundle(); }}><Download />Export workspace bundle</Button>
<Button size="sm" variant="outline" onClick={duplicateWorkspace}><Copy />Duplicate workspace</Button>
<Button size="sm" variant="outline" onClick={validateCurrent}><ClipboardCheck />Validate workspace</Button>
<Button size="sm" variant="outline" disabled={!canTest} onClick={testCurrent}><FlaskConical />Test on this installation</Button>
<Button size="sm" variant="destructive" disabled={!canTest || !currentDraft.baseBlob} onClick={stageDeletion}><Trash2 />Delete workspace</Button>
<Button size="sm" variant="outline" disabled={transferring} onClick={() => { void downloadBundle(); }}><Download />Export workspace bundle</Button>
<Button size="sm" variant="outline" onClick={() => { void validateSelectedWorkspace(); }}><ClipboardCheck />Validate workspace</Button>
<Button size="sm" variant="outline" onClick={() => { void testSelectedWorkspace(); }}><FlaskConical />Test on this installation</Button>
</div>
</div>
{notice && <p role="status" className="mb-4 flex items-center gap-2 rounded-md border border-border bg-muted/50 px-3 py-2 text-sm"><CheckCircle2 className="size-4 text-primary" />{notice}</p>}
{diagnostics.length > 0 && <div data-testid="workspace-diagnostics" aria-live="polite" className="mb-4 grid gap-1 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm">{diagnostics.map((diagnostic) => <p key={diagnostic} className="flex items-start gap-2"><AlertCircle className="mt-0.5 size-4 shrink-0 text-amber-700" />{diagnostic}</p>)}</div>}
{activeDeletionDraft && <div className="mb-4 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm"><p className="font-semibold">Deletion draft</p><p>The published workspace is unchanged. Validation and a separate confirmation are required before this deletion is published.</p><div className="mt-2 flex gap-2"><Button size="xs" variant="ghost" onClick={() => { workspaceDeletionDrafts.discard(activeDeletionDraft.id); setDeletionDraft(undefined); setNotice(undefined); }}>Discard deletion draft</Button><Button size="xs" variant="destructive" onClick={requestDeletionPublish}>Publish deletion</Button></div></div>}
<WorkspaceEditor draft={currentDraft} idLocked={Boolean(currentDraft.baseBlob && selectedSummary?.id === currentDraft.workspaceId)} onSaveDraft={saveDraft} onPublish={async (request) => { requestPublish(request); }} />
<section className="mt-6 border-t border-border/70 pt-5" aria-label="Git status and history">
<h3 className="font-heading text-sm font-semibold">Git status &amp; history</h3>
<p className="mt-2 text-sm text-muted-foreground">{status?.degraded ? "Using the last valid local snapshot." : "Registry checkout is current."}</p>
{record && <p className="mt-1 font-mono text-xs text-muted-foreground">Revision {record.revision.commit.slice(0, 12)}</p>}
</section>
</>}
</>
<WorkspaceEditor mode={{ kind: "read_only", catalog: selectedSummary, record: record as WorkspaceRecord }} />
</>
)
)}
</div>
</div>
</DialogContent>
{publishRequest && <WorkspacePublishDialog open={Boolean(publishRequest)} request={publishRequest} onOpenChange={(nextOpen) => { if (!nextOpen) setPublishRequest(undefined); }} onPublished={published} onResolved={saveResolvedDraft} onPull={pullLatest} onReload={reloadWorkspace} />}
{publishRequest && <WorkspacePublishDialog open request={publishRequest} onOpenChange={(nextOpen) => { if (!nextOpen) setPublishRequest(undefined); }} onPublished={published} />}
</Dialog>
);
}
@@ -2,150 +2,65 @@ import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw";
import { beforeEach, expect, test, vi } from "vitest";
import type { CanonicalWorkspace, PublishWorkspaceRequest, WorkspaceConflict } from "../api/workspaces";
import { canonicalWorkspaceFixture, workspaceRevisionFixture } from "../test/workspace-fixtures";
import { server } from "../test/msw";
import { WorkspacePublishDialog } from "./WorkspacePublishDialog";
const workspace: CanonicalWorkspace = {
workspace: { schema_version: 3, id: "psd-clinical", name: "PSD Clinical", language: "en" },
dwh: { engine: "postgres", database: "clinical", schema: "datawarehouse", supported_transports: ["postgres_direct"] },
semantic_index: {
vector_store: { engine: "qdrant", collection: "clinical", dimensions: 1024, distance: "cosine" },
embedding: { provider: "ollama_internal", model: "qwen3-embedding:0.6b", dimensions: 1024 },
const workspace = {
...canonicalWorkspaceFixture("bootstrap-slot"),
workspace: {
...canonicalWorkspaceFixture("bootstrap-slot").workspace,
name: "Bootstrap slot",
description: "Needs configuration",
},
llm_policy: { allowed: ["zai/glm-5.2"] },
};
const request: PublishWorkspaceRequest = {
action: "update", workspace, baseCommit: "a".repeat(40), baseBlob: "b".repeat(40),
};
const conflict: WorkspaceConflict = {
code: "workspace_conflict",
fields: ["semantic_index.vector_store.collection"],
expected: { commit: "a".repeat(40), blob: "b".repeat(40) },
actual: { commit: "c".repeat(40), blob: "d".repeat(40) },
base: workspace,
local: { ...workspace, semantic_index: { ...workspace.semantic_index, vector_store: { ...workspace.semantic_index.vector_store, collection: "local_collection" } } },
remote: { ...workspace, semantic_index: { ...workspace.semantic_index, vector_store: { ...workspace.semantic_index.vector_store, collection: "remote_collection" } } },
};
const diagnosticsBranchConflict: WorkspaceConflict = {
...conflict,
fields: ["diagnostics.dwh_rest"],
base: workspace,
remote: workspace,
local: {
...workspace,
dwh: { ...workspace.dwh, supported_transports: ["postgres_direct", "rest_api"] },
diagnostics: { dwh_rest: { method: "GET", path: "/health", auth: "none", response: { database: "database", schema: "schema" } } },
},
const request = {
action: "create" as const,
workspace,
baseCommit: "a".repeat(40),
};
beforeEach(() => {
server.use(http.post("/api/workspaces/validate", () => HttpResponse.json({ workspace, contract: {} })));
});
test("validates a draft and requires a separate confirmation before publishing", async () => {
test("validates a bootstrap draft and requires a separate confirmation before creating it", async () => {
const user = userEvent.setup();
const published = vi.fn();
let publishCalls = 0;
server.use(http.post("/api/workspaces/publish", () => {
publishCalls += 1;
return HttpResponse.json({ revision: { id: "psd-clinical", commit: "c".repeat(40), blob: "d".repeat(40), snapshotPath: "/safe" } });
return HttpResponse.json({ revision: workspaceRevisionFixture("bootstrap-slot") });
}));
render(<WorkspacePublishDialog open request={request} onOpenChange={vi.fn()} onPublished={published} onResolved={vi.fn()} onPull={vi.fn()} onReload={vi.fn()} />);
expect(screen.getByRole("button", { name: "Publish" })).toBeDisabled();
render(<WorkspacePublishDialog open request={request} onOpenChange={vi.fn()} onPublished={published} />);
expect(screen.getByRole("button", { name: "Create workspace" })).toBeDisabled();
await user.click(screen.getByRole("button", { name: "Validate draft" }));
expect(await screen.findByText("Workspace definition is valid." )).toBeVisible();
await user.click(screen.getByRole("button", { name: "Publish" }));
expect(screen.getByRole("heading", { name: "Confirm publication" })).toBeVisible();
expect(await screen.findByText("Workspace definition is valid.")).toBeVisible();
await user.click(screen.getByRole("button", { name: "Create workspace" }));
expect(screen.getByRole("heading", { name: "Confirm workspace creation" })).toBeVisible();
expect(publishCalls).toBe(0);
await user.click(screen.getByRole("button", { name: "Confirm publish" }));
await user.click(screen.getByRole("button", { name: "Confirm create" }));
await waitFor(() => expect(published).toHaveBeenCalledTimes(1));
await waitFor(() => expect(published).toHaveBeenCalledWith(workspaceRevisionFixture("bootstrap-slot")));
expect(publishCalls).toBe(1);
});
test("shows a field-level conflict and never overwrites the remote workspace", async () => {
const user = userEvent.setup();
let published = false;
server.use(http.post("/api/workspaces/publish", () => {
published = true;
return HttpResponse.json({ ...conflict, message: "Workspace changed in the registry." }, { status: 409 });
}));
render(<WorkspacePublishDialog open request={request} onOpenChange={vi.fn()} onPublished={vi.fn()} onResolved={vi.fn()} onPull={vi.fn()} onReload={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Validate draft" }));
await user.click(await screen.findByRole("button", { name: "Publish" }));
await user.click(screen.getByRole("button", { name: "Confirm publish" }));
expect(await screen.findByText("semantic_index.vector_store.collection")).toBeVisible();
expect(screen.getByText("local_collection")).toBeVisible();
expect(screen.getByText("remote_collection")).toBeVisible();
expect(screen.getByRole("radio", { name: "Use your draft for semantic_index.vector_store.collection" })).toBeVisible();
expect(screen.getByRole("radio", { name: "Use registry value for semantic_index.vector_store.collection" })).toBeVisible();
expect(screen.getByRole("button", { name: "Save revised draft" })).toBeDisabled();
expect(published).toBe(true);
});
test("saves explicit local choices as a rebased draft and does not republish it", async () => {
const user = userEvent.setup();
const saved = vi.fn();
let publishCalls = 0;
server.use(http.post("/api/workspaces/publish", () => {
publishCalls += 1;
return HttpResponse.json({ ...conflict, message: "Workspace changed in the registry." }, { status: 409 });
}));
render(<WorkspacePublishDialog open request={request} onOpenChange={vi.fn()} onPublished={vi.fn()} onResolved={saved} onPull={vi.fn()} onReload={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Validate draft" }));
await user.click(await screen.findByRole("button", { name: "Publish" }));
await user.click(screen.getByRole("button", { name: "Confirm publish" }));
await user.click(await screen.findByRole("radio", { name: "Use your draft for semantic_index.vector_store.collection" }));
await user.click(screen.getByRole("button", { name: "Save revised draft" }));
expect(saved).toHaveBeenCalledWith(expect.objectContaining({
baseCommit: "c".repeat(40), baseBlob: "d".repeat(40),
workspace: expect.objectContaining({ semantic_index: expect.objectContaining({ vector_store: expect.objectContaining({ collection: "local_collection" }) }) }),
}));
expect(publishCalls).toBe(1);
});
test("rebases a selected optional diagnostics branch into the revised draft", async () => {
const user = userEvent.setup();
const saved = vi.fn();
server.use(http.post("/api/workspaces/publish", () => HttpResponse.json({
...diagnosticsBranchConflict, message: "Workspace changed in the registry.",
}, { status: 409 })));
render(<WorkspacePublishDialog open request={request} onOpenChange={vi.fn()} onPublished={vi.fn()} onResolved={saved} onPull={vi.fn()} onReload={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Validate draft" }));
await user.click(await screen.findByRole("button", { name: "Publish" }));
await user.click(screen.getByRole("button", { name: "Confirm publish" }));
await user.click(await screen.findByRole("radio", { name: "Use your draft for diagnostics.dwh_rest" }));
await user.click(screen.getByRole("button", { name: "Save revised draft" }));
expect(saved).toHaveBeenCalledWith(expect.objectContaining({
baseCommit: "c".repeat(40), baseBlob: "d".repeat(40),
workspace: expect.objectContaining({ diagnostics: diagnosticsBranchConflict.local.diagnostics }),
}));
});
test("keeps a conflict open and redacts a failed registry pull", async () => {
test("surfaces a safe curator-owned refusal without showing conflict resolution UI", async () => {
const user = userEvent.setup();
server.use(http.post("/api/workspaces/publish", () => HttpResponse.json({
...conflict, message: "Workspace changed in the registry.",
code: "workspace_curator_owned",
message: "Existing descriptors are curator-owned.",
}, { status: 409 })));
render(<WorkspacePublishDialog open request={request} onOpenChange={vi.fn()} onPublished={vi.fn()} onResolved={vi.fn()} onPull={vi.fn().mockRejectedValue(new Error("token=secret"))} onReload={vi.fn()} />);
render(<WorkspacePublishDialog open request={request} onOpenChange={vi.fn()} onPublished={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Validate draft" }));
await user.click(await screen.findByRole("button", { name: "Publish" }));
await user.click(screen.getByRole("button", { name: "Confirm publish" }));
await user.click(await screen.findByRole("button", { name: "Pull latest registry" }));
await user.click(await screen.findByRole("button", { name: "Create workspace" }));
await user.click(screen.getByRole("button", { name: "Confirm create" }));
expect(await screen.findByText("Registry pull could not be completed. Try again or reload the workspace.")).toBeVisible();
expect(screen.queryByText(/token=secret/)).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Reload workspace" })).toBeVisible();
expect(await screen.findByText("workspace_curator_owned: Existing descriptors are curator-owned.")).toBeVisible();
expect(screen.queryByText(/save revised draft|use your draft|use registry value/i)).not.toBeInTheDocument();
});
+32 -156
View File
@@ -1,15 +1,11 @@
import { useEffect, useState } from "react";
import {
asWorkspaceApiError,
asWorkspaceConflict,
publishWorkspace,
validateWorkspace,
type CanonicalWorkspace,
type PublishWorkspaceRequest,
type WorkspaceConflict,
type WorkspaceRevision,
} from "../api/workspaces";
import type { WorkspaceDraft } from "../workspaces/drafts";
import { Button } from "../components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../components/ui/dialog";
@@ -18,146 +14,31 @@ export interface WorkspacePublishDialogProps {
request: PublishWorkspaceRequest;
onOpenChange: (open: boolean) => void;
onPublished: (revision: WorkspaceRevision | undefined) => void;
onResolved: (draft: WorkspaceDraft) => void;
onPull: () => Promise<void> | void;
onReload: () => void;
}
function valueAt(workspace: CanonicalWorkspace, path: string): string {
const value = path.split(".").reduce<unknown>((current, key) => (
current && typeof current === "object" ? (current as Record<string, unknown>)[key] : undefined
), workspace);
return value === undefined ? "—" : typeof value === "string" || typeof value === "number" || typeof value === "boolean"
? String(value)
: JSON.stringify(value);
}
function valueAtPath(workspace: CanonicalWorkspace, path: string): unknown {
return path.split(".").reduce<unknown>((current, key) => (
current && typeof current === "object" ? (current as Record<string, unknown>)[key] : undefined
), workspace);
}
function replaceAtPath(value: Record<string, unknown>, path: string[], replacement: unknown): Record<string, unknown> {
const [key, ...remaining] = path;
const copy = { ...value };
if (remaining.length === 0) {
if (replacement === undefined) delete copy[key];
else copy[key] = replacement;
return copy;
}
const child = copy[key];
copy[key] = replaceAtPath(child && typeof child === "object" && !Array.isArray(child) ? child as Record<string, unknown> : {}, remaining, replacement);
return copy;
}
function requestWithWorkspace(request: PublishWorkspaceRequest, workspace: CanonicalWorkspace): PublishWorkspaceRequest {
return request.action === "delete" ? request : { ...request, workspace };
}
function RevisionSummary({ request }: { request: PublishWorkspaceRequest }) {
const label = request.action === "create" ? "New workspace" : request.action === "delete" ? "Deletion" : "Workspace update";
return <p className="rounded-md border border-border/70 bg-muted/40 px-3 py-2 font-mono text-xs text-muted-foreground">{label} · base {request.baseCommit.slice(0, 12)}</p>;
return <p className="rounded-md border border-border/70 bg-muted/40 px-3 py-2 font-mono text-xs text-muted-foreground">New workspace · base {request.baseCommit.slice(0, 12)}</p>;
}
function ConflictReview({ conflict, onPull, onReload, onResolved }: {
conflict: WorkspaceConflict;
onPull: () => Promise<void> | void;
onReload: () => void;
onResolved: (draft: WorkspaceDraft) => void;
}) {
const [pulling, setPulling] = useState(false);
const [pulled, setPulled] = useState(false);
const [pullError, setPullError] = useState(false);
const [choices, setChoices] = useState<Record<string, "local" | "remote">>({});
const canSave = Boolean(conflict.actual.blob) && conflict.fields.every((field) => choices[field]);
async function pull() {
setPulling(true);
setPullError(false);
try {
await onPull();
setPulled(true);
} catch {
setPullError(true);
} finally {
setPulling(false);
}
}
function saveRevisedDraft() {
if (!conflict.actual.blob || !canSave) return;
const workspace = conflict.fields.reduce<CanonicalWorkspace>((current, field) => (
choices[field] === "local"
? replaceAtPath(current as unknown as Record<string, unknown>, field.split("."), valueAtPath(conflict.local, field)) as unknown as CanonicalWorkspace
: current
), conflict.remote);
onResolved({
workspaceId: workspace.workspace.id,
baseCommit: conflict.actual.commit,
baseBlob: conflict.actual.blob,
workspace,
updatedAt: new Date().toISOString(),
});
}
return <div className="grid gap-4">
<div className="rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm">
<p className="font-semibold">The registry changed before publication.</p>
<p className="mt-1 text-muted-foreground">Choose a value for every changed field to save a revised browser draft against registry revision {conflict.actual.commit.slice(0, 12)}. Saving never publishes it.</p>
</div>
<div className="grid gap-3">
{conflict.fields.map((field) => <section key={field} className="overflow-hidden rounded-md border border-border/70" aria-label={`Conflict for ${field}`}>
<h3 className="border-b border-border/70 bg-muted/40 px-3 py-2 font-mono text-xs font-semibold">{field}</h3>
<dl className="grid divide-y divide-border/70 text-sm sm:grid-cols-3 sm:divide-x sm:divide-y-0">
<div className="min-w-0 px-3 py-2"><dt className="text-xs text-muted-foreground">Base</dt><dd className="mt-1 break-words font-mono text-xs">{valueAt(conflict.base, field)}</dd></div>
<div className="min-w-0 px-3 py-2"><dt className="text-xs text-muted-foreground">Your draft</dt><dd className="mt-1 break-words font-mono text-xs">{valueAt(conflict.local, field)}</dd></div>
<div className="min-w-0 px-3 py-2"><dt className="text-xs text-muted-foreground">Registry</dt><dd className="mt-1 break-words font-mono text-xs">{valueAt(conflict.remote, field)}</dd></div>
</dl>
<fieldset className="flex flex-wrap gap-3 border-t border-border/70 px-3 py-2 text-xs">
<legend className="sr-only">Resolve {field}</legend>
<label className="flex items-center gap-1.5"><input type="radio" name={`resolution-${field}`} aria-label={`Use your draft for ${field}`} checked={choices[field] === "local"} onChange={() => setChoices((current) => ({ ...current, [field]: "local" }))} />Use your draft</label>
<label className="flex items-center gap-1.5"><input type="radio" name={`resolution-${field}`} aria-label={`Use registry value for ${field}`} checked={choices[field] === "remote"} onChange={() => setChoices((current) => ({ ...current, [field]: "remote" }))} />Use registry value</label>
</fieldset>
</section>)}
</div>
{pulled && <p role="status" className="text-sm text-muted-foreground">Latest registry state pulled. Reload the workspace before editing or publishing again.</p>}
{pullError && <p role="alert" className="text-sm text-destructive">Registry pull could not be completed. Try again or reload the workspace.</p>}
<div className="flex flex-wrap justify-end gap-2">
<Button onClick={saveRevisedDraft} disabled={!canSave}>Save revised draft</Button>
<Button variant="outline" onClick={() => { void pull(); }} disabled={pulling}>{pulling ? "Pulling…" : "Pull latest registry"}</Button>
<Button onClick={onReload}>Reload workspace</Button>
</div>
</div>;
}
export function WorkspacePublishDialog({ open, request, onOpenChange, onPublished, onResolved, onPull, onReload }: WorkspacePublishDialogProps) {
export function WorkspacePublishDialog({ open, request, onOpenChange, onPublished }: WorkspacePublishDialogProps) {
const [validatedRequest, setValidatedRequest] = useState<PublishWorkspaceRequest>();
const [confirmationOpen, setConfirmationOpen] = useState(false);
const [conflict, setConflict] = useState<WorkspaceConflict>();
const [confirming, setConfirming] = useState(false);
const [message, setMessage] = useState<string>();
const [publishing, setPublishing] = useState(false);
useEffect(() => {
if (!open) return;
setValidatedRequest(undefined);
setConfirmationOpen(false);
setConflict(undefined);
setConfirming(false);
setMessage(undefined);
setPublishing(false);
}, [open, request]);
async function validate() {
async function validateDraft() {
setMessage(undefined);
setConflict(undefined);
if (request.action === "delete") {
setValidatedRequest(request);
setMessage("Deletion is pinned to the published revision.");
return;
}
try {
const result = await validateWorkspace(request.workspace);
setValidatedRequest(requestWithWorkspace(request, result.workspace));
setValidatedRequest({ ...request, workspace: result.workspace });
setMessage("Workspace definition is valid.");
} catch (error) {
const safe = asWorkspaceApiError(error);
@@ -165,7 +46,7 @@ export function WorkspacePublishDialog({ open, request, onOpenChange, onPublishe
}
}
async function publish() {
async function createWorkspace() {
if (!validatedRequest) return;
setPublishing(true);
setMessage(undefined);
@@ -174,43 +55,38 @@ export function WorkspacePublishDialog({ open, request, onOpenChange, onPublishe
onPublished(result?.revision);
onOpenChange(false);
} catch (error) {
const detectedConflict = asWorkspaceConflict(error);
if (detectedConflict) {
setConflict(detectedConflict);
setConfirmationOpen(false);
} else {
const safe = asWorkspaceApiError(error);
setMessage(safe ? `${safe.code}: ${safe.message}` : "workspace_invalid: Publication could not be completed");
}
const safe = asWorkspaceApiError(error);
setMessage(safe ? `${safe.code}: ${safe.message}` : "workspace_invalid: Publication could not be completed");
setConfirming(false);
} finally {
setPublishing(false);
}
}
return <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent showCloseButton={false} className="max-w-[min(94vw,46rem)] p-0">
<DialogHeader className="border-b border-border/70 px-5 pb-4 pt-5 pr-12">
<DialogTitle>{conflict ? "Publication conflict" : "Publish workspace"}</DialogTitle>
<DialogDescription>{conflict ? "Choose each local or registry value, then save a revised draft for normal validation and confirmation." : "Validation and an explicit confirmation are required before this shared definition is published."}</DialogDescription>
</DialogHeader>
<div className="grid gap-4 px-5 py-5">
{conflict ? <ConflictReview conflict={conflict} onPull={onPull} onReload={onReload} onResolved={onResolved} /> : <>
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent showCloseButton={false} className="max-w-[min(94vw,46rem)] p-0">
<DialogHeader className="border-b border-border/70 px-5 pb-4 pt-5 pr-12">
<DialogTitle>{confirming ? "Confirm workspace creation" : "Create workspace"}</DialogTitle>
<DialogDescription>{confirming ? "This creates the validated workspace definition in the shared Git registry." : "Validation and an explicit confirmation are required before this shared definition is created."}</DialogDescription>
</DialogHeader>
<div className="grid gap-4 px-5 py-5">
<RevisionSummary request={validatedRequest ?? request} />
{message && <p role="status" className="rounded-md border border-border/70 bg-muted/40 px-3 py-2 text-sm">{message}</p>}
<div className="flex flex-wrap justify-end gap-2">
<Button variant="outline" onClick={() => { void validate(); }}>Validate draft</Button>
<Button disabled={!validatedRequest} onClick={() => setConfirmationOpen(true)}>Publish</Button>
</div>
</>}
</div>
<button type="button" aria-label="Close publish workspace" onClick={() => onOpenChange(false)} className="absolute right-3 top-3 grid size-7 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground">×</button>
</DialogContent>
<Dialog open={confirmationOpen} onOpenChange={setConfirmationOpen}>
<DialogContent showCloseButton={false} className="max-w-md">
<DialogHeader><DialogTitle>Confirm publication</DialogTitle><DialogDescription>This publishes the validated workspace definition to the shared Git registry.</DialogDescription></DialogHeader>
<RevisionSummary request={validatedRequest ?? request} />
<DialogFooter><Button variant="outline" onClick={() => setConfirmationOpen(false)}>Cancel</Button><Button onClick={() => { void publish(); }} disabled={publishing}>{publishing ? "Publishing…" : "Confirm publish"}</Button></DialogFooter>
{confirming ? (
<DialogFooter>
<Button variant="outline" onClick={() => setConfirming(false)}>Cancel</Button>
<Button onClick={() => { void createWorkspace(); }} disabled={publishing}>{publishing ? "Creating…" : "Confirm create"}</Button>
</DialogFooter>
) : (
<div className="flex flex-wrap justify-end gap-2">
<Button variant="outline" onClick={() => { void validateDraft(); }}>Validate draft</Button>
<Button disabled={!validatedRequest} onClick={() => setConfirming(true)}>Create workspace</Button>
</div>
)}
</div>
<button type="button" aria-label="Close publish workspace" onClick={() => onOpenChange(false)} className="absolute right-3 top-3 grid size-7 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground">×</button>
</DialogContent>
</Dialog>
</Dialog>;
);
}