feat: store workspace preferences and drafts locally
This commit is contained in:
+28
-10
@@ -12,23 +12,36 @@ export class ApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
// Only declare a JSON content-type when we actually send a body. Body-less
|
||||
// POSTs (resume, close) would otherwise make Fastify reject the empty body
|
||||
// with FST_ERR_CTP_EMPTY_JSON_BODY (400).
|
||||
const headers: Record<string, string> = {
|
||||
...(init?.headers as Record<string, string> | undefined),
|
||||
};
|
||||
if (init?.body != null && !("content-type" in headers) && !("Content-Type" in headers)) {
|
||||
headers["content-type"] = "application/json";
|
||||
function requestHeaders(init: RequestInit | undefined): Headers {
|
||||
const headers = new Headers(init?.headers);
|
||||
// Fetch supplies the multipart boundary for FormData. Declaring JSON here
|
||||
// would prevent Fastify from parsing an imported workspace bundle.
|
||||
if (
|
||||
init?.body != null
|
||||
&& !(typeof FormData !== "undefined" && init.body instanceof FormData)
|
||||
&& !headers.has("content-type")
|
||||
) {
|
||||
headers.set("content-type", "application/json");
|
||||
}
|
||||
const res = await fetch(joinBackendPath(BASE, path), { ...init, headers });
|
||||
return headers;
|
||||
}
|
||||
|
||||
async function request(path: string, init?: RequestInit): Promise<Response> {
|
||||
const res = await fetch(joinBackendPath(BASE, path), { ...init, headers: requestHeaders(init) });
|
||||
if (!res.ok) {
|
||||
const bodyText = await res.text().catch(() => "");
|
||||
let payload: unknown;
|
||||
try { payload = bodyText ? JSON.parse(bodyText) : undefined; } catch { payload = undefined; }
|
||||
throw new ApiError(res.status, bodyText, payload);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
// Only declare a JSON content-type when we actually send a body. Body-less
|
||||
// POSTs (resume, close) would otherwise make Fastify reject the empty body
|
||||
// with FST_ERR_CTP_EMPTY_JSON_BODY (400).
|
||||
const res = await request(path, init);
|
||||
if (res.status === 204) return undefined as T;
|
||||
// Accepted fire-and-forget endpoints may legitimately return 202 with no
|
||||
// representation. Keep apiFetch useful for both 202 and 204 contracts.
|
||||
@@ -36,4 +49,9 @@ export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T>
|
||||
return body ? (JSON.parse(body) as T) : (undefined as T);
|
||||
}
|
||||
|
||||
/** Download registry bundles without attempting to parse their ZIP body as JSON. */
|
||||
export async function apiFetchBlob(path: string, init?: RequestInit): Promise<Blob> {
|
||||
return (await request(path, init)).blob();
|
||||
}
|
||||
|
||||
export { BASE };
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { apiFetch } from "./client";
|
||||
import { getSettings } from "./settings";
|
||||
import { workspacePreferences, type WorkspacePreference } from "../workspaces/preferences";
|
||||
import { workspacePreferences, type WorkspacePreference } from "../workspaces/drafts";
|
||||
import type {
|
||||
Principal, ResumeSessionResult, SessionScope, SessionSummary, SessionDocument, UiResponse,
|
||||
} from "./types";
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { server } from "../test/msw";
|
||||
import { importWorkspace } from "./workspaces";
|
||||
|
||||
test("uploads a workspace bundle without JSON content type", async () => {
|
||||
let contentType: string | null = null;
|
||||
server.use(http.post("http://localhost:8787/workspaces/import", ({ request }) => {
|
||||
contentType = request.headers.get("content-type");
|
||||
return HttpResponse.json({ draft: { workspace: {} } });
|
||||
}));
|
||||
|
||||
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);
|
||||
});
|
||||
@@ -1,4 +1,194 @@
|
||||
import { apiFetch } from "./client";
|
||||
import { ApiError, apiFetch, apiFetchBlob } from "./client";
|
||||
|
||||
export const listWorkspaces = () =>
|
||||
apiFetch<{ name: string; file: string }[]>("/workspaces");
|
||||
export type WorkspaceErrorCode =
|
||||
| "workspace_invalid" | "binding_missing" | "workspace_not_activatable"
|
||||
| "workspace_stale" | "workspace_conflict" | "git_unavailable"
|
||||
| "git_auth_failed" | "git_non_fast_forward" | "git_push_rejected"
|
||||
| "connector_unavailable" | "semantic_index_incompatible";
|
||||
|
||||
export interface RestDiagnosticRequest {
|
||||
method: "GET" | "POST";
|
||||
path: string;
|
||||
auth: "none" | "bearer" | "x-api-key";
|
||||
}
|
||||
|
||||
export interface CanonicalDiagnostics {
|
||||
dwh_rest?: RestDiagnosticRequest & { response: { database: string; schema: string } };
|
||||
vector_rest?: {
|
||||
metadata: RestDiagnosticRequest & { response: { collection: string; dimensions: string; distance: string } };
|
||||
reversible_probe?: RestDiagnosticRequest & { method: "POST"; auth: "bearer" | "x-api-key"; response: { operation: string } };
|
||||
};
|
||||
embedding?: RestDiagnosticRequest & { response: { model: string; dimensions: string } };
|
||||
}
|
||||
|
||||
export interface CanonicalWorkspace {
|
||||
workspace: {
|
||||
schema_version: 2;
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
language: "en" | "it";
|
||||
};
|
||||
dwh: {
|
||||
engine: "postgres";
|
||||
database: string;
|
||||
schema: string;
|
||||
port?: number;
|
||||
timeout_ms?: number;
|
||||
supported_transports: ("postgres_direct" | "rest_api" | "ssh_tunnel")[];
|
||||
};
|
||||
semantic_index: {
|
||||
vector_store: {
|
||||
engine: "pgvector";
|
||||
database: string;
|
||||
schema: string;
|
||||
collection: string;
|
||||
dimensions: number;
|
||||
distance: "cosine" | "l2" | "inner_product";
|
||||
port?: number;
|
||||
timeout_ms?: number;
|
||||
supported_transports: ("pgvector_direct" | "rest_api" | "ssh_tunnel")[];
|
||||
};
|
||||
vector_writer?: Record<string, never>;
|
||||
embedding: {
|
||||
provider: "ollama_compatible" | "openai_compatible";
|
||||
model: string;
|
||||
dimensions: number;
|
||||
timeout_ms?: number;
|
||||
};
|
||||
};
|
||||
llm_policy: { default?: `${string}/${string}`; allowed: `${string}/${string}`[] };
|
||||
diagnostics?: CanonicalDiagnostics;
|
||||
}
|
||||
|
||||
export interface WorkspaceRevision {
|
||||
id: string;
|
||||
commit: string;
|
||||
blob: string;
|
||||
snapshotPath: string;
|
||||
state: "operational" | "migration_required";
|
||||
}
|
||||
|
||||
export interface WorkspaceSummary {
|
||||
id: string;
|
||||
/** Kept for compatibility with the existing workspace selector. */
|
||||
name: string;
|
||||
file: string;
|
||||
displayName: string;
|
||||
description?: string;
|
||||
language: "en" | "it";
|
||||
revision: WorkspaceRevision;
|
||||
}
|
||||
|
||||
export interface WorkspaceRecord {
|
||||
workspace: CanonicalWorkspace;
|
||||
revision: WorkspaceRevision;
|
||||
}
|
||||
|
||||
export interface WorkspaceRegistryStatus {
|
||||
branch: string;
|
||||
head?: string;
|
||||
ahead: number;
|
||||
behind: number;
|
||||
degraded: boolean;
|
||||
lastError?: WorkspaceErrorCode;
|
||||
}
|
||||
|
||||
export interface WorkspaceDiagnostic {
|
||||
level: "error" | "warning" | "info";
|
||||
code: WorkspaceErrorCode | "binding_ok";
|
||||
field?: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface WorkspaceDiagnostics {
|
||||
activatable: boolean;
|
||||
diagnostics: WorkspaceDiagnostic[];
|
||||
}
|
||||
|
||||
export type PublishWorkspaceRequest =
|
||||
| { action: "create"; workspace: CanonicalWorkspace; baseCommit: string }
|
||||
| { action: "update"; workspace: CanonicalWorkspace; baseCommit: string; baseBlob: string }
|
||||
| { action: "delete"; id: string; baseCommit: string; baseBlob: string };
|
||||
|
||||
export interface WorkspaceConflict {
|
||||
code: "workspace_conflict";
|
||||
fields: string[];
|
||||
base: CanonicalWorkspace;
|
||||
local: CanonicalWorkspace;
|
||||
remote: CanonicalWorkspace;
|
||||
}
|
||||
|
||||
export interface WorkspaceApiError {
|
||||
status: number;
|
||||
code: WorkspaceErrorCode;
|
||||
message: string;
|
||||
fields?: string[];
|
||||
}
|
||||
|
||||
const workspaceErrorCodes = new Set<WorkspaceErrorCode>([
|
||||
"workspace_invalid", "binding_missing", "workspace_not_activatable", "workspace_stale",
|
||||
"workspace_conflict", "git_unavailable", "git_auth_failed", "git_non_fast_forward",
|
||||
"git_push_rejected", "connector_unavailable", "semantic_index_incompatible",
|
||||
]);
|
||||
|
||||
function object(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/** Sanitized registry error data; it intentionally excludes the raw response body. */
|
||||
export function asWorkspaceApiError(error: unknown): WorkspaceApiError | undefined {
|
||||
if (!(error instanceof ApiError)) return undefined;
|
||||
const payload = object(error.payload);
|
||||
const code = payload?.code;
|
||||
const message = payload?.message;
|
||||
if (typeof code !== "string" || !workspaceErrorCodes.has(code as WorkspaceErrorCode) || typeof message !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const fields = Array.isArray(payload?.fields) && payload.fields.every((field) => typeof field === "string")
|
||||
? payload.fields
|
||||
: undefined;
|
||||
return { status: error.status, code: code as WorkspaceErrorCode, message, ...(fields ? { fields } : {}) };
|
||||
}
|
||||
|
||||
/** Narrows a sanitized 409 payload without exposing ApiError's raw body. */
|
||||
export function asWorkspaceConflict(error: unknown): WorkspaceConflict | undefined {
|
||||
const safe = asWorkspaceApiError(error);
|
||||
if (safe?.code !== "workspace_conflict") return undefined;
|
||||
const payload = object((error as ApiError).payload);
|
||||
const fields = safe.fields;
|
||||
if (!payload || !fields || !object(payload.base) || !object(payload.local) || !object(payload.remote)) return undefined;
|
||||
return {
|
||||
code: "workspace_conflict",
|
||||
fields,
|
||||
base: payload.base as CanonicalWorkspace,
|
||||
local: payload.local as CanonicalWorkspace,
|
||||
remote: payload.remote as CanonicalWorkspace,
|
||||
};
|
||||
}
|
||||
|
||||
export const listWorkspaces = () => apiFetch<WorkspaceSummary[]>("/workspaces");
|
||||
export const getWorkspace = (id: string) => apiFetch<WorkspaceRecord>(`/workspaces/${encodeURIComponent(id)}`);
|
||||
export const getWorkspaceRegistryStatus = () => apiFetch<WorkspaceRegistryStatus>("/workspace-registry/status");
|
||||
export const pullWorkspaceRegistry = () => apiFetch<WorkspaceRegistryStatus>("/workspace-registry/pull", { method: "POST" });
|
||||
export const validateWorkspace = (workspace: CanonicalWorkspace) =>
|
||||
apiFetch<{ workspace: CanonicalWorkspace; contract: unknown }>("/workspaces/validate", {
|
||||
method: "POST", body: JSON.stringify({ workspace }),
|
||||
});
|
||||
export const testWorkspace = (id: string) =>
|
||||
apiFetch<WorkspaceDiagnostics>(`/workspaces/${encodeURIComponent(id)}/test`, { method: "POST" });
|
||||
export const publishWorkspace = (request: PublishWorkspaceRequest) =>
|
||||
apiFetch<{ revision: WorkspaceRevision } | undefined>("/workspaces/publish", {
|
||||
method: "POST", body: JSON.stringify(request),
|
||||
});
|
||||
export const exportWorkspace = (id: string) =>
|
||||
apiFetchBlob(`/workspaces/${encodeURIComponent(id)}/export`);
|
||||
export const importWorkspace = (bundle: File) => {
|
||||
const body = new FormData();
|
||||
body.set("bundle", bundle);
|
||||
return apiFetch<{ draft: { workspace: CanonicalWorkspace; contract?: unknown } }>("/workspaces/import", {
|
||||
method: "POST", body,
|
||||
});
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user