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
+18 -11
View File
@@ -1,6 +1,6 @@
import { http, HttpResponse } from "msw"; import { http, HttpResponse } from "msw";
import { server } from "../test/msw"; import { server } from "../test/msw";
import { canonicalWorkspaceFixture } from "../test/workspace-fixtures"; import { canonicalWorkspaceFixture, workspaceRevisionFixture, workspaceSummaryFixture } from "../test/workspace-fixtures";
import { createSession, getMe, listSessions, prewarmRuntime, resumeSession } from "./sessions"; import { createSession, getMe, listSessions, prewarmRuntime, resumeSession } from "./sessions";
import { import {
renameSession, setSessionGroup, archiveSession, unarchiveSession, renameSession, setSessionGroup, archiveSession, unarchiveSession,
@@ -15,8 +15,10 @@ test("createSession migrates legacy selections and POSTs browser preferences", a
workspace: "psd-clinical", provider: "zai", model: "glm-5.2", thinking: "low", workspace: "psd-clinical", provider: "zai", model: "glm-5.2", thinking: "low",
})), })),
http.get("/api/workspaces", () => HttpResponse.json([{ http.get("/api/workspaces", () => HttpResponse.json([{
id: "psd-clinical", name: "psd-clinical", file: "psd-clinical.yaml", displayName: "PSD Clinical", language: "en", ...workspaceSummaryFixture("psd-clinical", {
revision: { id: "psd-clinical", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/snapshot" }, displayName: "PSD Clinical",
revision: workspaceRevisionFixture("psd-clinical"),
}),
}])), }])),
http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({ http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("psd-clinical"), workspace: canonicalWorkspaceFixture("psd-clinical"),
@@ -43,11 +45,11 @@ test("createSession does not POST when a selected summary aliases another worksp
let posted = false; let posted = false;
server.use( server.use(
http.get("/api/workspaces", () => HttpResponse.json([{ http.get("/api/workspaces", () => HttpResponse.json([{
id: "psd-clinical", name: "other-workspace", file: "psd-clinical.yaml", ...workspaceSummaryFixture("psd-clinical", {
displayName: "PSD Clinical", language: "en", displayName: "PSD Clinical",
revision: { revision: workspaceRevisionFixture("psd-clinical"),
id: "psd-clinical", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/snapshot", }),
}, name: "other-workspace",
}])), }])),
http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({ http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("psd-clinical"), workspace: canonicalWorkspaceFixture("psd-clinical"),
@@ -82,8 +84,10 @@ test.each([
let posted = false; let posted = false;
server.use( server.use(
http.get("/api/workspaces", () => HttpResponse.json([{ http.get("/api/workspaces", () => HttpResponse.json([{
id: "psd-clinical", name: "psd-clinical", file: "psd-clinical.yaml", ...workspaceSummaryFixture("psd-clinical", {
displayName: "PSD Clinical", language: "en", revision, displayName: "PSD Clinical",
revision: revision as any,
}),
}])), }])),
http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({ http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("psd-clinical"), workspace: canonicalWorkspaceFixture("psd-clinical"),
@@ -131,7 +135,10 @@ test("createSession rejects a workspace summary that omits the canonical revisio
workspace: "psd-clinical", provider: "zai", model: "glm-5.2", thinking: "low", workspace: "psd-clinical", provider: "zai", model: "glm-5.2", thinking: "low",
})), })),
http.get("/api/workspaces", () => HttpResponse.json([{ http.get("/api/workspaces", () => HttpResponse.json([{
id: "psd-clinical", name: "psd-clinical", file: "psd-clinical.yaml", displayName: "PSD Clinical", language: "en", ...workspaceSummaryFixture("psd-clinical", {
displayName: "PSD Clinical",
configurationState: "configuration_required",
}),
}])), }])),
http.post("/api/sessions", async () => { http.post("/api/sessions", async () => {
posted = true; posted = true;
+97 -297
View File
@@ -1,27 +1,32 @@
import { expect, test } from "vitest"; import { expect, test } from "vitest";
import { http, HttpResponse } from "msw"; import { http, HttpResponse } from "msw";
import { server } from "../test/msw"; import { server } from "../test/msw";
import { canonicalWorkspaceFixture, workspaceRevisionFixture, workspaceSummaryFixture } from "../test/workspace-fixtures";
import { import {
asWorkspaceConflict, getWorkspace, importWorkspace, listWorkspaces, publishWorkspace, validateWorkspace, asWorkspaceApiError,
getWorkspace,
importWorkspace,
listWorkspaces,
publishWorkspace,
validateWorkspace,
type CanonicalWorkspace, type CanonicalWorkspace,
} from "./workspaces"; } from "./workspaces";
const workspace: CanonicalWorkspace = { const workspace = canonicalWorkspaceFixture("psd-clinical");
workspace: { schema_version: 3, id: "psd-clinical", name: "PSD Clinical", language: "en" }, const revision = workspaceRevisionFixture("psd-clinical");
dwh: { engine: "postgres", database: "clinical", schema: "datawarehouse", supported_transports: ["postgres_direct"] },
semantic_index: { const readySummary = workspaceSummaryFixture("psd-clinical", {
vector_store: { engine: "qdrant", collection: "clinical", dimensions: 1024, distance: "cosine" }, displayName: "PSD Clinical",
embedding: { provider: "ollama_internal", model: "qwen3-embedding:0.6b", dimensions: 1024 }, description: "Clinical workspace",
}, revision,
llm_policy: { allowed: ["zai/glm-5.2"] }, });
};
const evidenceWorkspace = { const evidenceWorkspace = {
...workspace, ...workspace,
evidence: { evidence: {
source: { source: {
type: "filesystem", type: "filesystem",
uri: "workspace-content/psd-clinical/evidence", uri: "psd-clinical/evidence",
patterns: ["**/*.md"], patterns: ["**/*.md"],
max_bytes: 10 * 1024 * 1024, max_bytes: 10 * 1024 * 1024,
}, },
@@ -29,79 +34,43 @@ const evidenceWorkspace = {
}, },
} satisfies CanonicalWorkspace; } satisfies CanonicalWorkspace;
const revision = { test("decodes catalog-driven workspace summaries with exact root descriptor paths", async () => {
id: "psd-clinical", server.use(http.get("/api/workspaces", () => HttpResponse.json([
commit: "a".repeat(40), readySummary,
blob: "b".repeat(40), workspaceSummaryFixture("bootstrap-slot", {
snapshotPath: "workspaces/psd-clinical.yaml", displayName: "Bootstrap slot",
}; description: "Needs configuration",
configurationState: "configuration_required",
}),
])));
const summary = { await expect(listWorkspaces()).resolves.toEqual([
id: "psd-clinical", readySummary,
name: "psd-clinical", workspaceSummaryFixture("bootstrap-slot", {
file: "psd-clinical.yaml", displayName: "Bootstrap slot",
displayName: "PSD Clinical", description: "Needs configuration",
description: "Clinical workspace", configurationState: "configuration_required",
language: "en" as const, }),
revision, ]);
};
test("decodes and normalizes state-free workspace summaries without passing through backend-only fields", async () => {
server.use(http.get("/api/workspaces", () => HttpResponse.json([{
...summary, workspace, backendOnly: "ignored",
}])));
await expect(listWorkspaces()).resolves.toEqual([summary]);
});
test("accepts internally multiline display names and descriptions using backend trim semantics", async () => {
const multiline = {
...summary,
displayName: "PSD\nClinical",
description: "First line\n\tSecond line",
};
server.use(http.get("/api/workspaces", () => HttpResponse.json([multiline])));
await expect(listWorkspaces()).resolves.toEqual([multiline]);
}); });
test.each([ test.each([
["an id/name alias", { ...summary, name: "other-workspace" }], ["a summary with the removed language field", { ...readySummary, language: "en" }],
["a non-canonical selector file", { ...summary, file: "workspaces/psd-clinical.yaml" }], ["a non-canonical descriptor path", { ...readySummary, file: "psd-clinical.yaml" }],
])("rejects workspace summaries with %s", async (_case, malformedSummary) => { ["a ready summary without a revision", { ...readySummary, revision: undefined }],
["a configuration_required summary with a revision", {
...workspaceSummaryFixture("bootstrap-slot", {
displayName: "Bootstrap slot",
configurationState: "configuration_required",
}),
revision,
}],
])("rejects %s", async (_case, malformedSummary) => {
server.use(http.get("/api/workspaces", () => HttpResponse.json([malformedSummary]))); server.use(http.get("/api/workspaces", () => HttpResponse.json([malformedSummary])));
await expect(listWorkspaces()).rejects.toThrow("invalid workspace summary"); await expect(listWorkspaces()).rejects.toThrow("invalid workspace summary");
}); });
test.each([
["historical state", { ...revision, state: "operational" }],
["unknown revision field", { ...revision, generation: 1 }],
["malformed revision", { ...revision, commit: "not-a-commit" }],
])("rejects workspace summaries with %s", async (_case, malformedRevision) => {
server.use(http.get("/api/workspaces", () => HttpResponse.json([{
...summary, revision: malformedRevision,
}])));
await expect(listWorkspaces()).rejects.toThrow("invalid workspace summary");
});
test.each([
["a non-array response", { ...summary }],
["a malformed selector field", [{ ...summary, language: "fr" }]],
])("rejects %s from the workspace summary API", async (_case, response) => {
server.use(http.get("/api/workspaces", () => HttpResponse.json(response)));
await expect(listWorkspaces()).rejects.toThrow("invalid workspace summary");
});
test("preserves a present summary without revision so callers can distinguish it from an absent workspace", async () => {
const { revision: _revision, ...incomplete } = summary;
server.use(http.get("/api/workspaces", () => HttpResponse.json([incomplete])));
await expect(listWorkspaces()).resolves.toEqual([incomplete]);
});
test("uploads a workspace bundle without JSON content type", async () => { test("uploads a workspace bundle without JSON content type", async () => {
let contentType: string | null = null; let contentType: string | null = null;
server.use(http.post("/api/workspaces/import", ({ request }) => { server.use(http.post("/api/workspaces/import", ({ request }) => {
@@ -111,13 +80,10 @@ test("uploads a workspace bundle without JSON content type", async () => {
await importWorkspace(new File(["zip"], "clinical.thoth-workspace.zip", { type: "application/zip" })); await importWorkspace(new File(["zip"], "clinical.thoth-workspace.zip", { type: "application/zip" }));
// jsdom's FormData is not the same implementation as Node's fetch FormData,
// so it cannot expose a browser-generated boundary here. The client must leave
// that header untouched; a real browser adds multipart/form-data + boundary.
expect(contentType ?? "").not.toMatch(/application\/json/i); expect(contentType ?? "").not.toMatch(/application\/json/i);
}); });
test("sanitizes imported Evidence before returning a browser draft", async () => { test("sanitizes imported filesystem Evidence only when it uses the workspace directory root", async () => {
server.use(http.post("/api/workspaces/import", () => HttpResponse.json({ server.use(http.post("/api/workspaces/import", () => HttpResponse.json({
draft: { workspace: evidenceWorkspace, contract: { variables: [] } }, draft: { workspace: evidenceWorkspace, contract: { variables: [] } },
}))); })));
@@ -128,13 +94,21 @@ test("sanitizes imported Evidence before returning a browser draft", async () =>
expect(result.draft.workspace).not.toBe(evidenceWorkspace); expect(result.draft.workspace).not.toBe(evidenceWorkspace);
}); });
test("rejects imported Evidence with a secret-shaped field", async () => { test("rejects imported filesystem Evidence that still points at workspace-content", async () => {
const malformed = {
...evidenceWorkspace,
evidence: { ...evidenceWorkspace.evidence, signed_urls_file: "/run/secrets/urls" },
};
server.use(http.post("/api/workspaces/import", () => HttpResponse.json({ server.use(http.post("/api/workspaces/import", () => HttpResponse.json({
draft: { workspace: malformed, contract: {} }, draft: {
workspace: {
...evidenceWorkspace,
evidence: {
...evidenceWorkspace.evidence,
source: {
...evidenceWorkspace.evidence.source,
uri: "workspace-content/psd-clinical/evidence",
},
},
},
contract: { variables: [] },
},
}))); })));
await expect(importWorkspace(new File(["zip"], "clinical.thoth-workspace.zip"))) await expect(importWorkspace(new File(["zip"], "clinical.thoth-workspace.zip")))
@@ -142,140 +116,12 @@ test("rejects imported Evidence with a secret-shaped field", async () => {
}); });
test("accepts the atomic schema-v3 workspace revision contract without historical state", async () => { test("accepts the atomic schema-v3 workspace revision contract without historical state", async () => {
const stateFreeRevision = { server.use(http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({ workspace, revision })));
id: "psd-clinical",
commit: "a".repeat(40),
blob: "b".repeat(40),
snapshotPath: "workspaces/psd-clinical.yaml",
};
server.use(http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({
workspace, revision: stateFreeRevision,
})));
await expect(getWorkspace("psd-clinical")).resolves.toEqual({ workspace, revision: stateFreeRevision }); await expect(getWorkspace("psd-clinical")).resolves.toEqual({ workspace, revision });
}); });
test("rejects the removed historical workspace revision state as an extra API key", async () => { test("sanitizes read and validate responses while preserving directory-based Evidence", async () => {
server.use(http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({
workspace,
revision: {
id: "psd-clinical",
commit: "a".repeat(40),
blob: "b".repeat(40),
snapshotPath: "workspaces/psd-clinical.yaml",
[["st", "ate"].join("")]: "operational",
},
})));
await expect(getWorkspace("psd-clinical")).rejects.toThrow("invalid workspace revision");
});
test("rejects read responses with a missing or inconsistent revision", async () => {
server.use(http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({
workspace: evidenceWorkspace,
revision: { ...revision, id: "other-workspace" },
})));
await expect(getWorkspace("psd-clinical")).rejects.toThrow("invalid workspace revision");
server.use(http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({
workspace: evidenceWorkspace, revision: null,
})));
await expect(getWorkspace("psd-clinical")).rejects.toThrow("invalid workspace revision");
});
test("rejects a publish response with a malformed revision", async () => {
server.use(http.post("/api/workspaces/publish", () => HttpResponse.json({
revision: { ...revision, commit: "not-a-commit" },
})));
await expect(publishWorkspace({
action: "update", workspace: evidenceWorkspace,
baseCommit: revision.commit, baseBlob: revision.blob,
})).rejects.toThrow("invalid workspace revision");
});
test("rejects a conflict payload that attempts to surface a secret field", async () => {
server.use(http.post("/api/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();
});
const diagnosticConflictFields = [
"diagnostics.dwh_rest.method", "diagnostics.dwh_rest.path", "diagnostics.dwh_rest.auth",
"diagnostics.dwh_rest.response.database", "diagnostics.dwh_rest.response.schema",
] as const;
const optionalDiagnosticsConflictFields = [
"diagnostics",
"diagnostics.dwh_rest",
] as const;
const diagnosticsWorkspace: CanonicalWorkspace = {
...workspace,
dwh: { ...workspace.dwh, supported_transports: ["postgres_direct", "rest_api"] },
diagnostics: {
dwh_rest: { method: "POST", path: "/rpc/ping", auth: "bearer", response: { database: "database", schema: "schema" } },
},
};
test.each(optionalDiagnosticsConflictFields)("accepts optional diagnostics conflict branch %s", async (field) => {
server.use(http.post("/api/workspaces/publish", () => HttpResponse.json({
code: "workspace_conflict", message: "Workspace changed in the registry.", fields: [field],
expected: { commit: "a".repeat(40), blob: "b".repeat(40) },
actual: { commit: "c".repeat(40), blob: "d".repeat(40) },
base: workspace, local: diagnosticsWorkspace, remote: diagnosticsWorkspace,
}, { status: 409 })));
const error = await publishWorkspace({ action: "update", workspace: diagnosticsWorkspace, baseCommit: "a".repeat(40), baseBlob: "b".repeat(40) }).catch((cause: unknown) => cause);
expect(asWorkspaceConflict(error)).toMatchObject({ fields: [field] });
});
test.each(diagnosticConflictFields)("accepts canonical diagnostic conflict leaf %s with its remote revision", async (field) => {
const diagnosticsWorkspace: CanonicalWorkspace = {
...workspace,
dwh: { ...workspace.dwh, supported_transports: ["postgres_direct", "rest_api"] },
diagnostics: {
dwh_rest: { method: "POST", path: "/rpc/ping", auth: "bearer", response: { database: "database", schema: "schema" } },
},
};
server.use(http.post("/api/workspaces/publish", () => HttpResponse.json({
code: "workspace_conflict", message: "Workspace changed in the registry.",
fields: [field],
expected: { commit: "a".repeat(40), blob: "b".repeat(40) },
actual: { commit: "c".repeat(40), blob: "d".repeat(40) },
base: diagnosticsWorkspace, local: diagnosticsWorkspace, remote: diagnosticsWorkspace,
}, { status: 409 })));
const error = await publishWorkspace({ action: "update", workspace: diagnosticsWorkspace, baseCommit: "a".repeat(40), baseBlob: "b".repeat(40) }).catch((cause: unknown) => cause);
expect(asWorkspaceConflict(error)).toMatchObject({ actual: { commit: "c".repeat(40), blob: "d".repeat(40) }, fields: [field] });
});
test("rejects a conflict payload that attempts to surface removed vector transport and credential branches", async () => {
server.use(http.post("/api/workspaces/publish", () => HttpResponse.json({
code: "workspace_conflict",
message: "Workspace changed in the registry.",
fields: ["diagnostics.vector_rest.reversible_probe.auth"],
expected: { commit: "a".repeat(40), blob: "b".repeat(40) },
actual: { commit: "c".repeat(40), blob: "d".repeat(40) },
base: workspace,
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();
});
test("sanitizes read and validate responses while preserving Evidence", async () => {
server.use( server.use(
http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({ workspace: evidenceWorkspace, revision })), http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({ workspace: evidenceWorkspace, revision })),
http.post("/api/workspaces/validate", () => HttpResponse.json({ workspace: evidenceWorkspace, contract: {} })), http.post("/api/workspaces/validate", () => HttpResponse.json({ workspace: evidenceWorkspace, contract: {} })),
@@ -289,100 +135,54 @@ test("sanitizes read and validate responses while preserving Evidence", async ()
expect(validated.workspace.evidence).toEqual(evidenceWorkspace.evidence); expect(validated.workspace.evidence).toEqual(evidenceWorkspace.evidence);
}); });
test("rejects malformed workspace API responses instead of exposing unknown Evidence fields", async () => { test("publishes only bootstrap create requests", async () => {
const malformed = {
...evidenceWorkspace,
evidence: { ...evidenceWorkspace.evidence, signed_urls_file: "/run/secrets/urls" },
};
server.use(
http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({ workspace: malformed, revision })),
http.post("/api/workspaces/validate", () => HttpResponse.json({ workspace: malformed, contract: {} })),
);
await expect(getWorkspace("psd-clinical")).rejects.toThrow();
await expect(validateWorkspace(evidenceWorkspace)).rejects.toThrow();
});
test("publishes Evidence without mutating or dropping it from the request", async () => {
let sent: unknown; let sent: unknown;
server.use(http.post("/api/workspaces/publish", async ({ request }) => { server.use(http.post("/api/workspaces/publish", async ({ request }) => {
sent = await request.json(); sent = await request.json();
return HttpResponse.json({ revision }); return HttpResponse.json({ revision });
})); }));
await publishWorkspace({ await expect(publishWorkspace({
action: "update", workspace: evidenceWorkspace, action: "create",
baseCommit: revision.commit, baseBlob: revision.blob, workspace: evidenceWorkspace,
baseCommit: revision.commit,
})).resolves.toEqual({ revision });
expect(sent).toEqual({
action: "create",
workspace: { ...evidenceWorkspace },
baseCommit: revision.commit,
}); });
expect(sent).not.toHaveProperty("baseBlob");
expect(sent).toMatchObject({ workspace: { evidence: evidenceWorkspace.evidence } });
expect(evidenceWorkspace.evidence.source.patterns).toEqual(["**/*.md"]);
}); });
const evidenceConflictFields = [ test("rejects a publish response with a malformed revision", async () => {
"evidence",
"evidence.source",
"evidence.source.type",
"evidence.source.uri",
"evidence.source.patterns",
"evidence.source.max_bytes",
"evidence.source.uris",
"evidence.source.authentication",
"evidence.source.connect_timeout_ms",
"evidence.source.read_timeout_ms",
"evidence.source.max_redirects",
"evidence.source.allow_private_hosts",
"evidence.source.max_cache_bytes",
"evidence.source.endpoint_url",
"evidence.source.region",
"evidence.source.credentials",
"evidence.source.trusted_endpoint",
"evidence.source.allow_private_endpoint",
"evidence.source.allow_insecure_endpoint",
"evidence.source.max_objects",
"evidence.source.max_pages",
"evidence.source.page_size",
"evidence.policy",
"evidence.policy.max_chunk_chars",
"evidence.policy.retain_published_generations",
] as const;
test.each(evidenceConflictFields)("accepts canonical Evidence conflict field %s", async (field) => {
server.use(http.post("/api/workspaces/publish", () => HttpResponse.json({ server.use(http.post("/api/workspaces/publish", () => HttpResponse.json({
code: "workspace_conflict", revision: { ...revision, commit: "not-a-commit" },
message: "Workspace changed in the registry.", })));
fields: [field],
expected: { commit: "a".repeat(40), blob: "b".repeat(40) }, await expect(publishWorkspace({
actual: { commit: "c".repeat(40), blob: "d".repeat(40) }, action: "create",
base: evidenceWorkspace, workspace: evidenceWorkspace,
local: evidenceWorkspace, baseCommit: revision.commit,
remote: evidenceWorkspace, })).rejects.toThrow("invalid workspace revision");
});
test("decodes workspace_curator_owned safely without conflict fields", async () => {
server.use(http.post("/api/workspaces/publish", () => HttpResponse.json({
code: "workspace_curator_owned",
message: "Existing descriptors are curator-owned.",
}, { status: 409 }))); }, { status: 409 })));
const error = await publishWorkspace({ const error = await publishWorkspace({
action: "update", workspace: evidenceWorkspace, action: "create",
baseCommit: "a".repeat(40), baseBlob: "b".repeat(40), workspace,
baseCommit: revision.commit,
}).catch((cause: unknown) => cause); }).catch((cause: unknown) => cause);
expect(asWorkspaceConflict(error)).toMatchObject({ fields: [field] }); expect(asWorkspaceApiError(error)).toEqual({
}); status: 409,
code: "workspace_curator_owned",
test("rejects unknown Evidence conflict paths", async () => { message: "Existing descriptors are curator-owned.",
server.use(http.post("/api/workspaces/publish", () => HttpResponse.json({ });
code: "workspace_conflict",
message: "Workspace changed in the registry.",
fields: ["evidence.source.signed_url"],
expected: { commit: "a".repeat(40), blob: "b".repeat(40) },
actual: { commit: "c".repeat(40), blob: "d".repeat(40) },
base: evidenceWorkspace,
local: evidenceWorkspace,
remote: evidenceWorkspace,
}, { status: 409 })));
const error = await publishWorkspace({
action: "update", workspace: evidenceWorkspace,
baseCommit: "a".repeat(40), baseBlob: "b".repeat(40),
}).catch((cause: unknown) => cause);
expect(asWorkspaceConflict(error)).toBeUndefined();
}); });
Binary file not shown.
+6 -5
View File
@@ -4,7 +4,7 @@ import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw"; import { http, HttpResponse } from "msw";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { server } from "../test/msw"; import { server } from "../test/msw";
import { canonicalWorkspaceFixture, workspaceRevisionFixture } from "../test/workspace-fixtures"; import { canonicalWorkspaceFixture, workspaceRevisionFixture, workspaceSummaryFixture } from "../test/workspace-fixtures";
import { NewSessionDialog } from "./NewSessionDialog"; import { NewSessionDialog } from "./NewSessionDialog";
function renderDialog() { 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", workspace: "default", provider: "zai", model: "glm-5.2", thinking: "low",
})), })),
http.get("/api/workspaces", () => HttpResponse.json([{ http.get("/api/workspaces", () => HttpResponse.json([{
id: "default", name: "default", file: "default.yaml", displayName: "Default", language: "en", ...workspaceSummaryFixture("default", {
revision: workspaceRevisionFixture("default"), displayName: "Default",
revision: workspaceRevisionFixture("default"),
}),
}])), }])),
http.get("/api/workspaces/default", () => HttpResponse.json({ http.get("/api/workspaces/default", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("default", ["zai/glm-5.2"], "zai/glm-5.2"), 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", () => { http.get("/api/workspaces", () => {
summaryRequestStarted = true; summaryRequestStarted = true;
return HttpResponse.json([{ return HttpResponse.json([{
id: "psd-clinical", name: "psd-clinical", file: "psd-clinical.yaml", displayName: "PSD Clinical", language: "en", ...workspaceSummaryFixture("psd-clinical", { displayName: "PSD Clinical", revision: revision as any }),
revision,
}]); }]);
}), }),
http.get("/api/workspaces/psd-clinical", async () => { 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 { http, HttpResponse } from "msw";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { server } from "../test/msw"; import { server } from "../test/msw";
import { canonicalWorkspaceFixture } from "../test/workspace-fixtures"; import { canonicalWorkspaceFixture, workspaceSummaryFixture } from "../test/workspace-fixtures";
import { useSessionStore } from "../store/sessionStore"; import { useSessionStore } from "../store/sessionStore";
import { ComposerFooter, ContextGauge, SteerInput } from "./SteerInput"; import { ComposerFooter, ContextGauge, SteerInput } from "./SteerInput";
@@ -24,8 +24,10 @@ test("new sessions send the browser-selected workspace, model, provider, and thi
})); }));
server.use( server.use(
http.get("/api/workspaces", () => HttpResponse.json([{ http.get("/api/workspaces", () => HttpResponse.json([{
id: "psd-clinical", name: "psd-clinical", file: "psd-clinical.yaml", displayName: "PSD Clinical", language: "en", ...workspaceSummaryFixture("psd-clinical", {
revision: { id: "psd-clinical", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/snapshot" }, 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({ http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("psd-clinical"), 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", workspace: "psd", provider: "zai", model: "glm-5.2", thinking: "medium",
})), })),
http.get("/api/workspaces", () => HttpResponse.json([{ http.get("/api/workspaces", () => HttpResponse.json([{
id: "psd", name: "psd", file: "psd.yaml", displayName: "PSD", language: "en", ...workspaceSummaryFixture("psd", {
revision: { id: "psd", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/snapshot" }, displayName: "PSD",
revision: { id: "psd", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/snapshot" },
}),
}])), }])),
http.get("/api/workspaces/psd", () => HttpResponse.json({ http.get("/api/workspaces/psd", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("psd"), 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", workspace: "psd-clinical", provider: "zai", model: "glm-5.2", thinking: "medium",
})), })),
http.get("/api/workspaces", () => HttpResponse.json([{ http.get("/api/workspaces", () => HttpResponse.json([{
id: "psd-clinical", name: "psd-clinical", file: "psd-clinical.yaml", displayName: "PSD Clinical", language: "en", ...workspaceSummaryFixture("psd-clinical", {
revision: { id: "psd-clinical", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/snapshot" }, 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({ http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("psd-clinical"), 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", workspace: "research", provider: "deepseek", model: "deepseek-v4-pro", thinking: "medium",
})), })),
http.get("/api/workspaces", () => HttpResponse.json([ http.get("/api/workspaces", () => HttpResponse.json([
{ id: "research", name: "research", file: "research.yaml", displayName: "Research", language: "en", revision: revision("research") }, workspaceSummaryFixture("research", { displayName: "Research", revision: revision("research") }),
{ 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/research", () => HttpResponse.json({ http.get("/api/workspaces/research", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("research", ["deepseek/deepseek-v4-pro"]), 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( server.use(
http.get("/api/settings", () => HttpResponse.json({ workspace: "research" })), http.get("/api/settings", () => HttpResponse.json({ workspace: "research" })),
http.get("/api/workspaces", () => HttpResponse.json([ http.get("/api/workspaces", () => HttpResponse.json([
{ id: "research", name: "research", file: "research.yaml", displayName: "Research", language: "en", revision: revision("research") }, workspaceSummaryFixture("research", { displayName: "Research", revision: revision("research") }),
{ 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/research", () => HttpResponse.json({ http.get("/api/workspaces/research", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("research", ["deepseek/deepseek-v4-pro"]), revision: revision("research"), 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( server.use(
http.get("/api/settings", () => HttpResponse.json({ workspace: "psd-clinical" })), http.get("/api/settings", () => HttpResponse.json({ workspace: "psd-clinical" })),
http.get("/api/workspaces", () => HttpResponse.json([ 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 () => { http.get("/api/workspaces/psd-clinical", async () => {
policyRequestStarted = true; policyRequestStarted = true;
@@ -359,7 +365,10 @@ test("initial submit rejects a workspace summary that omits the canonical revisi
server.use( server.use(
http.get("/api/settings", () => HttpResponse.json({ workspace: "broken-workspace" })), http.get("/api/settings", () => HttpResponse.json({ workspace: "broken-workspace" })),
http.get("/api/workspaces", () => HttpResponse.json([{ 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: [ http.get("/api/models", () => HttpResponse.json({ models: [
{ provider: "zai", id: "glm-5.2", name: "GLM-5.2", reasoning: true }, { 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( server.use(
http.get("/api/settings", () => HttpResponse.json({ workspace: "research" })), http.get("/api/settings", () => HttpResponse.json({ workspace: "research" })),
http.get("/api/workspaces", () => HttpResponse.json([ http.get("/api/workspaces", () => HttpResponse.json([
{ id: "research", name: "research", file: "research.yaml", displayName: "Research", language: "en", revision: revision("research") }, workspaceSummaryFixture("research", { displayName: "Research", revision: revision("research") }),
{ id: "workspace-b", name: "workspace-b", file: "workspace-b.yaml", displayName: "Workspace B", language: "en", revision: revision("workspace-b") }, workspaceSummaryFixture("workspace-b", { displayName: "Workspace B", revision: revision("workspace-b") }),
{ id: "workspace-c", name: "workspace-c", file: "workspace-c.yaml", displayName: "Workspace C", language: "en", revision: revision("workspace-c") }, workspaceSummaryFixture("workspace-c", { displayName: "Workspace C", revision: revision("workspace-c") }),
])), ])),
http.get("/api/workspaces/research", () => HttpResponse.json({ http.get("/api/workspaces/research", () => HttpResponse.json({
workspace: canonicalWorkspaceFixture("research", ["deepseek/deepseek-v4-pro"]), revision: revision("research"), 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 userEvent from "@testing-library/user-event";
import { expect, test, vi } from "vitest"; import { expect, test, vi } from "vitest";
import type { CanonicalWorkspace } from "../api/workspaces"; 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"; import { WorkspaceEditor } from "./WorkspaceEditor";
const workspace: CanonicalWorkspace = { 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: { dwh: {
engine: "postgres", database: "clinical", schema: "datawarehouse", port: 5432, engine: "postgres", database: "clinical", schema: "datawarehouse", port: 5432,
supported_transports: ["postgres_direct"], supported_transports: ["postgres_direct"],
@@ -22,10 +23,11 @@ const workspace: CanonicalWorkspace = {
const evidenceWorkspace: CanonicalWorkspace = { const evidenceWorkspace: CanonicalWorkspace = {
...workspace, ...workspace,
workspace: { ...workspace.workspace, id: "psd-clinical", name: "PSD Clinical", description: "Clinical workspace" },
evidence: { evidence: {
source: { source: {
type: "filesystem", type: "filesystem",
uri: "workspace-content/psd-clinical/evidence", uri: "psd-clinical/evidence",
patterns: ["documents/**/*.pdf"], patterns: ["documents/**/*.pdf"],
max_bytes: 12_000_000, max_bytes: 12_000_000,
}, },
@@ -33,129 +35,80 @@ const evidenceWorkspace: CanonicalWorkspace = {
}, },
}; };
const draft: WorkspaceDraft = { const draft: WorkspaceBootstrapDraft = {
workspaceId: "psd-clinical", workspaceId: "bootstrap-slot",
baseCommit: "a".repeat(40), baseCommit: "a".repeat(40),
baseBlob: "b".repeat(40),
workspace, workspace,
updatedAt: "2026-08-04T10:00:00.000Z", updatedAt: "2026-08-04T10:00:00.000Z",
}; };
test("uses closed choices for transport and rejects an invalid free-form port before save", async () => { test("bootstrap mode locks catalog metadata and saves only the local bootstrap draft", 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 () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onSaveDraft = vi.fn(); 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.clear(screen.getByLabelText("Vector collection"));
await user.type(screen.getByLabelText("Vector collection"), "research_docs"); await user.type(screen.getByLabelText("Vector collection"), "research_docs");
await user.click(screen.getByRole("button", { name: "Save draft" })); await user.click(screen.getByRole("button", { name: "Save draft" }));
expect(onSaveDraft).toHaveBeenCalledWith(expect.objectContaining({ expect(onSaveDraft).toHaveBeenCalledWith(expect.objectContaining({
baseCommit: "a".repeat(40),
workspaceId: "bootstrap-slot",
workspace: expect.objectContaining({ workspace: expect.objectContaining({
semantic_index: expect.objectContaining({ semantic_index: expect.objectContaining({
vector_store: { vector_store: expect.objectContaining({ collection: "research_docs" }),
engine: "qdrant",
collection: "research_docs",
dimensions: 1024,
distance: "cosine",
},
embedding: {
provider: "ollama_internal",
model: "qwen3-embedding:0.6b",
dimensions: 1024,
},
}), }),
}), }),
})); }));
expect(onSaveDraft.mock.calls[0]?.[0]).not.toHaveProperty("baseBlob");
}); });
test("shows fixed architecture values and no editable endpoint or credential controls", () => { test("read-only mode shows evidence and curator git guidance without mutation actions", () => {
render(<WorkspaceEditor draft={draft} onSaveDraft={vi.fn()} onPublish={vi.fn()} />); render(
<WorkspaceEditor
expect(screen.getByRole("combobox", { name: "Workspace language" })).toHaveValue("en"); mode={{
expect(screen.getByRole("listbox", { name: "DWH transport" })).toHaveProperty("multiple", true); kind: "read_only",
expect(screen.getByLabelText("Vector store engine")).toHaveValue("qdrant"); catalog: workspaceSummaryFixture("psd-clinical", {
expect(screen.getByLabelText("Vector distance")).toHaveValue("cosine"); displayName: "PSD Clinical",
expect(screen.getByLabelText("Semantic index dimensions")).toHaveValue(1024); description: "Clinical workspace",
expect(screen.getByLabelText("Embedding provider")).toHaveValue("ollama_internal"); revision: workspaceRevisionFixture("psd-clinical"),
expect(screen.getByLabelText("Embedding model")).toHaveValue("qwen3-embedding:0.6b"); }),
expect(screen.queryByLabelText("Vector database")).not.toBeInTheDocument(); record: {
expect(screen.queryByLabelText("Vector schema")).not.toBeInTheDocument(); workspace: evidenceWorkspace,
expect(screen.queryByLabelText("Vector port")).not.toBeInTheDocument(); revision: workspaceRevisionFixture("psd-clinical"),
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()} />);
expect(screen.getByLabelText("DWH database")).toHaveValue("clinical");
expect(screen.getByLabelText("DWH database")).toHaveAttribute("readonly");
const summary = screen.getByRole("region", { name: "Evidence" }); const summary = screen.getByRole("region", { name: "Evidence" });
expect(summary).toHaveTextContent("filesystem"); 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("8,000");
expect(summary).toHaveTextContent("5"); expect(summary).toHaveTextContent("5");
expect(summary).toHaveTextContent("Evidence is managed by the registry descriptor in P1."); expect(screen.getByText("Curator workflow")).toBeVisible();
expect(summary).not.toHaveTextContent(/signed_urls_file|static_files|secret|binding/i); expect(screen.getByText(/edit psd-clinical\/workspace\.yaml, commit\/push, then Pull/i)).toBeVisible();
expect(screen.queryByLabelText(/evidence.*(source|uri|pattern|credential)/i)).not.toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Save draft" })).not.toBeInTheDocument();
}); expect(screen.queryByRole("button", { name: /create workspace|publish/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();
}); });
+106 -85
View File
@@ -1,34 +1,30 @@
import { useEffect, useId, useMemo, useState } from "react"; import { useEffect, useId, useMemo, useState, type ChangeEvent, type ReactNode } from "react";
import type { CanonicalWorkspace, PublishWorkspaceRequest } from "../api/workspaces"; import type { CanonicalWorkspace, PublishWorkspaceRequest, WorkspaceRecord, WorkspaceSummary } from "../api/workspaces";
import type { WorkspaceDraft } from "../workspaces/drafts"; import type { WorkspaceBootstrapDraft } from "../workspaces/drafts";
import { Button } from "../components/ui/button"; import { Button } from "../components/ui/button";
type FieldErrors = Record<string, string>; type FieldErrors = Record<string, string>;
export interface WorkspaceEditorProps { export type WorkspaceEditorMode =
draft?: WorkspaceDraft; | { kind: "bootstrap"; catalog: WorkspaceSummary; draft: WorkspaceBootstrapDraft }
onSaveDraft: (draft: WorkspaceDraft) => void; | { kind: "read_only"; catalog: WorkspaceSummary; record: WorkspaceRecord };
/** Reserved for Task 10; saving a draft never publishes it. */
onPublish: (request: PublishWorkspaceRequest) => Promise<void>;
idLocked?: boolean;
}
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 { type ReadOnlyEditorProps = {
return { mode: Extract<WorkspaceEditorMode, { kind: "read_only" }>;
workspace: { schema_version: 3, id: "new-workspace", name: "New workspace", language: "en" }, /** Absent in read-only mode; declared so the union is uniformly addressable. */
dwh: { engine: "postgres", database: "database", schema: "public", supported_transports: ["postgres_direct"] }, onSaveDraft?: never;
semantic_index: { onRequestCreate?: never;
vector_store: { };
engine: "qdrant", collection: "documents",
dimensions: 1024, distance: "cosine", export type WorkspaceEditorProps = BootstrapEditorProps | ReadOnlyEditorProps;
},
embedding: { provider: "ollama_internal", model: "qwen3-embedding:0.6b", dimensions: 1024 }, 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";
},
llm_policy: { allowed: ["zai/glm-5.2"] },
};
}
function positiveInteger(value: number | undefined, label: string, max = Number.MAX_SAFE_INTEGER): string | undefined { function positiveInteger(value: number | undefined, label: string, max = Number.MAX_SAFE_INTEGER): string | undefined {
if (value === undefined) return undefined; if (value === undefined) return undefined;
@@ -52,14 +48,6 @@ function validate(workspace: CanonicalWorkspace): FieldErrors {
const dwhTimeout = positiveInteger(workspace.dwh.timeout_ms, "DWH timeout"); const dwhTimeout = positiveInteger(workspace.dwh.timeout_ms, "DWH timeout");
if (dwhTimeout) errors["dwh.timeout"] = dwhTimeout; 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 (!/^[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))) { 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"; errors["llm.allowed"] = "Use provider/model entries separated by commas";
} }
@@ -69,7 +57,7 @@ function validate(workspace: CanonicalWorkspace): FieldErrors {
return errors; return errors;
} }
function selectedValues(event: React.ChangeEvent<HTMLSelectElement>): string[] { function selectedValues(event: ChangeEvent<HTMLSelectElement>): string[] {
return Array.from(event.currentTarget.selectedOptions, (option) => option.value); 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); 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({ function Field({
label, error, children, hint, label,
error,
hint,
children,
}: { }: {
label: string; label: string;
error?: string; error?: string;
hint?: 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 id = useId();
const errorId = `${id}-error`; 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 ( return (
<section className="border-t border-border/70 pt-5 first:border-t-0 first:pt-0" aria-label={title}> <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> <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"> <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 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">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">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")} published generations</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> </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> </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(props: WorkspaceEditorProps) {
const bootstrapMode = props.mode.kind === "bootstrap";
export function WorkspaceEditor({ draft, onSaveDraft, onPublish, idLocked = Boolean(draft?.baseBlob) }: WorkspaceEditorProps) { const initialWorkspace = props.mode.kind === "bootstrap"
const [workspace, setWorkspace] = useState<CanonicalWorkspace>(draft?.workspace ?? emptyWorkspace()); ? coerceCatalogMetadata(props.mode.draft.workspace, props.mode.catalog)
: props.mode.record.workspace;
const [workspace, setWorkspace] = useState<CanonicalWorkspace>(initialWorkspace);
const [errors, setErrors] = useState<FieldErrors>({}); const [errors, setErrors] = useState<FieldErrors>({});
const readOnly = !bootstrapMode;
const allowedModels = useMemo(() => workspace.llm_policy.allowed.join(", "), [workspace.llm_policy.allowed]); const allowedModels = useMemo(() => workspace.llm_policy.allowed.join(", "), [workspace.llm_policy.allowed]);
useEffect(() => { useEffect(() => {
setWorkspace(draft?.workspace ?? emptyWorkspace()); setWorkspace(props.mode.kind === "bootstrap"
? coerceCatalogMetadata(props.mode.draft.workspace, props.mode.catalog)
: props.mode.record.workspace);
setErrors({}); setErrors({});
}, [draft]); }, [bootstrapMode, props.mode]);
function update(change: (previous: CanonicalWorkspace) => CanonicalWorkspace) { function update(change: (previous: CanonicalWorkspace) => CanonicalWorkspace) {
if (readOnly) return;
setWorkspace((previous) => { setWorkspace((previous) => {
const next = change(previous); const next = coerceCatalogMetadata(change(previous), props.mode.catalog);
setErrors(validate(next)); setErrors(validate(next));
return next; return next;
}); });
} }
function saveDraft() { function currentDraft(): WorkspaceBootstrapDraft {
const nextErrors = validate(workspace); if (props.mode.kind !== "bootstrap") throw new Error("Read-only workspaces cannot create drafts");
setErrors(nextErrors); return {
if (Object.keys(nextErrors).length) return; workspaceId: props.mode.catalog.id,
onSaveDraft({ baseCommit: props.mode.draft.baseCommit,
workspaceId: workspace.workspace.id, workspace: coerceCatalogMetadata(workspace, props.mode.catalog),
baseCommit: draft?.baseCommit ?? EMPTY_COMMIT,
...(draft?.baseBlob ? { baseBlob: draft.baseBlob } : {}),
workspace,
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
}); };
} }
function publishDraft() { function saveDraft() {
if (props.mode.kind !== "bootstrap") return;
const nextErrors = validate(workspace); const nextErrors = validate(workspace);
setErrors(nextErrors); setErrors(nextErrors);
if (Object.keys(nextErrors).length) return; if (Object.keys(nextErrors).length > 0) return;
const baseCommit = draft?.baseCommit ?? EMPTY_COMMIT; props.onSaveDraft?.(currentDraft());
const request: PublishWorkspaceRequest = draft?.baseBlob }
? { action: "update", workspace, baseCommit, baseBlob: draft.baseBlob }
: { action: "create", workspace, baseCommit }; function requestCreate() {
void onPublish(request); 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 ( return (
<form className="grid gap-6" onSubmit={(event) => { event.preventDefault(); saveDraft(); }} noValidate> <form className="grid gap-6" onSubmit={(event) => { event.preventDefault(); saveDraft(); }} noValidate>
<Section title="General"> <Section title="General">
<Field label="Workspace ID" error={errors["workspace.id"]} hint={idLocked ? "Technical IDs cannot change after publication." : "Lowercase, immutable technical identifier."}> <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={idLocked} className={fieldClass} value={workspace.workspace.id} onChange={(event) => update((value) => ({ ...value, workspace: { ...value.workspace, id: event.target.value } }))} />} {({ 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>
<Field label="Workspace name" error={errors["workspace.name"]}> <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} className={fieldClass} value={workspace.workspace.name} onChange={(event) => update((value) => ({ ...value, workspace: { ...value.workspace, name: event.target.value } }))} />} {({ 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>
<Field label="Description"> <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>
<Field label="Workspace language"> <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> </Field>
</Section> </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>} {({ 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>
<Field label="DWH transport" error={errors["dwh.transport"]} hint="Choose supported installation transports."> <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>
<Field label="DWH database" error={errors["dwh.database"]}> <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>
<Field label="DWH schema" error={errors["dwh.schema"]}> <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>
<Field label="DWH port" error={errors["dwh.port"]}> <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>
<Field label="DWH timeout (ms)" error={errors["dwh.timeout"]}> <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> </Field>
</Section> </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 />} {({ id, describedBy, invalid }) => <input id={id} aria-label="Vector store engine" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value="qdrant" readOnly />}
</Field> </Field>
<Field label="Vector collection" error={errors["vector.collection"]}> <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>
<Field label="Vector distance"> <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 />} {({ id, describedBy, invalid }) => <input id={id} aria-label="Vector distance" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value="cosine" readOnly />}
</Field> </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 />} {({ 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>
<Field label="Embedding provider"> <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 />} {({ id, describedBy, invalid }) => <input id={id} aria-label="Embedding provider" aria-describedby={describedBy} aria-invalid={invalid} className={fieldClass} value="ollama_internal" readOnly />}
</Field> </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 />} {({ 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> </Field>
</Section> </Section>
<Section title="LLM policy"> <Section title="LLM policy">
<Field label="Allowed models" error={errors["llm.allowed"]} hint="Comma-separated provider/model identifiers."> <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>
<Field label="Default model" error={errors["llm.default"]} hint="Only models in the allowlist are selectable."> <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> </Field>
</Section> </Section>
{workspace.evidence && <EvidenceSummary evidence={workspace.evidence} />} {workspace.evidence && <EvidenceSummary evidence={workspace.evidence} />}
<Section title="Installation requirements"> <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> </Section>
<div className="flex justify-end gap-2 border-t border-border/70 pt-4"> {readOnly ? (
<Button type="submit" variant="outline">Save draft</Button> <Section title="Curator workflow">
<Button type="button" onClick={publishDraft}>Publish draft</Button> <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>
</div> </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> </form>
); );
} }
+136 -216
View File
@@ -4,17 +4,53 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { http, HttpResponse } from "msw"; import { http, HttpResponse } from "msw";
import { afterEach, beforeEach, expect, test, vi } from "vitest"; import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { server } from "../test/msw"; import { server } from "../test/msw";
import { workspaceRevisionFixture, workspaceSummaryFixture } from "../test/workspace-fixtures";
import { WorkspaceManager } from "./WorkspaceManager"; import { WorkspaceManager } from "./WorkspaceManager";
const workspace = { const readyWorkspace = {
workspace: { schema_version: 3, id: "psd-clinical", name: "PSD Clinical", language: "en" }, workspace: {
dwh: { engine: "postgres", database: "clinical", schema: "datawarehouse", port: 5432, supported_transports: ["postgres_direct"] }, schema_version: 3,
semantic_index: { id: "psd-clinical",
vector_store: { engine: "qdrant", collection: "clinical", dimensions: 1024, distance: "cosine" }, name: "PSD Clinical",
embedding: { provider: "ollama_internal", model: "qwen3-embedding:0.6b", dimensions: 1024 }, description: "Clinical data",
language: "en" as const,
}, },
llm_policy: { default: "zai/glm-5.2", allowed: ["zai/glm-5.2"] }, dwh: {
} as const; 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() { function renderManager() {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
@@ -26,58 +62,108 @@ beforeEach(() => {
server.use( server.use(
http.get("/api/workspace-registry/status", () => http.get("/api/workspace-registry/status", () =>
HttpResponse.json({ branch: "main", head: "a".repeat(40), ahead: 0, behind: 0, degraded: false })), HttpResponse.json({ branch: "main", head: "a".repeat(40), ahead: 0, behind: 0, degraded: false })),
http.get("/api/workspaces", () => HttpResponse.json([{ http.get("/api/workspaces", () => HttpResponse.json([
id: "psd-clinical", name: "psd-clinical", displayName: "PSD Clinical", description: "Clinical data", workspaceSummaryFixture("bootstrap-slot", {
language: "en", file: "psd-clinical.yaml", displayName: "Bootstrap slot",
revision: { id: "psd-clinical", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/tmp/psd" }, 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({ http.get("/api/workspaces/psd-clinical", () => HttpResponse.json({
workspace, workspace: readyWorkspace,
revision: { id: "psd-clinical", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/tmp/psd" }, revision: workspaceRevisionFixture("psd-clinical"),
})), })),
); );
}); });
afterEach(() => vi.unstubAllGlobals()); 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(); const user = userEvent.setup();
renderManager(); renderManager();
expect(await screen.findByRole("heading", { name: "Workspace management" })).toBeVisible(); expect(await screen.findByRole("heading", { name: "Workspace management" })).toBeVisible();
expect(await screen.findByRole("button", { name: "PSD Clinical" })).toBeVisible(); expect(screen.getByRole("button", { name: "Bootstrap slot" })).toBeVisible();
expect(screen.getByText(`Commit ${"a".repeat(12)}`)).toBeVisible(); expect(screen.getByRole("button", { name: "PSD Clinical" })).toBeVisible();
await user.click(screen.getByRole("button", { name: "New workspace" })); await user.click(screen.getByRole("button", { name: "Bootstrap slot" }));
await user.clear(screen.getByLabelText("Workspace ID"));
await user.type(screen.getByLabelText("Workspace ID"), "trial-registry"); 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 user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(screen.getByText("Draft saved in this browser.")).toBeVisible()); 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 user = userEvent.setup();
const publishSpy = vi.fn(); let workspacesCalls = 0;
server.use( server.use(
http.post("/api/workspaces/import", () => HttpResponse.json({ draft: { workspace, contract: {} } })), http.get("/api/workspaces", () => {
http.post("/api/workspaces/publish", () => { workspacesCalls += 1;
publishSpy(); return HttpResponse.json(workspacesCalls === 1 ? [
return HttpResponse.json({}); 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(); 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(); await waitFor(() => expect(localStorage.getItem("thothii.workspace-registry.v2.bootstrap.bootstrap-slot")).toBeNull());
expect(publishSpy).not.toHaveBeenCalled(); expect(await screen.findByText(/edit bootstrap-slot\/workspace\.yaml, commit\/push, then Pull/i)).toBeVisible();
expect(localStorage.getItem("thothii.workspace-registry.v1.draft.psd-clinical")).not.toBeNull(); 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 user = userEvent.setup();
const publishSpy = vi.fn();
const createObjectURL = vi.fn(() => "blob:workspace-bundle"); const createObjectURL = vi.fn(() => "blob:workspace-bundle");
const revokeObjectURL = vi.fn(); const revokeObjectURL = vi.fn();
class DownloadUrl extends URL { class DownloadUrl extends URL {
@@ -89,123 +175,22 @@ test("pulls and exports only when the manager explicitly requests each action",
server.use( server.use(
http.post("/api/workspace-registry/pull", () => HttpResponse.json({ branch: "main", head: "c".repeat(40), ahead: 0, behind: 0, degraded: false })), 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.get("/api/workspaces/psd-clinical/export", () => new HttpResponse(new Blob(["bundle"], { type: "application/zip" }))),
http.post("/api/workspaces/publish", () => { http.post("/api/workspaces/validate", () => HttpResponse.json({ workspace: readyWorkspace, contract: {} })),
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/psd-clinical/test", () => HttpResponse.json({ http.post("/api/workspaces/psd-clinical/test", () => HttpResponse.json({
activatable: false, activatable: false,
diagnostics: [{ level: "warning", code: "binding_missing", field: "dwh", message: "DWH binding is not configured" }], 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(); renderManager();
await user.click(await screen.findByRole("button", { name: "PSD Clinical" })); 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" })); await user.click(screen.getByRole("button", { name: "Validate workspace" }));
expect(await screen.findByText("Workspace definition is valid.")).toBeVisible(); expect(await screen.findByText("Workspace definition is valid.")).toBeVisible();
await user.click(screen.getByRole("button", { name: "Test on this installation" })); 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(); 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(); const user = userEvent.setup();
renderManager(); 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(); server.use(http.post("/api/workspaces/import", () => HttpResponse.json({ draft: { workspace: bootstrapWorkspace, contract: {} } })));
expect(screen.getByText(`Revision ${"a".repeat(12)}`)).toBeVisible(); await user.upload(screen.getByLabelText("Import workspace bundle"), new File(["bundle"], "workspace.zip", { type: "application/zip" }));
expect(screen.queryByText(/migration required/i)).not.toBeInTheDocument(); 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();
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);
}); });
+169 -217
View File
@@ -1,12 +1,22 @@
import { useMemo, useState } from "react"; import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query"; 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 { import {
asWorkspaceApiError, exportWorkspace, getWorkspace, getWorkspaceRegistryStatus, importWorkspace, asWorkspaceApiError,
listWorkspaces, pullWorkspaceRegistry, testWorkspace, validateWorkspace, type CanonicalWorkspace, exportWorkspace,
type PublishWorkspaceRequest, type WorkspaceRecord, type WorkspaceRevision, getWorkspace,
getWorkspaceRegistryStatus,
importWorkspace,
listWorkspaces,
pullWorkspaceRegistry,
testWorkspace,
validateWorkspace,
type CanonicalWorkspace,
type PublishWorkspaceRequest,
type WorkspaceRecord,
type WorkspaceSummary,
} from "../api/workspaces"; } 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 { Button } from "../components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "../components/ui/dialog"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "../components/ui/dialog";
import { WorkspaceEditor } from "./WorkspaceEditor"; import { WorkspaceEditor } from "./WorkspaceEditor";
@@ -14,34 +24,6 @@ import { WorkspacePublishDialog } from "./WorkspacePublishDialog";
const EMPTY_COMMIT = "0".repeat(40); 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 }: { function QueryError({ name, message, retryLabel, onRetry }: {
name: string; name: string;
message: 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>; 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 }) { export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: () => void }) {
const [selectedId, setSelectedId] = useState<string>(); const [selectedId, setSelectedId] = useState<string>();
const [localDraft, setLocalDraft] = useState<WorkspaceDraft>(); const [localDraft, setLocalDraft] = useState<WorkspaceBootstrapDraft>();
const [notice, setNotice] = useState<string>(); const [notice, setNotice] = useState<string>();
const [diagnostics, setDiagnostics] = useState<string[]>([]); const [diagnostics, setDiagnostics] = useState<string[]>([]);
const [deletionDraft, setDeletionDraft] = useState<WorkspaceDeletionDraft>();
const [publishRequest, setPublishRequest] = useState<PublishWorkspaceRequest>(); const [publishRequest, setPublishRequest] = useState<PublishWorkspaceRequest>();
const [transferring, setTransferring] = useState(false); const [transferring, setTransferring] = useState(false);
const statusQuery = useQuery({ queryKey: ["workspace-registry-status"], queryFn: getWorkspaceRegistryStatus, enabled: open }); const statusQuery = useQuery({ queryKey: ["workspace-registry-status"], queryFn: getWorkspaceRegistryStatus, enabled: open });
const workspacesQuery = useQuery({ queryKey: ["workspaces"], queryFn: listWorkspaces, enabled: open }); const workspacesQuery = useQuery({ queryKey: ["workspaces"], queryFn: listWorkspaces, enabled: open });
const workspaces = workspacesQuery.data ?? []; const workspaces = workspacesQuery.data ?? [];
const selectedSummary = useMemo(() => workspaces.find((workspace) => workspace.id === selectedId), [selectedId, workspaces]); const selectedSummary = useMemo(() => workspaces.find((workspace) => workspace.id === selectedId), [selectedId, workspaces]);
const selectedSummaryIncomplete = Boolean(selectedSummary && !selectedSummary.revision);
const detailQuery = useQuery({ const detailQuery = useQuery({
queryKey: ["workspace", selectedId], queryKey: ["workspace", selectedId],
queryFn: () => getWorkspace(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 record = detailQuery.data;
const savedDraft = selectedId && !localDraft ? workspaceDrafts.load(selectedId) : undefined; const activeBootstrapDraft = selectedSummary?.configurationState === "configuration_required"
const savedDeletionDraft = selectedId && !deletionDraft ? workspaceDeletionDrafts.load(selectedId) : undefined; ? (localDraft?.workspaceId === selectedSummary.id ? localDraft : workspaceBootstrapDrafts.load(selectedSummary.id) ?? bootstrapDraftFor(selectedSummary, statusQuery.data?.head ?? EMPTY_COMMIT))
const currentDraft = localDraft ?? savedDraft ?? (record ? draftFromRecord(record) : undefined); : undefined;
const activeDeletionDraft = deletionDraft ?? savedDeletionDraft;
const canTest = Boolean(record && currentDraft?.workspaceId === record.workspace.workspace.id); function resetTransientState() {
setNotice(undefined);
setDiagnostics([]);
setPublishRequest(undefined);
}
function selectWorkspace(id: string) { function selectWorkspace(id: string) {
setSelectedId(id); setSelectedId(id);
setLocalDraft(undefined); setLocalDraft(undefined);
setDeletionDraft(undefined); resetTransientState();
setNotice(undefined);
setDiagnostics([]);
setPublishRequest(undefined);
} }
function createWorkspace() { function saveDraft(draft: WorkspaceBootstrapDraft) {
const draft: WorkspaceDraft = { workspaceId: "new-workspace", baseCommit: EMPTY_COMMIT, workspace: newWorkspace(), updatedAt: new Date().toISOString() }; workspaceBootstrapDrafts.save(draft);
setSelectedId(draft.workspaceId);
setLocalDraft(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); setSelectedId(draft.workspaceId);
setLocalDraft(draft);
setNotice("Draft saved in this browser."); setNotice("Draft saved in this browser.");
setDiagnostics([]);
} }
function requestPublish(request: PublishWorkspaceRequest) { function requestCreate(request: PublishWorkspaceRequest, draft: WorkspaceBootstrapDraft) {
if (request.action !== "delete") { workspaceBootstrapDrafts.save(draft);
const nextDraft: WorkspaceDraft = { setLocalDraft(draft);
workspaceId: request.workspace.workspace.id, setSelectedId(draft.workspaceId);
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); setNotice(undefined);
setDiagnostics([]); setDiagnostics([]);
setPublishRequest(request); setPublishRequest(request);
} }
function requestDeletionPublish() {
if (!activeDeletionDraft) return;
requestPublish({ action: "delete", id: activeDeletionDraft.id, baseCommit: activeDeletionDraft.baseCommit, baseBlob: activeDeletionDraft.baseBlob });
}
async function pullLatest() { async function pullLatest() {
setNotice(undefined); setNotice(undefined);
setDiagnostics([]); setDiagnostics([]);
@@ -153,47 +136,35 @@ export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: ()
} catch (error) { } catch (error) {
const safe = asWorkspaceApiError(error); const safe = asWorkspaceApiError(error);
setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "git_unavailable: Registry pull could not be completed"]); setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "git_unavailable: Registry pull could not be completed"]);
throw error;
} }
} }
function reloadWorkspace() { async function validateSelectedWorkspace() {
if (selectedId) { if (!record) return;
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); setNotice(undefined);
setDiagnostics([]); setDiagnostics([]);
try { try {
const result = await importWorkspace(file); await validateWorkspace(record.workspace);
const imported: WorkspaceDraft = { setNotice("Workspace definition is valid.");
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) { } catch (error) {
const safe = asWorkspaceApiError(error); const safe = asWorkspaceApiError(error);
setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "workspace_invalid: Workspace bundle could not be imported"]); setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "workspace_invalid: Validation could not be completed"]);
} finally { }
setTransferring(false); }
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) { async function importBundle(file: File | undefined) {
const publishedRequest = publishRequest; if (!file) return;
if (publishedRequest?.action === "delete") { setTransferring(true);
workspaceDeletionDrafts.discard(publishedRequest.id); setNotice(undefined);
setSelectedId(undefined); setDiagnostics([]);
} else if (publishedRequest) { try {
workspaceDrafts.discard(publishedRequest.workspace.workspace.id); const result = await importWorkspace(file);
setSelectedId(publishedRequest.workspace.workspace.id); 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); 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); setPublishRequest(undefined);
setDiagnostics([]); 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() { const titleReady = workspacesQuery.isSuccess || workspacesQuery.isError;
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([]);
}
return ( return (
<Dialog open={open} onOpenChange={(nextOpen) => { if (!nextOpen) onClose(); }}> <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"> <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"> <DialogHeader className="border-b border-border/70 px-5 pb-4 pt-5 pr-12">
<DialogTitle>Workspace management</DialogTitle> <DialogTitle>{titleReady ? "Workspace management" : ""}</DialogTitle>
<DialogDescription>Draft shared workspace definitions locally. Installation bindings and secrets stay outside this page.</DialogDescription> <DialogDescription>{titleReady ? "Draft bootstrap-only workspace definitions locally. Existing published descriptors stay read-only." : ""}</DialogDescription>
</DialogHeader> </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> <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"> <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"> <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> <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> <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"> <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> <span className="block truncate text-xs text-muted-foreground">{workspace.id}</span>
</button> </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> </div>
</nav> </nav>
<div className="min-w-0 overflow-y-auto px-5 py-5"> <div className="min-w-0 overflow-y-auto px-5 py-5">
{selectedSummaryIncomplete ? ( {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>}
<div className="rounded-md border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm"> {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>}
<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> {!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>}
</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>} {selectedSummary?.configurationState === "configuration_required" && activeBootstrapDraft && (
{!selectedSummaryIncomplete && !detailQuery.isError && (currentDraft || detailQuery.isLoading) && (
<> <>
{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 className="mb-5 flex flex-wrap items-start justify-between gap-3 border-b border-border/70 pb-4">
<div> <div>
<p className="thot-label">Workspace definition</p> <p className="thot-label">Workspace definition</p>
<h2 className="font-heading text-lg font-semibold">{currentDraft.workspace.workspace.name}</h2> <h2 className="font-heading text-lg font-semibold">{record.workspace.workspace.name}</h2>
<p className="font-mono text-xs text-muted-foreground">{currentDraft.workspaceId}</p> <p className="font-mono text-xs text-muted-foreground">{record.workspace.workspace.id}</p>
</div> </div>
<div className="flex flex-wrap gap-2"> <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" disabled={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={() => { void validateSelectedWorkspace(); }}><ClipboardCheck />Validate workspace</Button>
<Button size="sm" variant="outline" onClick={validateCurrent}><ClipboardCheck />Validate workspace</Button> <Button size="sm" variant="outline" onClick={() => { void testSelectedWorkspace(); }}><FlaskConical />Test on this installation</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>
</div> </div>
</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>} <WorkspaceEditor mode={{ kind: "read_only", catalog: selectedSummary, record: record as WorkspaceRecord }} />
{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>
</>}
</>
)} )}
</div> </div>
</div> </div>
</DialogContent> </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> </Dialog>
); );
} }
@@ -2,150 +2,65 @@ import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event"; import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw"; import { http, HttpResponse } from "msw";
import { beforeEach, expect, test, vi } from "vitest"; 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 { server } from "../test/msw";
import { WorkspacePublishDialog } from "./WorkspacePublishDialog"; import { WorkspacePublishDialog } from "./WorkspacePublishDialog";
const workspace: CanonicalWorkspace = { const workspace = {
workspace: { schema_version: 3, id: "psd-clinical", name: "PSD Clinical", language: "en" }, ...canonicalWorkspaceFixture("bootstrap-slot"),
dwh: { engine: "postgres", database: "clinical", schema: "datawarehouse", supported_transports: ["postgres_direct"] }, workspace: {
semantic_index: { ...canonicalWorkspaceFixture("bootstrap-slot").workspace,
vector_store: { engine: "qdrant", collection: "clinical", dimensions: 1024, distance: "cosine" }, name: "Bootstrap slot",
embedding: { provider: "ollama_internal", model: "qwen3-embedding:0.6b", dimensions: 1024 }, description: "Needs configuration",
}, },
llm_policy: { allowed: ["zai/glm-5.2"] },
}; };
const request: PublishWorkspaceRequest = { const request = {
action: "update", workspace, baseCommit: "a".repeat(40), baseBlob: "b".repeat(40), action: "create" as const,
}; workspace,
baseCommit: "a".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" } } },
},
}; };
beforeEach(() => { beforeEach(() => {
server.use(http.post("/api/workspaces/validate", () => HttpResponse.json({ workspace, contract: {} }))); 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 user = userEvent.setup();
const published = vi.fn(); const published = vi.fn();
let publishCalls = 0; let publishCalls = 0;
server.use(http.post("/api/workspaces/publish", () => { server.use(http.post("/api/workspaces/publish", () => {
publishCalls += 1; 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" })); await user.click(screen.getByRole("button", { name: "Validate draft" }));
expect(await screen.findByText("Workspace definition is valid." )).toBeVisible(); expect(await screen.findByText("Workspace definition is valid.")).toBeVisible();
await user.click(screen.getByRole("button", { name: "Publish" })); await user.click(screen.getByRole("button", { name: "Create workspace" }));
expect(screen.getByRole("heading", { name: "Confirm publication" })).toBeVisible(); expect(screen.getByRole("heading", { name: "Confirm workspace creation" })).toBeVisible();
expect(publishCalls).toBe(0); 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); expect(publishCalls).toBe(1);
}); });
test("shows a field-level conflict and never overwrites the remote workspace", async () => { test("surfaces a safe curator-owned refusal without showing conflict resolution UI", 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 () => {
const user = userEvent.setup(); const user = userEvent.setup();
server.use(http.post("/api/workspaces/publish", () => HttpResponse.json({ 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 }))); }, { 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(screen.getByRole("button", { name: "Validate draft" }));
await user.click(await screen.findByRole("button", { name: "Publish" })); await user.click(await screen.findByRole("button", { name: "Create workspace" }));
await user.click(screen.getByRole("button", { name: "Confirm publish" })); await user.click(screen.getByRole("button", { name: "Confirm create" }));
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(await screen.findByText("workspace_curator_owned: Existing descriptors are curator-owned.")).toBeVisible();
expect(screen.queryByText(/token=secret/)).not.toBeInTheDocument(); expect(screen.queryByText(/save revised draft|use your draft|use registry value/i)).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Reload workspace" })).toBeVisible();
}); });
+32 -156
View File
@@ -1,15 +1,11 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { import {
asWorkspaceApiError, asWorkspaceApiError,
asWorkspaceConflict,
publishWorkspace, publishWorkspace,
validateWorkspace, validateWorkspace,
type CanonicalWorkspace,
type PublishWorkspaceRequest, type PublishWorkspaceRequest,
type WorkspaceConflict,
type WorkspaceRevision, type WorkspaceRevision,
} from "../api/workspaces"; } from "../api/workspaces";
import type { WorkspaceDraft } from "../workspaces/drafts";
import { Button } from "../components/ui/button"; import { Button } from "../components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../components/ui/dialog"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../components/ui/dialog";
@@ -18,146 +14,31 @@ export interface WorkspacePublishDialogProps {
request: PublishWorkspaceRequest; request: PublishWorkspaceRequest;
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
onPublished: (revision: WorkspaceRevision | undefined) => 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 }) { 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">New workspace · 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">{label} · base {request.baseCommit.slice(0, 12)}</p>;
} }
function ConflictReview({ conflict, onPull, onReload, onResolved }: { export function WorkspacePublishDialog({ open, request, onOpenChange, onPublished }: WorkspacePublishDialogProps) {
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) {
const [validatedRequest, setValidatedRequest] = useState<PublishWorkspaceRequest>(); const [validatedRequest, setValidatedRequest] = useState<PublishWorkspaceRequest>();
const [confirmationOpen, setConfirmationOpen] = useState(false); const [confirming, setConfirming] = useState(false);
const [conflict, setConflict] = useState<WorkspaceConflict>();
const [message, setMessage] = useState<string>(); const [message, setMessage] = useState<string>();
const [publishing, setPublishing] = useState(false); const [publishing, setPublishing] = useState(false);
useEffect(() => { useEffect(() => {
if (!open) return; if (!open) return;
setValidatedRequest(undefined); setValidatedRequest(undefined);
setConfirmationOpen(false); setConfirming(false);
setConflict(undefined);
setMessage(undefined); setMessage(undefined);
setPublishing(false); setPublishing(false);
}, [open, request]); }, [open, request]);
async function validate() { async function validateDraft() {
setMessage(undefined); setMessage(undefined);
setConflict(undefined);
if (request.action === "delete") {
setValidatedRequest(request);
setMessage("Deletion is pinned to the published revision.");
return;
}
try { try {
const result = await validateWorkspace(request.workspace); const result = await validateWorkspace(request.workspace);
setValidatedRequest(requestWithWorkspace(request, result.workspace)); setValidatedRequest({ ...request, workspace: result.workspace });
setMessage("Workspace definition is valid."); setMessage("Workspace definition is valid.");
} catch (error) { } catch (error) {
const safe = asWorkspaceApiError(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; if (!validatedRequest) return;
setPublishing(true); setPublishing(true);
setMessage(undefined); setMessage(undefined);
@@ -174,43 +55,38 @@ export function WorkspacePublishDialog({ open, request, onOpenChange, onPublishe
onPublished(result?.revision); onPublished(result?.revision);
onOpenChange(false); onOpenChange(false);
} catch (error) { } catch (error) {
const detectedConflict = asWorkspaceConflict(error); const safe = asWorkspaceApiError(error);
if (detectedConflict) { setMessage(safe ? `${safe.code}: ${safe.message}` : "workspace_invalid: Publication could not be completed");
setConflict(detectedConflict); setConfirming(false);
setConfirmationOpen(false);
} else {
const safe = asWorkspaceApiError(error);
setMessage(safe ? `${safe.code}: ${safe.message}` : "workspace_invalid: Publication could not be completed");
}
} finally { } finally {
setPublishing(false); setPublishing(false);
} }
} }
return <Dialog open={open} onOpenChange={onOpenChange}> return (
<DialogContent showCloseButton={false} className="max-w-[min(94vw,46rem)] p-0"> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogHeader className="border-b border-border/70 px-5 pb-4 pt-5 pr-12"> <DialogContent showCloseButton={false} className="max-w-[min(94vw,46rem)] p-0">
<DialogTitle>{conflict ? "Publication conflict" : "Publish workspace"}</DialogTitle> <DialogHeader className="border-b border-border/70 px-5 pb-4 pt-5 pr-12">
<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> <DialogTitle>{confirming ? "Confirm workspace creation" : "Create workspace"}</DialogTitle>
</DialogHeader> <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>
<div className="grid gap-4 px-5 py-5"> </DialogHeader>
{conflict ? <ConflictReview conflict={conflict} onPull={onPull} onReload={onReload} onResolved={onResolved} /> : <> <div className="grid gap-4 px-5 py-5">
<RevisionSummary request={validatedRequest ?? request} /> <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>} {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"> {confirming ? (
<Button variant="outline" onClick={() => { void validate(); }}>Validate draft</Button> <DialogFooter>
<Button disabled={!validatedRequest} onClick={() => setConfirmationOpen(true)}>Publish</Button> <Button variant="outline" onClick={() => setConfirming(false)}>Cancel</Button>
</div> <Button onClick={() => { void createWorkspace(); }} disabled={publishing}>{publishing ? "Creating…" : "Confirm create"}</Button>
</>} </DialogFooter>
</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> <div className="flex flex-wrap justify-end gap-2">
</DialogContent> <Button variant="outline" onClick={() => { void validateDraft(); }}>Validate draft</Button>
<Dialog open={confirmationOpen} onOpenChange={setConfirmationOpen}> <Button disabled={!validatedRequest} onClick={() => setConfirming(true)}>Create workspace</Button>
<DialogContent showCloseButton={false} className="max-w-md"> </div>
<DialogHeader><DialogTitle>Confirm publication</DialogTitle><DialogDescription>This publishes the validated workspace definition to the shared Git registry.</DialogDescription></DialogHeader> )}
<RevisionSummary request={validatedRequest ?? request} /> </div>
<DialogFooter><Button variant="outline" onClick={() => setConfirmationOpen(false)}>Cancel</Button><Button onClick={() => { void publish(); }} disabled={publishing}>{publishing ? "Publishing…" : "Confirm publish"}</Button></DialogFooter> <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> </DialogContent>
</Dialog> </Dialog>
</Dialog>; );
} }
+23 -1
View File
@@ -1,4 +1,4 @@
import type { CanonicalWorkspace, WorkspaceRevision } from "../api/workspaces"; import type { CanonicalWorkspace, WorkspaceRevision, WorkspaceSummary } from "../api/workspaces";
export function canonicalWorkspaceFixture( export function canonicalWorkspaceFixture(
id: string, id: string,
@@ -29,3 +29,25 @@ export function workspaceRevisionFixture(id: string): WorkspaceRevision {
snapshotPath: `/snapshots/${"a".repeat(40)}/${id}.yaml`, snapshotPath: `/snapshots/${"a".repeat(40)}/${id}.yaml`,
}; };
} }
export function workspaceSummaryFixture(
id: string,
options: {
displayName?: string;
description?: string;
configurationState?: WorkspaceSummary["configurationState"];
revision?: WorkspaceRevision;
} = {},
): WorkspaceSummary {
const configurationState = options.configurationState ?? "ready";
const revision = options.revision ?? (configurationState === "ready" ? workspaceRevisionFixture(id) : undefined);
return {
id,
name: id,
file: `${id}/workspace.yaml`,
displayName: options.displayName ?? id,
...(options.description === undefined ? {} : { description: options.description }),
configurationState,
...(revision ? { revision } : {}),
};
}
+74 -228
View File
@@ -1,7 +1,10 @@
import { beforeEach, expect, test } from "vitest"; import { beforeEach, expect, test } from "vitest";
import type { CanonicalWorkspace } from "../api/workspaces"; import type { CanonicalWorkspace } from "../api/workspaces";
import { import {
sanitizeCanonicalWorkspace, workspaceDeletionDrafts, workspaceDrafts, workspacePreferences, sanitizeCanonicalWorkspace,
workspaceBootstrapDrafts,
workspacePreferences,
type WorkspaceBootstrapDraft,
} from "./drafts"; } from "./drafts";
const workspace: CanonicalWorkspace = { const workspace: CanonicalWorkspace = {
@@ -19,68 +22,29 @@ const workspace: CanonicalWorkspace = {
llm_policy: { allowed: ["zai/glm-5.2"] }, llm_policy: { allowed: ["zai/glm-5.2"] },
}; };
const bootstrapDraft: WorkspaceBootstrapDraft = {
workspaceId: "psd-clinical",
baseCommit: "a".repeat(40),
workspace,
updatedAt: "2026-08-04T10:00:00.000Z",
};
const policy = { max_chunk_chars: 8_000, retain_published_generations: 5 }; const policy = { max_chunk_chars: 8_000, retain_published_generations: 5 };
const evidenceWorkspaces = [ const evidenceWorkspace: CanonicalWorkspace = {
{ ...workspace,
name: "filesystem", evidence: {
workspace: { source: {
...workspace, type: "filesystem",
evidence: { uri: "psd-clinical/evidence",
source: { patterns: ["documents/**/*.pdf", "notes/*.md"],
type: "filesystem", max_bytes: 12_000_000,
uri: "workspace-content/psd-clinical/evidence", },
patterns: ["documents/**/*.pdf", "notes/*.md"], policy,
max_bytes: 12_000_000,
},
policy,
},
} satisfies CanonicalWorkspace,
}, },
{ };
name: "http",
workspace: { beforeEach(() => localStorage.clear());
...workspace,
evidence: {
source: {
type: "http",
uris: ["https://evidence.example/manifest.json", "http://evidence.example/files/list.txt"],
authentication: "signed_urls_file",
connect_timeout_ms: 2_000,
read_timeout_ms: 20_000,
max_bytes: 12_000_000,
max_redirects: 2,
allow_private_hosts: false,
max_cache_bytes: 24_000_000,
},
policy,
},
} satisfies CanonicalWorkspace,
},
{
name: "s3",
workspace: {
...workspace,
evidence: {
source: {
type: "s3",
uri: "s3://clinical-evidence/published/",
endpoint_url: "https://objects.example",
region: "eu-west-1",
credentials: "static_files",
trusted_endpoint: true,
allow_private_endpoint: false,
allow_insecure_endpoint: false,
max_bytes: 12_000_000,
max_objects: 2_000,
max_pages: 20,
page_size: 100,
},
policy,
},
} satisfies CanonicalWorkspace,
},
] as const;
test("keeps an anonymous user's model selection in browser storage", () => { test("keeps an anonymous user's model selection in browser storage", () => {
workspacePreferences.save({ workspacePreferences.save({
@@ -90,191 +54,73 @@ test("keeps an anonymous user's model selection in browser storage", () => {
expect(workspacePreferences.load()).toMatchObject({ model: "glm-5.2" }); expect(workspacePreferences.load()).toMatchObject({ model: "glm-5.2" });
}); });
test("reloads a canonical workspace draft and discards it by workspace ID", () => { test("reloads a bootstrap draft from the v2 browser-storage key and discards it by workspace ID", () => {
workspaceDrafts.save({ workspaceBootstrapDrafts.save(bootstrapDraft);
expect(workspaceBootstrapDrafts.load("psd-clinical")).toEqual(bootstrapDraft);
expect(localStorage.getItem("thothii.workspace-registry.v2.bootstrap.psd-clinical")).toContain('"baseCommit"');
expect(localStorage.getItem("thothii.workspace-registry.v2.bootstrap.psd-clinical")).not.toContain("baseBlob");
workspaceBootstrapDrafts.discard("psd-clinical");
expect(workspaceBootstrapDrafts.load("psd-clinical")).toBeUndefined();
});
test("purges known v1 update and deletion keys without touching unrelated localStorage", () => {
localStorage.setItem("thothii.workspace-registry.v1.draft.psd-clinical", JSON.stringify({
workspaceId: "psd-clinical", workspaceId: "psd-clinical",
baseCommit: "a".repeat(40), baseCommit: "a".repeat(40),
baseBlob: "b".repeat(40), baseBlob: "b".repeat(40),
workspace, workspace,
updatedAt: "2026-08-04T10:00:00.000Z", updatedAt: "2026-08-04T10:00:00.000Z",
}); }));
localStorage.setItem("thothii.workspace-registry.v1.delete.psd-clinical", JSON.stringify({
expect(workspaceDrafts.load("psd-clinical")).toMatchObject({
baseCommit: "a".repeat(40), workspace,
});
workspaceDrafts.discard("psd-clinical");
expect(workspaceDrafts.load("psd-clinical")).toBeUndefined();
});
test("persists a deletion draft without retaining a workspace definition", () => {
workspaceDeletionDrafts.save({
id: "psd-clinical", id: "psd-clinical",
baseCommit: "a".repeat(40), baseCommit: "a".repeat(40),
baseBlob: "b".repeat(40), baseBlob: "b".repeat(40),
updatedAt: "2026-08-04T10:00:00.000Z", updatedAt: "2026-08-04T10:00:00.000Z",
}); }));
localStorage.setItem("unrelated", "keep-me");
expect(workspaceDeletionDrafts.load("psd-clinical")).toEqual({ expect(workspaceBootstrapDrafts.load("psd-clinical")).toBeUndefined();
id: "psd-clinical", expect(localStorage.getItem("thothii.workspace-registry.v1.draft.psd-clinical")).toBeNull();
baseCommit: "a".repeat(40), expect(localStorage.getItem("thothii.workspace-registry.v1.delete.psd-clinical")).toBeNull();
expect(localStorage.getItem("unrelated")).toBe("keep-me");
});
test("rejects draft payloads that still carry baseBlob from the removed update flow", () => {
localStorage.setItem("thothii.workspace-registry.v2.bootstrap.psd-clinical", JSON.stringify({
...bootstrapDraft,
baseBlob: "b".repeat(40), baseBlob: "b".repeat(40),
updatedAt: "2026-08-04T10:00:00.000Z", }));
});
expect(localStorage.getItem("thothii.workspace-registry.v1.delete.psd-clinical")).not.toContain("PSD Clinical"); expect(workspaceBootstrapDrafts.load("psd-clinical")).toBeUndefined();
}); });
test("keeps valid canonical diagnostic configuration", () => { test("accepts only the workspace directory evidence root for filesystem sources", () => {
const configured = { const sanitized = sanitizeCanonicalWorkspace(evidenceWorkspace);
...workspace,
dwh: { ...workspace.dwh, supported_transports: ["postgres_direct", "rest_api"] }, expect(sanitized).toEqual(evidenceWorkspace);
diagnostics: { expect(sanitized).not.toBe(evidenceWorkspace);
dwh_rest: { expect(sanitized?.evidence).not.toBe(evidenceWorkspace.evidence);
method: "POST", });
path: "/rpc/ping",
auth: "bearer", test("rejects filesystem Evidence that still points at workspace-content", () => {
response: { database: "database", schema: "schema" }, const invalid: CanonicalWorkspace = {
...evidenceWorkspace,
evidence: {
source: {
type: "filesystem",
uri: "workspace-content/psd-clinical/evidence",
patterns: ["documents/**/*.pdf", "notes/*.md"],
max_bytes: 12_000_000,
}, },
policy,
}, },
} satisfies CanonicalWorkspace; };
workspaceDrafts.save({
workspaceId: "psd-clinical",
baseCommit: "a".repeat(40),
workspace: configured,
updatedAt: "2026-08-04T10:00:00.000Z",
});
expect(workspaceDrafts.load("psd-clinical")?.workspace.diagnostics).toEqual(configured.diagnostics);
});
beforeEach(() => localStorage.clear());
test.each([
["an unsupported schema version", { ...workspace, workspace: { ...workspace.workspace, schema_version: 1 } }],
["an invalid DWH engine", { ...workspace, dwh: { ...workspace.dwh, engine: "mysql" } }],
["a diagnostic path with a query", {
...workspace,
diagnostics: {
dwh_rest: {
method: "POST", path: "/rpc/ping?token=secret", auth: "bearer",
response: { database: "database", schema: "schema" },
},
},
}],
["a diagnostic path with a fragment", {
...workspace,
diagnostics: {
dwh_rest: {
method: "POST", path: "/rpc/ping#token", auth: "bearer",
response: { database: "database", schema: "schema" },
},
},
}],
["a diagnostic path outside the declared origin", {
...workspace,
diagnostics: {
dwh_rest: {
method: "POST", path: "https://outside.example/rpc/ping", auth: "bearer",
response: { database: "database", schema: "schema" },
},
},
}],
["an unknown secret field", { ...workspace, secret: "must-not-be-persisted" }],
])("rejects a draft with %s", (_reason, invalidWorkspace) => {
workspaceDrafts.save({
workspaceId: "psd-clinical",
baseCommit: "a".repeat(40),
workspace: invalidWorkspace as CanonicalWorkspace,
updatedAt: "2026-08-04T10:00:00.000Z",
});
expect(workspaceDrafts.load("psd-clinical")).toBeUndefined();
expect(localStorage.getItem("thothii.workspace-registry.v1.draft.psd-clinical")).toBeNull();
});
test("rejects a draft that tries to persist removed external semantic configuration fields", () => {
workspaceDrafts.save({
workspaceId: "psd-clinical",
baseCommit: "a".repeat(40),
workspace: {
...workspace,
semantic_index: {
vector_store: {
...workspace.semantic_index.vector_store,
database: "vectors",
},
embedding: workspace.semantic_index.embedding,
},
} as CanonicalWorkspace,
updatedAt: "2026-08-04T10:00:00.000Z",
});
expect(workspaceDrafts.load("psd-clinical")).toBeUndefined();
expect(localStorage.getItem("thothii.workspace-registry.v1.draft.psd-clinical")).toBeNull();
});
test.each(evidenceWorkspaces)("deep-sanitizes canonical $name Evidence", ({ workspace: configured }) => {
const sanitized = sanitizeCanonicalWorkspace(configured);
expect(sanitized).toEqual(configured);
expect(sanitized).not.toBe(configured);
expect(sanitized?.evidence).not.toBe(configured.evidence);
expect(sanitized?.evidence?.source).not.toBe(configured.evidence.source);
expect(sanitized?.evidence?.policy).not.toBe(configured.evidence.policy);
});
test.each(evidenceWorkspaces)("saves and reloads canonical $name Evidence", ({ workspace: configured }) => {
workspaceDrafts.save({
workspaceId: "psd-clinical",
baseCommit: "a".repeat(40),
workspace: configured,
updatedAt: "2026-08-04T10:00:00.000Z",
});
expect(workspaceDrafts.load("psd-clinical")?.workspace.evidence).toEqual(configured.evidence);
});
test.each([
["an unknown Evidence key", { ...evidenceWorkspaces[0].workspace.evidence, extra: "unexpected" }],
["a secret-shaped source key", {
...evidenceWorkspaces[1].workspace.evidence,
source: { ...evidenceWorkspaces[1].workspace.evidence.source, signed_urls_file: "/run/secrets/urls" },
}],
["an HTTP URI with credentials", {
...evidenceWorkspaces[1].workspace.evidence,
source: { ...evidenceWorkspaces[1].workspace.evidence.source, uris: ["https://user:secret@evidence.example/file"] },
}],
["an HTTP URI with a signed query", {
...evidenceWorkspaces[1].workspace.evidence,
source: { ...evidenceWorkspaces[1].workspace.evidence.source, uris: ["https://evidence.example/file?token=secret"] },
}],
["an unsafe S3 URI", {
...evidenceWorkspaces[2].workspace.evidence,
source: { ...evidenceWorkspaces[2].workspace.evidence.source, uri: "s3://user:secret@clinical-evidence/published/" },
}],
["an invalid zero policy value", {
...evidenceWorkspaces[0].workspace.evidence,
policy: { ...policy, max_chunk_chars: 0 },
}],
["an unsafe integer policy value", {
...evidenceWorkspaces[0].workspace.evidence,
policy: { ...policy, retain_published_generations: Number.MAX_SAFE_INTEGER + 1 },
}],
["a malformed source union", {
...evidenceWorkspaces[0].workspace.evidence,
source: { ...evidenceWorkspaces[0].workspace.evidence.source, uris: ["https://evidence.example/file"] },
}],
])("rejects %s instead of putting it in browser state", (_reason, evidence) => {
const invalid = { ...workspace, evidence };
expect(sanitizeCanonicalWorkspace(invalid)).toBeUndefined(); expect(sanitizeCanonicalWorkspace(invalid)).toBeUndefined();
workspaceBootstrapDrafts.save({ ...bootstrapDraft, workspace: invalid });
workspaceDrafts.save({ expect(workspaceBootstrapDrafts.load("psd-clinical")).toBeUndefined();
workspaceId: "psd-clinical",
baseCommit: "a".repeat(40),
workspace: invalid as CanonicalWorkspace,
updatedAt: "2026-08-04T10:00:00.000Z",
});
expect(workspaceDrafts.load("psd-clinical")).toBeUndefined();
}); });
test("continues to sanitize workspaces without Evidence", () => { test("continues to sanitize workspaces without Evidence", () => {
+72 -59
View File
@@ -4,21 +4,15 @@ import type {
} from "../api/workspaces"; } from "../api/workspaces";
export { workspacePreferences, type WorkspacePreference } from "./preferences"; export { workspacePreferences, type WorkspacePreference } from "./preferences";
export interface WorkspaceDraft { export interface WorkspaceBootstrapDraft {
workspaceId: string; workspaceId: string;
baseCommit: string; baseCommit: string;
baseBlob?: string;
workspace: CanonicalWorkspace; workspace: CanonicalWorkspace;
updatedAt: string; updatedAt: string;
} }
/** A publishable deletion intent; it deliberately carries no workspace body. */ /** @deprecated Use WorkspaceBootstrapDraft. */
export interface WorkspaceDeletionDraft { export type WorkspaceDraft = WorkspaceBootstrapDraft;
id: string;
baseCommit: string;
baseBlob: string;
updatedAt: string;
}
export const WORKSPACE_SUMMARY_ERROR = "Could not load workspace registry. Please retry."; export const WORKSPACE_SUMMARY_ERROR = "Could not load workspace registry. Please retry.";
export const WORKSPACE_POLICY_ERROR = "Could not load selected workspace policy. Please retry."; export const WORKSPACE_POLICY_ERROR = "Could not load selected workspace policy. Please retry.";
@@ -123,9 +117,9 @@ export const workspacePolicyGate = {
}, },
}; };
const PREFIX = "thothii.workspace-registry.v1"; const LEGACY_PREFIX = "thothii.workspace-registry.v1";
const DRAFT_PREFIX = `${PREFIX}.draft.`; const PREFIX = "thothii.workspace-registry.v2";
const DELETE_DRAFT_PREFIX = `${PREFIX}.delete.`; const DRAFT_PREFIX = `${PREFIX}.bootstrap.`;
function storage(): Storage | undefined { function storage(): Storage | undefined {
try { return window.localStorage; } catch { return undefined; } try { return window.localStorage; } catch { return undefined; }
@@ -234,7 +228,7 @@ function copyFilesystemEvidence(value: unknown, id: string): EvidenceSource | un
const maxBytes = positiveInteger(source?.max_bytes); const maxBytes = positiveInteger(source?.max_bytes);
if ( if (
source?.type !== "filesystem" source?.type !== "filesystem"
|| uri !== `workspace-content/${id}/evidence` || uri !== `${id}/evidence`
|| !Array.isArray(patterns) || !Array.isArray(patterns)
|| patterns.length === 0 || patterns.length === 0
|| !patterns.every((pattern) => typeof pattern === "string" && isSafeEvidencePattern(pattern)) || !patterns.every((pattern) => typeof pattern === "string" && isSafeEvidencePattern(pattern))
@@ -480,20 +474,47 @@ export function sanitizeCanonicalWorkspace(value: unknown): CanonicalWorkspace |
}; };
} }
function normalize(value: unknown): WorkspaceDraft | undefined { function repairBootstrapWorkspace(value: unknown, id: string): CanonicalWorkspace | undefined {
const source = exactRecord(value, ["workspaceId", "baseCommit", "baseBlob", "workspace", "updatedAt"]); const direct = sanitizeCanonicalWorkspace(value);
const workspace = sanitizeCanonicalWorkspace(source?.workspace); if (direct) return direct;
const source = exactRecord(value, [
"workspace", "dwh", "semantic_index", "llm_policy", "diagnostics", "evidence",
]);
const evidence = exactRecord(source?.evidence, ["source", "policy"]);
const evidenceSource = exactRecord(evidence?.source, ["type", "uri", "patterns", "max_bytes"]);
if (
source
&& evidence
&& evidenceSource?.type === "filesystem"
&& typeof evidenceSource.uri === "string"
&& /^[a-z][a-z0-9-]{2,62}\/evidence$/.test(evidenceSource.uri)
) {
return sanitizeCanonicalWorkspace({
...source,
evidence: {
...evidence,
source: {
...evidenceSource,
uri: `${id}/evidence`,
},
},
});
}
return undefined;
}
function normalize(value: unknown): WorkspaceBootstrapDraft | undefined {
const source = exactRecord(value, ["workspaceId", "baseCommit", "workspace", "updatedAt"]);
const id = workspaceId(source?.workspaceId); const id = workspaceId(source?.workspaceId);
const workspace = id ? repairBootstrapWorkspace(source?.workspace, id) : undefined;
const baseCommit = typeof source?.baseCommit === "string" && /^[0-9a-f]{40}$/.test(source.baseCommit) ? source.baseCommit : undefined; 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;
const updatedAt = typeof source?.updatedAt === "string" && Number.isFinite(Date.parse(source.updatedAt)) ? source.updatedAt : undefined; const updatedAt = typeof source?.updatedAt === "string" && Number.isFinite(Date.parse(source.updatedAt)) ? source.updatedAt : undefined;
if (!source || !workspace || !id || id !== workspace.workspace.id || !baseCommit || (source.baseBlob !== undefined && !baseBlob) || !updatedAt) { if (!source || !workspace || !id || id !== workspace.workspace.id || !baseCommit || !updatedAt) {
return undefined; return undefined;
} }
return { return {
workspaceId: id, workspaceId: id,
baseCommit, baseCommit,
...(baseBlob ? { baseBlob } : {}),
workspace, workspace,
updatedAt, updatedAt,
}; };
@@ -503,28 +524,21 @@ function key(id: string): string {
return `${DRAFT_PREFIX}${encodeURIComponent(id)}`; return `${DRAFT_PREFIX}${encodeURIComponent(id)}`;
} }
function deletionKey(id: string): string { function purgeLegacyRegistryDrafts(): void {
return `${DELETE_DRAFT_PREFIX}${encodeURIComponent(id)}`; const store = storage();
if (!store) return;
const keys = Array.from({ length: store.length }, (_, index) => store.key(index)).filter((value): value is string => value !== null);
for (const entry of keys) {
if (entry.startsWith(`${LEGACY_PREFIX}.draft.`) || entry.startsWith(`${LEGACY_PREFIX}.delete.`)) {
store.removeItem(entry);
}
}
} }
function normalizeDeletion(value: unknown): WorkspaceDeletionDraft | undefined { /** Browser-only bootstrap drafts. Saving or editing one never calls the server. */
const source = exactRecord(value, ["id", "baseCommit", "baseBlob", "updatedAt"]); export const workspaceBootstrapDrafts = {
const id = workspaceId(source?.id); load(id: string): WorkspaceBootstrapDraft | undefined {
const baseCommit = typeof source?.baseCommit === "string" && /^[0-9a-f]{40}$/.test(source.baseCommit) purgeLegacyRegistryDrafts();
? source.baseCommit
: undefined;
const baseBlob = typeof source?.baseBlob === "string" && /^[0-9a-f]{40}$/.test(source.baseBlob)
? source.baseBlob
: undefined;
const updatedAt = typeof source?.updatedAt === "string" && Number.isFinite(Date.parse(source.updatedAt))
? source.updatedAt
: undefined;
return id && baseCommit && baseBlob && updatedAt ? { id, baseCommit, baseBlob, updatedAt } : undefined;
}
/** Browser-only workspace drafts. Saving or editing one never calls the server. */
export const workspaceDrafts = {
load(id: string): WorkspaceDraft | undefined {
try { try {
const raw = storage()?.getItem(key(id)); const raw = storage()?.getItem(key(id));
return raw ? normalize(JSON.parse(raw)) : undefined; return raw ? normalize(JSON.parse(raw)) : undefined;
@@ -533,35 +547,34 @@ export const workspaceDrafts = {
} }
}, },
save(draft: WorkspaceDraft): void { save(draft: WorkspaceBootstrapDraft): void {
purgeLegacyRegistryDrafts();
const safe = normalize(draft); const safe = normalize(draft);
if (!safe) return; if (!safe) return;
try { storage()?.setItem(key(safe.workspaceId), JSON.stringify(safe)); } catch { /* storage is optional */ } try { storage()?.setItem(key(safe.workspaceId), JSON.stringify(safe)); } catch { /* storage is optional */ }
}, },
discard(id: string): void { discard(id: string): void {
purgeLegacyRegistryDrafts();
try { storage()?.removeItem(key(id)); } catch { /* storage is optional */ } try { storage()?.removeItem(key(id)); } catch { /* storage is optional */ }
}, },
}; };
/** Browser-only deletion drafts. Task 10 alone may publish one. */ /** @deprecated Use workspaceBootstrapDrafts. */
export const workspaceDrafts = workspaceBootstrapDrafts;
/** @deprecated Removed in P1.1; existing workspaces are curator-owned and deletions are not drafted in-browser. */
export interface WorkspaceDeletionDraft {
id: string;
baseCommit: string;
baseBlob: string;
updatedAt: string;
}
/** @deprecated Removed in P1.1; kept temporarily so legacy imports compile during the UI transition. */
export const workspaceDeletionDrafts = { export const workspaceDeletionDrafts = {
load(id: string): WorkspaceDeletionDraft | undefined { load(_id: string): WorkspaceDeletionDraft | undefined { return undefined; },
try { save(_draft: WorkspaceDeletionDraft): void {},
const raw = storage()?.getItem(deletionKey(id)); discard(_id: string): void {},
return raw ? normalizeDeletion(JSON.parse(raw)) : undefined;
} catch {
return undefined;
}
},
save(draft: WorkspaceDeletionDraft): void {
const safe = normalizeDeletion(draft);
if (!safe) return;
try { storage()?.setItem(deletionKey(safe.id), JSON.stringify(safe)); } catch { /* storage is optional */ }
},
discard(id: string): void {
try { storage()?.removeItem(deletionKey(id)); } catch { /* storage is optional */ }
},
}; };