feat: publish and synchronize workspace drafts

This commit is contained in:
2026-08-04 06:47:10 +02:00
parent 6b40fa0cc5
commit b75b3af28e
9 changed files with 545 additions and 16 deletions
+22 -1
View File
@@ -1,7 +1,17 @@
import { expect, test } from "vitest";
import { http, HttpResponse } from "msw";
import { server } from "../test/msw";
import { importWorkspace } from "./workspaces";
import { asWorkspaceConflict, importWorkspace, publishWorkspace, type CanonicalWorkspace } from "./workspaces";
const workspace: CanonicalWorkspace = {
workspace: { schema_version: 2, id: "psd-clinical", name: "PSD Clinical", language: "en" },
dwh: { engine: "postgres", database: "clinical", schema: "datawarehouse", supported_transports: ["postgres_direct"] },
semantic_index: {
vector_store: { engine: "pgvector", database: "vectors", schema: "public", collection: "clinical", dimensions: 768, distance: "cosine", supported_transports: ["pgvector_direct"] },
embedding: { provider: "ollama_compatible", model: "nomic-embed-text", dimensions: 768 },
},
llm_policy: { allowed: ["zai/glm-5.2"] },
};
test("uploads a workspace bundle without JSON content type", async () => {
let contentType: string | null = null;
@@ -17,3 +27,14 @@ test("uploads a workspace bundle without JSON content type", async () => {
// that header untouched; a real browser adds multipart/form-data + boundary.
expect(contentType ?? "").not.toMatch(/application\/json/i);
});
test("rejects a conflict payload that attempts to surface a secret field", async () => {
server.use(http.post("http://localhost:8787/workspaces/publish", () => HttpResponse.json({
code: "workspace_conflict", message: "Workspace changed in the registry.", fields: ["dwh.password"],
base: { ...workspace, dwh: { ...workspace.dwh, password: "secret" } }, local: workspace, remote: workspace,
}, { status: 409 })));
const error = await publishWorkspace({ action: "update", workspace, baseCommit: "a".repeat(40), baseBlob: "b".repeat(40) }).catch((cause: unknown) => cause);
expect(asWorkspaceConflict(error)).toBeUndefined();
});
+18 -4
View File
@@ -1,4 +1,5 @@
import { ApiError, apiFetch, apiFetchBlob } from "./client";
import { sanitizeCanonicalWorkspace } from "../workspaces/drafts";
export type WorkspaceErrorCode =
| "workspace_invalid" | "binding_missing" | "workspace_not_activatable"
@@ -126,6 +127,16 @@ export interface WorkspaceApiError {
fields?: string[];
}
const conflictFields = new Set([
"workspace.name", "workspace.description", "workspace.language",
"dwh.database", "dwh.schema", "dwh.port", "dwh.timeout_ms", "dwh.supported_transports",
"semantic_index.vector_store.database", "semantic_index.vector_store.schema", "semantic_index.vector_store.collection",
"semantic_index.vector_store.dimensions", "semantic_index.vector_store.distance", "semantic_index.vector_store.port",
"semantic_index.vector_store.timeout_ms", "semantic_index.vector_store.supported_transports",
"semantic_index.embedding.provider", "semantic_index.embedding.model", "semantic_index.embedding.dimensions",
"semantic_index.embedding.timeout_ms", "semantic_index.vector_writer", "llm_policy.default", "llm_policy.allowed",
]);
const workspaceErrorCodes = new Set<WorkspaceErrorCode>([
"workspace_invalid", "binding_missing", "workspace_not_activatable", "workspace_stale",
"workspace_conflict", "git_unavailable", "git_auth_failed", "git_non_fast_forward",
@@ -159,13 +170,16 @@ export function asWorkspaceConflict(error: unknown): WorkspaceConflict | undefin
if (safe?.code !== "workspace_conflict") return undefined;
const payload = object((error as ApiError).payload);
const fields = safe.fields;
if (!payload || !fields || !object(payload.base) || !object(payload.local) || !object(payload.remote)) return undefined;
const base = payload && sanitizeCanonicalWorkspace(payload.base);
const local = payload && sanitizeCanonicalWorkspace(payload.local);
const remote = payload && sanitizeCanonicalWorkspace(payload.remote);
if (!payload || !fields || !fields.every((field) => conflictFields.has(field)) || !base || !local || !remote) return undefined;
return {
code: "workspace_conflict",
fields,
base: payload.base as CanonicalWorkspace,
local: payload.local as CanonicalWorkspace,
remote: payload.remote as CanonicalWorkspace,
base,
local,
remote,
};
}
+15 -3
View File
@@ -113,7 +113,7 @@ function Section({ title, children }: { title: string; children: React.ReactNode
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: _onPublish, idLocked = Boolean(draft?.baseBlob) }: WorkspaceEditorProps) {
export function WorkspaceEditor({ draft, onSaveDraft, onPublish, idLocked = Boolean(draft?.baseBlob) }: WorkspaceEditorProps) {
const [workspace, setWorkspace] = useState<CanonicalWorkspace>(draft?.workspace ?? emptyWorkspace());
const [errors, setErrors] = useState<FieldErrors>({});
const allowedModels = useMemo(() => workspace.llm_policy.allowed.join(", "), [workspace.llm_policy.allowed]);
@@ -144,6 +144,17 @@ export function WorkspaceEditor({ draft, onSaveDraft, onPublish: _onPublish, idL
});
}
function publishDraft() {
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);
}
return (
<form className="grid gap-6" onSubmit={(event) => { event.preventDefault(); saveDraft(); }} noValidate>
<Section title="General">
@@ -228,8 +239,9 @@ export function WorkspaceEditor({ draft, onSaveDraft, onPublish: _onPublish, idL
<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>
</Section>
<div className="flex justify-end border-t border-border/70 pt-4">
<Button type="submit">Save draft</Button>
<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>
</form>
);
+53 -1
View File
@@ -2,7 +2,7 @@ import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { http, HttpResponse } from "msw";
import { beforeEach, expect, test } from "vitest";
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { server } from "../test/msw";
import { WorkspaceManager } from "./WorkspaceManager";
@@ -38,6 +38,8 @@ beforeEach(() => {
);
});
afterEach(() => vi.unstubAllGlobals());
test("lists registry workspaces and saves a new workspace only as a browser draft", async () => {
const user = userEvent.setup();
renderManager();
@@ -53,6 +55,56 @@ test("lists registry workspaces and saves a new workspace only as a browser draf
expect(localStorage.getItem("thothii.workspace-registry.v1.draft.trial-registry")).not.toBeNull();
});
test("imports a bundle as a local draft and never publishes it automatically", async () => {
const user = userEvent.setup();
const publishSpy = vi.fn();
server.use(
http.post("http://localhost:8787/workspaces/import", () => HttpResponse.json({ draft: { workspace, contract: {} } })),
http.post("http://localhost:8787/workspaces/publish", () => {
publishSpy();
return HttpResponse.json({});
}),
);
renderManager();
await user.upload(screen.getByLabelText("Import workspace bundle"), new File(["bundle"], "workspace.zip", { type: "application/zip" }));
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();
});
test("pulls and exports only when the manager explicitly requests each action", async () => {
const user = userEvent.setup();
const publishSpy = vi.fn();
const createObjectURL = vi.fn(() => "blob:workspace-bundle");
const revokeObjectURL = vi.fn();
class DownloadUrl extends URL {
static createObjectURL = createObjectURL;
static revokeObjectURL = revokeObjectURL;
}
vi.stubGlobal("URL", DownloadUrl);
vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => undefined);
server.use(
http.post("http://localhost:8787/workspace-registry/pull", () => HttpResponse.json({ branch: "main", head: "c".repeat(40), ahead: 0, behind: 0, degraded: false })),
http.get("http://localhost:8787/workspaces/psd-clinical/export", () => new HttpResponse(new Blob(["bundle"], { type: "application/zip" }))),
http.post("http://localhost:8787/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;
+131 -5
View File
@@ -1,14 +1,16 @@
import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { AlertCircle, CheckCircle2, ClipboardCheck, FlaskConical, Plus, Trash2, Copy, X } from "lucide-react";
import { AlertCircle, CheckCircle2, ClipboardCheck, Download, FlaskConical, GitPullRequest, Plus, Trash2, Copy, Upload, X } from "lucide-react";
import {
asWorkspaceApiError, getWorkspace, getWorkspaceRegistryStatus, listWorkspaces, testWorkspace,
validateWorkspace, type CanonicalWorkspace, type PublishWorkspaceRequest, type WorkspaceRecord,
asWorkspaceApiError, exportWorkspace, getWorkspace, getWorkspaceRegistryStatus, importWorkspace,
listWorkspaces, pullWorkspaceRegistry, testWorkspace, validateWorkspace, type CanonicalWorkspace,
type PublishWorkspaceRequest, type WorkspaceRecord, type WorkspaceRevision,
} from "../api/workspaces";
import { workspaceDeletionDrafts, workspaceDrafts, type WorkspaceDeletionDraft, type WorkspaceDraft } from "../workspaces/drafts";
import { Button } from "../components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "../components/ui/dialog";
import { WorkspaceEditor } from "./WorkspaceEditor";
import { WorkspacePublishDialog } from "./WorkspacePublishDialog";
const EMPTY_COMMIT = "0".repeat(40);
@@ -55,6 +57,8 @@ export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: ()
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 detailQuery = useQuery({
@@ -79,6 +83,7 @@ export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: ()
setDeletionDraft(undefined);
setNotice(undefined);
setDiagnostics([]);
setPublishRequest(undefined);
}
function createWorkspace() {
@@ -88,6 +93,7 @@ export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: ()
setDeletionDraft(undefined);
setNotice("New draft. Choose its immutable workspace ID before saving.");
setDiagnostics([]);
setPublishRequest(undefined);
}
function duplicateWorkspace() {
@@ -103,6 +109,7 @@ export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: ()
setLocalDraft(duplicate);
setDeletionDraft(undefined);
setNotice("Duplicate draft. Give it a new immutable workspace ID before publishing.");
setPublishRequest(undefined);
}
function saveDraft(draft: WorkspaceDraft) {
@@ -112,6 +119,121 @@ export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: ()
setNotice("Draft saved in this browser.");
}
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);
}
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([]);
try {
await pullWorkspaceRegistry();
await Promise.all([statusQuery.refetch(), workspacesQuery.refetch()]);
setNotice("Registry updated. Reload a workspace to review its latest revision.");
} 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);
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.");
} catch (error) {
const safe = asWorkspaceApiError(error);
setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "workspace_invalid: Workspace bundle could not be imported"]);
} finally {
setTransferring(false);
}
}
async function downloadBundle() {
if (!record) return;
setTransferring(true);
setNotice(undefined);
setDiagnostics([]);
try {
const bundle = await exportWorkspace(record.workspace.workspace.id);
const url = URL.createObjectURL(bundle);
const link = document.createElement("a");
link.href = url;
link.download = `${record.workspace.workspace.id}.zip`;
link.click();
URL.revokeObjectURL(url);
setNotice("Workspace bundle downloaded.");
} catch (error) {
const safe = asWorkspaceApiError(error);
setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "workspace_invalid: Workspace bundle could not be exported"]);
} finally {
setTransferring(false);
}
}
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);
}
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()]);
}
async function validateCurrent() {
if (!currentDraft) return;
setNotice(undefined);
@@ -160,6 +282,8 @@ export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: ()
<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">
{workspacesQuery.isLoading ? <p className="p-2 text-xs text-muted-foreground">Loading workspaces…</p> : workspacesQuery.isError ? <QueryError name="Workspace list failed" message="Could not load workspaces." retryLabel="Retry workspace list" onRetry={() => { void workspacesQuery.refetch(); }} /> : workspaces.map((workspace) => (
<button key={workspace.id} type="button" aria-label={workspace.displayName} aria-current={selectedId === workspace.id ? "page" : undefined} onClick={() => selectWorkspace(workspace.id)} className="mb-1 w-full rounded-md px-2.5 py-2 text-left text-sm hover:bg-muted aria-[current=page]:bg-primary/10 aria-[current=page]:font-semibold">
@@ -187,6 +311,7 @@ export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: ()
<p className="font-mono text-xs text-muted-foreground">{currentDraft.workspaceId}</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>
@@ -195,8 +320,8 @@ export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: ()
</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. Publishing this staged deletion is a Task 10 action.</p><Button size="xs" variant="ghost" className="mt-2" onClick={() => { workspaceDeletionDrafts.discard(activeDeletionDraft.id); setDeletionDraft(undefined); setNotice(undefined); }}>Discard deletion draft</Button></div>}
<WorkspaceEditor draft={currentDraft} idLocked={Boolean(currentDraft.baseBlob && selectedSummary?.id === currentDraft.workspaceId)} onSaveDraft={saveDraft} onPublish={async () => undefined} />
{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>
@@ -208,6 +333,7 @@ export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: ()
</div>
</div>
</DialogContent>
{publishRequest && <WorkspacePublishDialog open={Boolean(publishRequest)} request={publishRequest} onOpenChange={(nextOpen) => { if (!nextOpen) setPublishRequest(undefined); }} onPublished={published} onPull={pullLatest} onReload={reloadWorkspace} />}
</Dialog>
);
}
@@ -0,0 +1,94 @@
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 { server } from "../test/msw";
import { WorkspacePublishDialog } from "./WorkspacePublishDialog";
const workspace: CanonicalWorkspace = {
workspace: { schema_version: 2, id: "psd-clinical", name: "PSD Clinical", language: "en" },
dwh: { engine: "postgres", database: "clinical", schema: "datawarehouse", supported_transports: ["postgres_direct"] },
semantic_index: {
vector_store: { engine: "pgvector", database: "vectors", schema: "public", collection: "clinical", dimensions: 768, distance: "cosine", supported_transports: ["pgvector_direct"] },
embedding: { provider: "ollama_compatible", model: "nomic-embed-text", dimensions: 768 },
},
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.embedding.model"],
base: workspace,
local: { ...workspace, semantic_index: { ...workspace.semantic_index, embedding: { ...workspace.semantic_index.embedding, model: "local-model" } } },
remote: { ...workspace, semantic_index: { ...workspace.semantic_index, embedding: { ...workspace.semantic_index.embedding, model: "remote-model" } } },
};
beforeEach(() => {
server.use(http.post("http://localhost:8787/workspaces/validate", () => HttpResponse.json({ workspace, contract: {} })));
});
test("validates a draft and requires a separate confirmation before publishing", async () => {
const user = userEvent.setup();
const published = vi.fn();
let publishCalls = 0;
server.use(http.post("http://localhost:8787/workspaces/publish", () => {
publishCalls += 1;
return HttpResponse.json({ revision: { id: "psd-clinical", commit: "c".repeat(40), blob: "d".repeat(40), snapshotPath: "/safe", state: "operational" } });
}));
render(<WorkspacePublishDialog open request={request} onOpenChange={vi.fn()} onPublished={published} onPull={vi.fn()} onReload={vi.fn()} />);
expect(screen.getByRole("button", { name: "Publish" })).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(publishCalls).toBe(0);
await user.click(screen.getByRole("button", { name: "Confirm publish" }));
await waitFor(() => expect(published).toHaveBeenCalledTimes(1));
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("http://localhost:8787/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()} 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.embedding.model")).toBeVisible();
expect(screen.getByText("local-model")).toBeVisible();
expect(screen.getByText("remote-model")).toBeVisible();
expect(screen.getByRole("button", { name: "Pull latest registry" })).toBeVisible();
expect(screen.getByRole("button", { name: "Reload workspace" })).toBeVisible();
expect(screen.queryByRole("button", { name: /use local|use remote|confirm publish/i })).not.toBeInTheDocument();
expect(published).toBe(true);
});
test("keeps a conflict open and redacts a failed registry pull", async () => {
const user = userEvent.setup();
server.use(http.post("http://localhost:8787/workspaces/publish", () => HttpResponse.json({
...conflict, message: "Workspace changed in the registry.",
}, { status: 409 })));
render(<WorkspacePublishDialog open request={request} onOpenChange={vi.fn()} onPublished={vi.fn()} onPull={vi.fn().mockRejectedValue(new Error("token=secret"))} 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("button", { name: "Pull latest registry" }));
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();
});
@@ -0,0 +1,166 @@
import { useEffect, useState } from "react";
import {
asWorkspaceApiError,
asWorkspaceConflict,
publishWorkspace,
validateWorkspace,
type CanonicalWorkspace,
type PublishWorkspaceRequest,
type WorkspaceConflict,
type WorkspaceRevision,
} from "../api/workspaces";
import { Button } from "../components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../components/ui/dialog";
export interface WorkspacePublishDialogProps {
open: boolean;
request: PublishWorkspaceRequest;
onOpenChange: (open: boolean) => void;
onPublished: (revision: WorkspaceRevision | undefined) => 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 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>;
}
function ConflictReview({ conflict, onPull, onReload }: { conflict: WorkspaceConflict; onPull: () => Promise<void> | void; onReload: () => void }) {
const [pulling, setPulling] = useState(false);
const [pulled, setPulled] = useState(false);
const [pullError, setPullError] = useState(false);
async function pull() {
setPulling(true);
setPullError(false);
try {
await onPull();
setPulled(true);
} catch {
setPullError(true);
} finally {
setPulling(false);
}
}
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">Your browser draft is unchanged. Pull or reload before creating a revised draft; this screen never merges or overwrites remote values.</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>
</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 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, onPull, onReload }: WorkspacePublishDialogProps) {
const [validatedRequest, setValidatedRequest] = useState<PublishWorkspaceRequest>();
const [confirmationOpen, setConfirmationOpen] = useState(false);
const [conflict, setConflict] = useState<WorkspaceConflict>();
const [message, setMessage] = useState<string>();
const [publishing, setPublishing] = useState(false);
useEffect(() => {
if (!open) return;
setValidatedRequest(undefined);
setConfirmationOpen(false);
setConflict(undefined);
setMessage(undefined);
setPublishing(false);
}, [open, request]);
async function validate() {
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));
setMessage("Workspace definition is valid.");
} catch (error) {
const safe = asWorkspaceApiError(error);
setMessage(safe ? `${safe.code}: ${safe.message}` : "workspace_invalid: Validation could not be completed");
}
}
async function publish() {
if (!validatedRequest) return;
setPublishing(true);
setMessage(undefined);
try {
const result = await publishWorkspace(validatedRequest);
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");
}
} 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 ? "Compare the changed fields, then pull and reload before revising your draft." : "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} /> : <>
<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>
</DialogContent>
</Dialog>
</Dialog>;
}
+3 -2
View File
@@ -250,7 +250,8 @@ function copyDiagnostics(value: unknown): CanonicalDiagnostics | undefined {
return diagnostics;
}
function copyWorkspace(value: unknown): CanonicalWorkspace | undefined {
/** Drops unknown fields before a server response can become a browser draft or conflict view. */
export function sanitizeCanonicalWorkspace(value: unknown): CanonicalWorkspace | undefined {
const source = exactRecord(value, ["workspace", "dwh", "semantic_index", "llm_policy", "diagnostics"]);
const metadata = exactRecord(source?.workspace, ["schema_version", "id", "name", "description", "language"]);
const dwh = exactRecord(source?.dwh, ["engine", "database", "schema", "port", "timeout_ms", "supported_transports"]);
@@ -330,7 +331,7 @@ function copyWorkspace(value: unknown): CanonicalWorkspace | undefined {
function normalize(value: unknown): WorkspaceDraft | undefined {
const source = exactRecord(value, ["workspaceId", "baseCommit", "baseBlob", "workspace", "updatedAt"]);
const workspace = copyWorkspace(source?.workspace);
const workspace = sanitizeCanonicalWorkspace(source?.workspace);
const id = workspaceId(source?.workspaceId);
const baseCommit = typeof source?.baseCommit === "string" && /^[0-9a-f]{40}$/.test(source.baseCommit) ? source.baseCommit : undefined;
const baseBlob = source?.baseBlob === undefined ? undefined : typeof source.baseBlob === "string" && /^[0-9a-f]{40}$/.test(source.baseBlob) ? source.baseBlob : undefined;