308 lines
15 KiB
TypeScript
308 lines
15 KiB
TypeScript
import { useMemo, useState } from "react";
|
|
import { useQuery } from "@tanstack/react-query";
|
|
import { AlertCircle, CheckCircle2, ClipboardCheck, Download, FlaskConical, GitPullRequest, Upload, X } from "lucide-react";
|
|
import {
|
|
asWorkspaceApiError,
|
|
exportWorkspace,
|
|
getWorkspace,
|
|
getWorkspaceRegistryStatus,
|
|
importWorkspace,
|
|
listWorkspaces,
|
|
pullWorkspaceRegistry,
|
|
testWorkspace,
|
|
validateWorkspace,
|
|
type CanonicalWorkspace,
|
|
type PublishWorkspaceRequest,
|
|
type WorkspaceRecord,
|
|
type WorkspaceSummary,
|
|
} from "../api/workspaces";
|
|
import { workspaceBootstrapDrafts, type WorkspaceBootstrapDraft } from "../workspaces/drafts";
|
|
import { Button } from "../components/ui/button";
|
|
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "../components/ui/dialog";
|
|
import { WorkspaceEditor } from "./WorkspaceEditor";
|
|
import { WorkspacePublishDialog } from "./WorkspacePublishDialog";
|
|
|
|
const EMPTY_COMMIT = "0".repeat(40);
|
|
|
|
function QueryError({ name, message, retryLabel, onRetry }: {
|
|
name: string;
|
|
message: string;
|
|
retryLabel: string;
|
|
onRetry: () => void;
|
|
}) {
|
|
return <div role="alert" aria-label={name} className="grid gap-2 rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm"><p>{message}</p><div><Button size="sm" variant="outline" onClick={onRetry}>{retryLabel}</Button></div></div>;
|
|
}
|
|
|
|
function defaultBootstrapWorkspace(summary: WorkspaceSummary): CanonicalWorkspace {
|
|
return {
|
|
workspace: {
|
|
schema_version: 3,
|
|
id: summary.id,
|
|
name: summary.displayName,
|
|
...(summary.description ? { description: summary.description } : {}),
|
|
language: "en",
|
|
},
|
|
dwh: {
|
|
engine: "postgres",
|
|
database: "database",
|
|
schema: "public",
|
|
supported_transports: ["postgres_direct"],
|
|
},
|
|
semantic_index: {
|
|
vector_store: {
|
|
engine: "qdrant",
|
|
collection: summary.id.replaceAll("-", "_"),
|
|
dimensions: 1024,
|
|
distance: "cosine",
|
|
},
|
|
embedding: {
|
|
provider: "ollama_internal",
|
|
model: "qwen3-embedding:0.6b",
|
|
dimensions: 1024,
|
|
},
|
|
},
|
|
llm_policy: { allowed: ["zai/glm-5.2"], default: "zai/glm-5.2" },
|
|
};
|
|
}
|
|
|
|
function bootstrapDraftFor(summary: WorkspaceSummary, baseCommit: string): WorkspaceBootstrapDraft {
|
|
return {
|
|
workspaceId: summary.id,
|
|
baseCommit,
|
|
workspace: defaultBootstrapWorkspace(summary),
|
|
updatedAt: new Date().toISOString(),
|
|
};
|
|
}
|
|
|
|
export function WorkspaceManager({ open, onClose }: { open: boolean; onClose: () => void }) {
|
|
const [selectedId, setSelectedId] = useState<string>();
|
|
const [localDraft, setLocalDraft] = useState<WorkspaceBootstrapDraft>();
|
|
const [notice, setNotice] = useState<string>();
|
|
const [diagnostics, setDiagnostics] = useState<string[]>([]);
|
|
const [publishRequest, setPublishRequest] = useState<PublishWorkspaceRequest>();
|
|
const [transferring, setTransferring] = useState(false);
|
|
|
|
const statusQuery = useQuery({ queryKey: ["workspace-registry-status"], queryFn: getWorkspaceRegistryStatus, enabled: open });
|
|
const workspacesQuery = useQuery({ queryKey: ["workspaces"], queryFn: listWorkspaces, enabled: open });
|
|
const workspaces = workspacesQuery.data ?? [];
|
|
const selectedSummary = useMemo(() => workspaces.find((workspace) => workspace.id === selectedId), [selectedId, workspaces]);
|
|
const detailQuery = useQuery({
|
|
queryKey: ["workspace", selectedId],
|
|
queryFn: () => getWorkspace(selectedId!),
|
|
enabled: Boolean(open && selectedId && selectedSummary?.configurationState === "ready"),
|
|
});
|
|
const record = detailQuery.data;
|
|
|
|
const activeBootstrapDraft = selectedSummary?.configurationState === "configuration_required"
|
|
? (localDraft?.workspaceId === selectedSummary.id ? localDraft : workspaceBootstrapDrafts.load(selectedSummary.id) ?? bootstrapDraftFor(selectedSummary, statusQuery.data?.head ?? EMPTY_COMMIT))
|
|
: undefined;
|
|
|
|
function resetTransientState() {
|
|
setNotice(undefined);
|
|
setDiagnostics([]);
|
|
setPublishRequest(undefined);
|
|
}
|
|
|
|
function selectWorkspace(id: string) {
|
|
setSelectedId(id);
|
|
setLocalDraft(undefined);
|
|
resetTransientState();
|
|
}
|
|
|
|
function saveDraft(draft: WorkspaceBootstrapDraft) {
|
|
workspaceBootstrapDrafts.save(draft);
|
|
setLocalDraft(draft);
|
|
setSelectedId(draft.workspaceId);
|
|
setNotice("Draft saved in this browser.");
|
|
setDiagnostics([]);
|
|
}
|
|
|
|
function requestCreate(request: PublishWorkspaceRequest, draft: WorkspaceBootstrapDraft) {
|
|
workspaceBootstrapDrafts.save(draft);
|
|
setLocalDraft(draft);
|
|
setSelectedId(draft.workspaceId);
|
|
setNotice(undefined);
|
|
setDiagnostics([]);
|
|
setPublishRequest(request);
|
|
}
|
|
|
|
async function pullLatest() {
|
|
setNotice(undefined);
|
|
setDiagnostics([]);
|
|
try {
|
|
await pullWorkspaceRegistry();
|
|
await Promise.all([statusQuery.refetch(), workspacesQuery.refetch()]);
|
|
setNotice("Registry updated. Reload a workspace to review its latest revision.");
|
|
} catch (error) {
|
|
const safe = asWorkspaceApiError(error);
|
|
setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "git_unavailable: Registry pull could not be completed"]);
|
|
}
|
|
}
|
|
|
|
async function validateSelectedWorkspace() {
|
|
if (!record) return;
|
|
setNotice(undefined);
|
|
setDiagnostics([]);
|
|
try {
|
|
await validateWorkspace(record.workspace);
|
|
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 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"]);
|
|
}
|
|
}
|
|
|
|
async function downloadBundle() {
|
|
if (!record) return;
|
|
setTransferring(true);
|
|
setNotice(undefined);
|
|
setDiagnostics([]);
|
|
try {
|
|
const bundle = await exportWorkspace(record.workspace.workspace.id);
|
|
const url = URL.createObjectURL(bundle);
|
|
const link = document.createElement("a");
|
|
link.href = url;
|
|
link.download = `${record.workspace.workspace.id}.zip`;
|
|
link.click();
|
|
URL.revokeObjectURL(url);
|
|
setNotice("Workspace bundle downloaded.");
|
|
} catch (error) {
|
|
const safe = asWorkspaceApiError(error);
|
|
setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "workspace_invalid: Workspace bundle could not be exported"]);
|
|
} finally {
|
|
setTransferring(false);
|
|
}
|
|
}
|
|
|
|
async function importBundle(file: File | undefined) {
|
|
if (!file) return;
|
|
setTransferring(true);
|
|
setNotice(undefined);
|
|
setDiagnostics([]);
|
|
try {
|
|
const result = await importWorkspace(file);
|
|
const importedId = result.draft.workspace.workspace.id;
|
|
const catalog = workspaces.length > 0 ? workspaces : ((await workspacesQuery.refetch()).data ?? []);
|
|
const matchingSummary = catalog.find((workspace) => workspace.id === importedId && workspace.configurationState === "configuration_required");
|
|
if (!matchingSummary) {
|
|
setDiagnostics(["workspace_invalid: Imported bundle can only bootstrap a matching catalog slot"]);
|
|
return;
|
|
}
|
|
const draft: WorkspaceBootstrapDraft = {
|
|
workspaceId: importedId,
|
|
baseCommit: statusQuery.data?.head ?? EMPTY_COMMIT,
|
|
workspace: result.draft.workspace,
|
|
updatedAt: new Date().toISOString(),
|
|
};
|
|
workspaceBootstrapDrafts.save(draft);
|
|
setNotice("Imported bootstrap draft saved in this browser. Validate it before creating the descriptor.");
|
|
} catch (error) {
|
|
const safe = asWorkspaceApiError(error);
|
|
setDiagnostics([safe ? `${safe.code}: ${safe.message}` : "workspace_invalid: Workspace bundle could not be imported"]);
|
|
} finally {
|
|
setTransferring(false);
|
|
}
|
|
}
|
|
|
|
function published() {
|
|
if (publishRequest) {
|
|
workspaceBootstrapDrafts.discard(publishRequest.workspace.workspace.id);
|
|
setSelectedId(publishRequest.workspace.workspace.id);
|
|
setNotice(`To change this workspace, edit ${publishRequest.workspace.workspace.id}/workspace.yaml, commit/push, then Pull.`);
|
|
} else {
|
|
setNotice("Workspace created.");
|
|
}
|
|
setLocalDraft(undefined);
|
|
setPublishRequest(undefined);
|
|
setDiagnostics([]);
|
|
void Promise.all([statusQuery.refetch(), workspacesQuery.refetch()]).then(() => detailQuery.refetch());
|
|
}
|
|
|
|
const titleReady = workspacesQuery.isSuccess || workspacesQuery.isError;
|
|
|
|
return (
|
|
<Dialog open={open} onOpenChange={(nextOpen) => { if (!nextOpen) onClose(); }}>
|
|
<DialogContent showCloseButton={false} className="max-h-[min(90vh,54rem)] max-w-[min(94vw,74rem)] overflow-hidden p-0">
|
|
<DialogHeader className="border-b border-border/70 px-5 pb-4 pt-5 pr-12">
|
|
<DialogTitle>{titleReady ? "Workspace management" : ""}</DialogTitle>
|
|
<DialogDescription>{titleReady ? "Draft bootstrap-only workspace definitions locally. Existing published descriptors stay read-only." : ""}</DialogDescription>
|
|
</DialogHeader>
|
|
<button type="button" aria-label="Close workspace management" onClick={onClose} className="absolute right-3 top-3 grid size-7 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"><X className="size-4" /></button>
|
|
<div className="grid max-h-[calc(min(90vh,54rem)-6.75rem)] min-h-[32rem] grid-cols-[14rem_minmax(0,1fr)] overflow-hidden">
|
|
<nav aria-label="Workspaces" className="flex min-h-0 flex-col border-r border-border/70 bg-muted/30 p-3">
|
|
<label className="mb-2 inline-flex h-7 cursor-pointer items-center justify-center gap-1 rounded-md border border-input px-3 text-[0.8rem] font-semibold text-foreground shadow-xs hover:bg-muted has-[:disabled]:cursor-not-allowed has-[:disabled]:opacity-50"><Upload className="size-3.5" />Import bundle<input aria-label="Import workspace bundle" type="file" accept="application/zip,.zip" className="sr-only" disabled={transferring} onChange={(event) => { const file = event.currentTarget.files?.[0]; event.currentTarget.value = ""; void importBundle(file); }} /></label>
|
|
<Button size="sm" variant="outline" className="mb-3 w-full" disabled={transferring} onClick={() => { void pullLatest(); }}><GitPullRequest />Pull latest registry</Button>
|
|
<div className="min-h-0 flex-1 overflow-y-auto">
|
|
{workspacesQuery.isLoading ? <p className="p-2 text-xs text-muted-foreground">Loading workspaces…</p> : workspacesQuery.isError ? <QueryError name="Workspace list failed" message="Could not load workspaces." retryLabel="Retry workspace list" onRetry={() => { void workspacesQuery.refetch(); }} /> : workspaces.map((workspace) => (
|
|
<button key={workspace.id} type="button" aria-label={workspace.displayName} aria-current={selectedId === workspace.id ? "page" : undefined} onClick={() => selectWorkspace(workspace.id)} className="mb-1 w-full rounded-md px-2.5 py-2 text-left text-sm hover:bg-muted aria-[current=page]:bg-primary/10 aria-[current=page]:font-semibold">
|
|
<span className="block truncate">{workspace.displayName}</span>
|
|
<span className="block truncate text-xs text-muted-foreground">{workspace.id}</span>
|
|
</button>
|
|
))}
|
|
</div>
|
|
</nav>
|
|
|
|
<div className="min-w-0 overflow-y-auto px-5 py-5">
|
|
{notice && <p role="status" className="mb-4 flex items-center gap-2 rounded-md border border-border bg-muted/50 px-3 py-2 text-sm"><CheckCircle2 className="size-4 text-primary" />{notice}</p>}
|
|
{diagnostics.length > 0 && <div data-testid="workspace-diagnostics" aria-live="polite" className="mb-4 grid gap-1 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm">{diagnostics.map((diagnostic) => <p key={diagnostic} className="flex items-start gap-2"><AlertCircle className="mt-0.5 size-4 shrink-0 text-amber-700" />{diagnostic}</p>)}</div>}
|
|
|
|
{!selectedSummary && !workspacesQuery.isLoading && !workspacesQuery.isError && <div className="grid min-h-64 place-items-center text-center"><div><h3 className="font-heading font-semibold">Select a workspace</h3><p className="mt-1 text-sm text-muted-foreground">Review an existing definition or bootstrap a configuration-required slot.</p></div></div>}
|
|
|
|
{selectedSummary?.configurationState === "configuration_required" && activeBootstrapDraft && (
|
|
<>
|
|
<div className="mb-5 border-b border-border/70 pb-4">
|
|
<p className="thot-label">Bootstrap workspace</p>
|
|
<h2 className="font-heading text-lg font-semibold">{selectedSummary.displayName}</h2>
|
|
<p className="font-mono text-xs text-muted-foreground">{selectedSummary.id}</p>
|
|
</div>
|
|
<WorkspaceEditor
|
|
mode={{ kind: "bootstrap", catalog: selectedSummary, draft: activeBootstrapDraft }}
|
|
onSaveDraft={saveDraft}
|
|
onRequestCreate={publishRequest ? undefined : requestCreate}
|
|
/>
|
|
</>
|
|
)}
|
|
|
|
{selectedSummary?.configurationState === "ready" && (
|
|
detailQuery.isError ? <QueryError name="Workspace details failed" message="Could not load workspace details." retryLabel="Retry workspace details" onRetry={() => { void detailQuery.refetch(); }} /> : detailQuery.isLoading || !record ? <p className="text-sm text-muted-foreground">Loading workspace definition…</p> : (
|
|
<>
|
|
<div className="mb-5 flex flex-wrap items-start justify-between gap-3 border-b border-border/70 pb-4">
|
|
<div>
|
|
<p className="thot-label">Workspace definition</p>
|
|
<h2 className="font-heading text-lg font-semibold">{record.workspace.workspace.name}</h2>
|
|
<p className="font-mono text-xs text-muted-foreground">{record.workspace.workspace.id}</p>
|
|
</div>
|
|
<div className="flex flex-wrap gap-2">
|
|
<Button size="sm" variant="outline" disabled={transferring} onClick={() => { void downloadBundle(); }}><Download />Export workspace bundle</Button>
|
|
<Button size="sm" variant="outline" onClick={() => { void validateSelectedWorkspace(); }}><ClipboardCheck />Validate workspace</Button>
|
|
<Button size="sm" variant="outline" onClick={() => { void testSelectedWorkspace(); }}><FlaskConical />Test on this installation</Button>
|
|
</div>
|
|
</div>
|
|
<WorkspaceEditor mode={{ kind: "read_only", catalog: selectedSummary, record: record as WorkspaceRecord }} />
|
|
</>
|
|
)
|
|
)}
|
|
</div>
|
|
</div>
|
|
</DialogContent>
|
|
{publishRequest && <WorkspacePublishDialog open request={publishRequest} onOpenChange={(nextOpen) => { if (!nextOpen) setPublishRequest(undefined); }} onPublished={published} />}
|
|
</Dialog>
|
|
);
|
|
}
|