feat: establish unified administration and model context baseline
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
import { createContext, useContext, useEffect, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { listWorkspaces } from "../api/workspaces";
|
||||
import { listModels } from "../api/models";
|
||||
import { getSettings } from "../api/settings";
|
||||
import { workspacePreferences } from "./preferences";
|
||||
import { workspacePolicyGate } from "./drafts";
|
||||
|
||||
/** One validated operational context. Never substitute another model for an unavailable choice. */
|
||||
export function useWorkingContext() {
|
||||
const [preferences, setPreferences] = useState(() => workspacePreferences.load());
|
||||
useEffect(() => {
|
||||
const unsubscribe = workspacePreferences.subscribe(setPreferences);
|
||||
setPreferences(workspacePreferences.load());
|
||||
return unsubscribe;
|
||||
}, []);
|
||||
const settings = useQuery({ queryKey: ["settings"], queryFn: getSettings });
|
||||
const workspacesQuery = useQuery({ queryKey: ["workspaces"], queryFn: listWorkspaces });
|
||||
const modelsQuery = useQuery({ queryKey: ["models"], queryFn: listModels });
|
||||
const workspaces = (workspacesQuery.data ?? []).filter(workspace => workspace.revision);
|
||||
const models = modelsQuery.data?.models ?? [];
|
||||
const defaultWorkspace = settings.data?.workspace;
|
||||
useEffect(() => {
|
||||
if (!settings.data || !workspacesQuery.isSuccess) return;
|
||||
workspacePreferences.migrate({ workspaceId: defaultWorkspace, provider: settings.data.provider,
|
||||
model: settings.data.model, thinking: settings.data.thinking });
|
||||
}, [settings.data, workspacesQuery.isSuccess, defaultWorkspace]);
|
||||
const workspaceId = preferences.workspaceId ?? defaultWorkspace ?? "";
|
||||
const modelId = preferences.provider && preferences.model ? `${preferences.provider}/${preferences.model}`
|
||||
: settings.data?.provider && settings.data.model ? `${settings.data.provider}/${settings.data.model}` : "";
|
||||
const workspace = workspaces.find(item => item.id === workspaceId);
|
||||
const model = models.find(item => `${item.provider}/${item.id}` === modelId);
|
||||
const loading = settings.isPending || workspacesQuery.isPending || modelsQuery.isPending;
|
||||
const error = settings.isError || workspacesQuery.isError || modelsQuery.isError;
|
||||
// A failed background refresh must not unmount an editor and destroy its unsaved draft.
|
||||
// Initial failures still fail closed: no validated catalog/settings means no ready context.
|
||||
const ready = !loading && !!settings.data && !!workspace && !!model;
|
||||
useEffect(() => {
|
||||
if (!workspaceId) workspacePolicyGate.clear();
|
||||
else if (workspacesQuery.isPending) workspacePolicyGate.beginSummary(workspaceId);
|
||||
else if (!workspace) workspacePolicyGate.rejectSummary(workspaceId);
|
||||
else { workspacePolicyGate.select(workspaceId); workspacePolicyGate.resolve(workspaceId); }
|
||||
}, [workspaceId, workspace, workspacesQuery.isPending, workspacesQuery.isError]);
|
||||
return { preferences, workspaces, models, workspaceId, modelId, workspace, model, loading, error, ready,
|
||||
origins: workspacePreferences.origins(),
|
||||
retry: () => { void settings.refetch(); void workspacesQuery.refetch(); void modelsQuery.refetch(); } };
|
||||
}
|
||||
|
||||
export interface WorkingContextScope { workspaceId: string; ready: boolean; locked: boolean; administrationBusy?: boolean }
|
||||
export const WorkingContextContext = createContext<WorkingContextScope | null>(null);
|
||||
export const WorkingContextProvider = WorkingContextContext.Provider;
|
||||
// The optional scope keeps independently rendered management pages usable in their existing tests/tools.
|
||||
export function useWorkingContextScope() { return useContext(WorkingContextContext); }
|
||||
@@ -1,11 +1,40 @@
|
||||
import { beforeEach, expect, test, vi } from "vitest";
|
||||
import { workspacePreferences } from "./preferences";
|
||||
import { clearAuthState, setAuthState } from "../auth/authState";
|
||||
|
||||
const userA = {
|
||||
issuer: "local", subject: "preference-user-a", roles: ["user"] as const,
|
||||
permissions: ["session.use"], isAdmin: false, csrfToken: "a".repeat(43), session: null,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
clearAuthState();
|
||||
workspacePreferences.reset();
|
||||
});
|
||||
|
||||
test("remembers only explicit global model choices per user, independently of workspace", () => {
|
||||
setAuthState(userA);
|
||||
workspacePreferences.migrate({ workspaceId: "one", provider: "zai", model: "glm-5.3" });
|
||||
expect(localStorage.length).toBe(0);
|
||||
workspacePreferences.selectModel("local/qwen");
|
||||
workspacePreferences.save({ ...workspacePreferences.load(), workspaceId: "two" });
|
||||
workspacePreferences.reset();
|
||||
expect(workspacePreferences.load()).toEqual({ provider: "local", model: "qwen" });
|
||||
setAuthState({ ...userA, subject: "preference-user-b" });
|
||||
expect(workspacePreferences.load()).toEqual({});
|
||||
workspacePreferences.migrate({ provider: "zai", model: "glm-5.3" });
|
||||
setAuthState(userA);
|
||||
expect(workspacePreferences.load()).toEqual({ provider: "local", model: "qwen" });
|
||||
});
|
||||
|
||||
test("Admin-first initialization can later receive workspace defaults without replacing its model", () => {
|
||||
workspacePreferences.migrate({ provider: "local", model: "qwen" });
|
||||
workspacePreferences.selectModel("zai/glm-5.3");
|
||||
expect(workspacePreferences.migrate({ workspaceId: "psd", provider: "local", model: "qwen", thinking: "medium" }))
|
||||
.toEqual({ workspaceId: "psd", provider: "zai", model: "glm-5.3", thinking: "medium" });
|
||||
});
|
||||
|
||||
test("keeps selections only in current application memory", () => {
|
||||
localStorage.setItem("unrelated", "keep-me");
|
||||
workspacePreferences.save({
|
||||
@@ -50,3 +79,34 @@ test("notifies shell consumers when the selected workspace changes", () => {
|
||||
expect(listener).toHaveBeenCalledTimes(2);
|
||||
expect(listener).toHaveBeenLastCalledWith({ workspaceId: "catalog-two" });
|
||||
});
|
||||
|
||||
test("remembers workspace and model independently, ahead of defaults, per principal", () => {
|
||||
setAuthState(userA);
|
||||
workspacePreferences.migrate({ workspaceId: "default", provider: "zai", model: "glm-5.3" });
|
||||
expect(workspacePreferences.origins()).toEqual({ workspace: "Installation default", model: "Installation default" });
|
||||
workspacePreferences.selectWorkspace("research");
|
||||
workspacePreferences.selectModel("deepseek/deepseek-v4-pro");
|
||||
workspacePreferences.selectWorkspace("clinical");
|
||||
workspacePreferences.reset();
|
||||
expect(workspacePreferences.migrate({ workspaceId: "default", provider: "zai", model: "glm-5.3" }))
|
||||
.toMatchObject({ workspaceId: "clinical", provider: "deepseek", model: "deepseek-v4-pro" });
|
||||
expect(workspacePreferences.origins()).toEqual({ workspace: "Last choice", model: "Last choice" });
|
||||
setAuthState({ ...userA, subject: "another-user" });
|
||||
expect(workspacePreferences.load()).toEqual({});
|
||||
});
|
||||
|
||||
test("isolates remembered context between application mounts", () => {
|
||||
setAuthState(userA);
|
||||
const original = location.href;
|
||||
try {
|
||||
history.replaceState(null, "", "/portal-one");
|
||||
workspacePreferences.selectWorkspace("research");
|
||||
workspacePreferences.selectModel("local/qwen");
|
||||
history.replaceState(null, "", "/portal-two");
|
||||
workspacePreferences.reset();
|
||||
expect(workspacePreferences.load()).toEqual({});
|
||||
history.replaceState(null, "", "/portal-one");
|
||||
workspacePreferences.reset();
|
||||
expect(workspacePreferences.load()).toEqual({ workspaceId: "research", provider: "local", model: "qwen" });
|
||||
} finally { history.replaceState(null, "", original); }
|
||||
});
|
||||
|
||||
@@ -8,19 +8,52 @@ export interface WorkspacePreference {
|
||||
let current: WorkspacePreference | undefined;
|
||||
const listeners = new Set<(value: WorkspacePreference) => void>();
|
||||
|
||||
function modelStorageKey(): string | undefined {
|
||||
const user = getAuthState();
|
||||
// localStorage is already origin-scoped. Include application mount and principal, not
|
||||
// workspace: selecting another workspace must never select another LLM.
|
||||
return user ? `thothii:interaction-model:v1:${location.pathname}:${JSON.stringify([user.issuer, user.subject])}` : undefined;
|
||||
}
|
||||
|
||||
function rememberedModel(): Partial<WorkspacePreference> {
|
||||
try {
|
||||
const key = modelStorageKey();
|
||||
const id: unknown = key ? JSON.parse(localStorage.getItem(key) ?? "null") : null;
|
||||
if (typeof id !== "string" || !/^[a-z][a-z0-9._-]{0,63}\/[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(id)) return {};
|
||||
const slash = id.indexOf("/");
|
||||
return { provider: id.slice(0, slash), model: id.slice(slash + 1) };
|
||||
} catch { return {}; }
|
||||
}
|
||||
|
||||
function workspaceStorageKey(): string | undefined {
|
||||
return modelStorageKey()?.replace("interaction-model:v1", "workspace:v1");
|
||||
}
|
||||
function rememberedWorkspace(): Partial<WorkspacePreference> {
|
||||
try {
|
||||
const key = workspaceStorageKey();
|
||||
const id: unknown = key ? JSON.parse(localStorage.getItem(key) ?? "null") : null;
|
||||
return typeof id === "string" && id.length > 0 && id.length <= 256 ? { workspaceId: id } : {};
|
||||
} catch { return {}; }
|
||||
}
|
||||
|
||||
subscribeAuthState(() => {
|
||||
current = undefined;
|
||||
notify();
|
||||
});
|
||||
|
||||
function snapshot(value: WorkspacePreference | undefined): WorkspacePreference {
|
||||
return value === undefined ? {} : { ...value };
|
||||
}
|
||||
|
||||
function notify(): void {
|
||||
const value = snapshot(current);
|
||||
const value = { ...rememberedWorkspace(), ...rememberedModel(), ...snapshot(current) };
|
||||
for (const listener of listeners) listener(value);
|
||||
}
|
||||
|
||||
/** Ephemeral workspace choices for the current application process. */
|
||||
/** Shared context: explicit workspace/model choices are independently remembered per user/mount. */
|
||||
export const workspacePreferences = {
|
||||
load(): WorkspacePreference {
|
||||
return snapshot(current);
|
||||
return { ...rememberedWorkspace(), ...rememberedModel(), ...snapshot(current) };
|
||||
},
|
||||
|
||||
save(value: WorkspacePreference): WorkspacePreference {
|
||||
@@ -29,10 +62,39 @@ export const workspacePreferences = {
|
||||
return snapshot(current);
|
||||
},
|
||||
|
||||
/** Seed current memory from backend installation settings only before the first local choice. */
|
||||
/** The only explicit operational LLM choice, shared by Core and Administration. */
|
||||
selectModel(id: string): WorkspacePreference {
|
||||
const slash = id.indexOf("/");
|
||||
if (slash <= 0 || slash === id.length - 1) throw new Error("Invalid model identity");
|
||||
const value = { ...this.load(), provider: id.slice(0, slash), model: id.slice(slash + 1) };
|
||||
try {
|
||||
const key = modelStorageKey();
|
||||
if (key) localStorage.setItem(key, JSON.stringify(id));
|
||||
} catch { /* Keep this visit usable when browser storage is disabled. */ }
|
||||
return this.save(value);
|
||||
},
|
||||
|
||||
selectWorkspace(workspaceId: string): WorkspacePreference {
|
||||
try {
|
||||
const key = workspaceStorageKey();
|
||||
if (key) localStorage.setItem(key, JSON.stringify(workspaceId));
|
||||
} catch { /* Preserve this visit's selection even without browser storage. */ }
|
||||
return this.save({ ...this.load(), workspaceId });
|
||||
},
|
||||
|
||||
origins() {
|
||||
return {
|
||||
workspace: rememberedWorkspace().workspaceId ? "Last choice" : "Installation default",
|
||||
model: rememberedModel().model ? "Last choice" : "Installation default",
|
||||
};
|
||||
},
|
||||
|
||||
/** Fill missing context fields without overwriting explicit choices, including Admin-first entry. */
|
||||
migrate(settings: WorkspacePreference): WorkspacePreference {
|
||||
if (current === undefined) {
|
||||
current = { ...settings };
|
||||
const selected = this.load();
|
||||
const next = { ...settings, ...selected };
|
||||
if (JSON.stringify(current) !== JSON.stringify(next)) {
|
||||
current = next;
|
||||
notify();
|
||||
}
|
||||
return snapshot(current);
|
||||
@@ -49,3 +111,4 @@ export const workspacePreferences = {
|
||||
notify();
|
||||
},
|
||||
};
|
||||
import { getAuthState, subscribeAuthState } from "../auth/authState";
|
||||
|
||||
Reference in New Issue
Block a user