Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions web/src/components/settings/SecretField.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ describe("SecretField", () => {
expect(onChange).toHaveBeenCalledWith("");
});

it("does not treat an empty input as a keep while nothing is saved", async () => {
it("goes back to nothing staged when an input with nothing saved is emptied", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const onKeep = vi.fn();
Expand All @@ -119,8 +119,8 @@ describe("SecretField", () => {
const input = screen.getByLabelText("Secret key");
await user.type(input, "x");
await user.clear(input);
expect(onKeep).not.toHaveBeenCalled();
expect(onChange).toHaveBeenCalledWith("");
expect(onKeep).toHaveBeenCalled();
expect(onChange).not.toHaveBeenCalledWith("");
});

it("offers no clear action while the field is read-only", () => {
Expand Down
14 changes: 8 additions & 6 deletions web/src/components/settings/SecretField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ export interface SecretFieldProps {
configured: boolean;
onChange: (value: string) => void;
/**
* Called when the input is emptied while a saved value exists, so a
* settings-form parent can revert the staged draft (`form.resetValue`)
* instead of staging `""` — a dirty `""` would clear the secret on save.
* Draft-based parents that already skip empty values may omit it.
* Called when the input is emptied, so a settings-form parent can revert the
* staged draft (`form.resetValue`) instead of staging `""`: a dirty `""`
* would clear a saved secret on save, and with none saved it would leave an
* empty change behind. Draft-based parents that already skip empty values
* may omit it.
*/
onKeep?: () => void;
/**
Expand Down Expand Up @@ -99,8 +100,9 @@ export function SecretField({
}

function handleChange(next: string) {
if (next === "" && configured) {
// Emptying the field means "keep the saved secret", never "clear it".
if (next === "") {
// Emptying the field goes back to what is saved: it keeps a saved
// secret, never clears it, and with none saved it leaves nothing staged.
keepSaved();
return;
}
Expand Down
61 changes: 56 additions & 5 deletions web/src/hooks/useSettingsForm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import { useHasUnsavedChanges } from "./useUnsavedChanges";
import { useSettingsForm } from "./useSettingsForm";
import { useStepSubmit } from "@/pages/setup-wizard/useStep";

const { mutateAsync, markDone, snapshot, authority } = vi.hoisted(() => ({
const { mutateAsync, markDone, snapshot, authority, saveBaseline } = vi.hoisted(() => ({
mutateAsync: vi.fn(),
// The snapshot the next save is guarded against.
saveBaseline: { current: undefined as Record<string, string> | undefined },
markDone: vi.fn(),
snapshot: { loaded: true, values: undefined as Record<string, string> | undefined },
authority: { profileId: "profile-a" },
Expand All @@ -29,15 +31,18 @@ vi.mock("@/api/client", () => ({
// would loop forever.
const KEYS = ["branding.server_name", "database.max_connections"];
const settingsData = { "branding.server_name": "Silo", "database.max_connections": "20" };
const sensitiveData = { configured: [], managed_by_env: [] };
const sensitiveData = { configured: [] as string[], managed_by_env: [] };

vi.mock("@/hooks/queries/admin/settings", () => ({
useAdminServerSettings: () => ({
data: snapshot.loaded ? (snapshot.values ?? settingsData) : undefined,
isLoading: false,
}),
useAdminSensitiveStatus: () => ({ data: sensitiveData }),
useUpdateServerSettings: () => ({ mutateAsync, isPending: false }),
useUpdateServerSettings: (baseline: Record<string, string> | undefined) => {
saveBaseline.current = baseline;
return { mutateAsync, isPending: false };
},
}));

afterEach(() => {
Expand All @@ -47,6 +52,7 @@ afterEach(() => {
snapshot.loaded = true;
snapshot.values = undefined;
authority.profileId = "profile-a";
sensitiveData.configured = [];
});

describe("useSettingsForm save()", () => {
Expand Down Expand Up @@ -339,10 +345,42 @@ describe("useSettingsForm unsaved-changes guard", () => {
expect(registry.result.current).toBe(false);
});

it("guards the next save with the current snapshot after an edit is undone in place", () => {
const before = { "branding.server_name": "Silo" };
snapshot.values = before;
const form = renderHook(() =>
useSettingsForm({ keys: ["branding.server_name", "branding.accent_color"] }),
);

// The Default accent with none saved: nothing to stage.
act(() => {
form.result.current.setValue("branding.accent_color", "");
});
expect(form.result.current.dirtyCount).toBe(0);

// Another write (a branding upload) moves the settings on.
const after = { "branding.server_name": "Silo", "branding.logo_ref": "logo" };
snapshot.values = after;
form.rerender();
act(() => {
form.result.current.setValue("branding.server_name", "Casa");
});

expect(saveBaseline.current).toBe(after);
});

it("releases an edit changed back to its saved value, but not a staged secret clear", () => {
sensitiveData.configured = ["email.smtp_password"];
const registry = renderHook(() => useHasUnsavedChanges());
const form = renderHook(() =>
useSettingsForm({ keys: ["branding.server_name", "email.smtp_password"] }),
useSettingsForm({
keys: [
"branding.server_name",
"email.smtp_password",
"s3.public_read_endpoint",
"s3.public_token_secret",
],
}),
);

act(() => {
Expand All @@ -354,7 +392,20 @@ describe("useSettingsForm unsaved-changes guard", () => {
expect(form.result.current.dirtyCount).toBe(0);
expect(registry.result.current).toBe(false);

// The snapshot leaves secrets out, so an empty secret is a clear to save.
// The snapshot leaves out a setting with nothing saved, secret or not, so
// emptying what was typed into one gets it back to its saved state.
for (const key of ["s3.public_read_endpoint", "s3.public_token_secret"]) {
act(() => {
form.result.current.setValue(key, "typed");
});
act(() => {
form.result.current.setValue(key, "");
});
}
expect(form.result.current.dirtyCount).toBe(0);
expect(registry.result.current).toBe(false);

// It leaves out a set secret too, and emptying that is a clear to save.
act(() => {
form.result.current.setValue("email.smtp_password", "");
});
Expand Down
37 changes: 27 additions & 10 deletions web/src/hooks/useSettingsForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,25 +130,21 @@ export function useSettingsForm({ keys }: UseSettingsFormOptions) {
if (!editBaseline.current) editBaseline.current = settings;
Comment thread
Quick104 marked this conversation as resolved.
Resolved
editVersions.current.set(key, (editVersions.current.get(key) ?? 0) + 1);
setLocalValues((prev) => ({ ...prev, [key]: value }));
// The snapshot leaves secrets out, so a key it lacks (a staged secret
// clear among them) stays dirty. An edit made during a save, or before
// the snapshot that save wrote has arrived, stays dirty too, because the
// snapshot cannot yet say what is saved.
// An edit made during a save, or before the snapshot that save wrote has
// arrived, stays dirty, because the snapshot cannot yet say what is saved.
const reverted =
!stage &&
!savePending.current &&
settings != null &&
settings !== savedOver.current &&
Object.hasOwn(settings, key) &&
settings[key] === value;
savedValue(settings, sensitiveData?.configured, key) === value;
setDirty((prev) => {
const next = new Set(prev);
if (reverted) next.delete(key);
else next.add(key);
return next;
});
},
[settings],
[sensitiveData, settings],
);

// Revert one staged field without disturbing other edits. This is also how
Expand All @@ -168,9 +164,12 @@ export function useSettingsForm({ keys }: UseSettingsFormOptions) {
);

const dirtyCount = dirty.size;
// With nothing staged, the next edit starts its own baseline. This runs on
// every change of the set, so an edit undone in place (an emptied setting
// with nothing saved) doesn't leave the baseline on the snapshot it began on.
useEffect(() => {
if (dirtyCount === 0) editBaseline.current = undefined;
}, [dirtyCount]);
if (dirty.size === 0) editBaseline.current = undefined;
}, [dirty]);
const dirtyKeys = useMemo(() => Array.from(dirty), [dirty]);

// The shared registry guards tab close and reload. `UnsavedChangesGuard`
Expand Down Expand Up @@ -358,3 +357,21 @@ export function useSettingsForm({ keys }: UseSettingsFormOptions) {
beginSettingsTransition,
};
}

/**
* What is saved for `key`, or undefined when the snapshot and the secret
* status can't say. A key the snapshot lacks has nothing saved, unless it is a
* set secret, which the snapshot leaves out; for that, or before the status
* (`configured`) has arrived, the saved value is unknown, and an empty draft is
* a clear to save.
*/
function savedValue(
settings: Record<string, string> | undefined,
configured: string[] | undefined,
key: string,
): string | undefined {
if (settings == null) return undefined;
if (Object.hasOwn(settings, key)) return settings[key];
if (configured == null || configured.includes(key)) return undefined;
return "";
}
53 changes: 26 additions & 27 deletions web/src/pages/admin-settings/AISettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,10 @@ const SPEECH_AI_KEYS = ["ai.speech_provider_id", "ai.asr_model"] as const;
const EMBEDDING_KEYS = ["recommendations.embedding_provider_id", "recommendations.embedding_model"];
/**
* Pre-`ai.*` keys still read as a fallback, so a server configured before the
* rename keeps its model and job limit until the modern key is saved.
* rename keeps its model until the modern key is saved. The server already
* reports the job limit under `ai.max_concurrent_jobs`.
*/
const LEGACY_AI_KEYS = ["subtitle_ai.chat_model", "subtitle_ai.max_concurrent_jobs"] as const;
const LEGACY_AI_KEYS = ["subtitle_ai.chat_model"] as const;

const AI_FEATURE_KEYS = [
"subtitle_ai.enabled",
Expand Down Expand Up @@ -671,10 +672,6 @@ export default function AISettings() {
}

const value = (key: string, fallback = "") => form.getValue(key) || fallback;
// Legacy `subtitle_ai.*` values stay authoritative until the modern `ai.*`
// key holds something, exactly as the old AI Services tab read them.
const effectiveValue = (key: string, legacyKey: string, fallback: string) =>
value(key, value(legacyKey, fallback));

const providers = providerList.data?.providers ?? [];
const providerTypes = providerList.data?.types ?? [];
Expand Down Expand Up @@ -801,13 +798,19 @@ export default function AISettings() {
}

async function save() {
const batchSize = parseStrictInteger(value("subtitle_ai.batch_size", "40"));
const contextLines = parseStrictInteger(value("subtitle_ai.context_neighbors", "2"));
const chunkSeconds = parseStrictInteger(value("subtitle_ai.asr_chunk_seconds", "600"));
const quotaJobs = parseStrictInteger(value("subtitle_ai.transcribe_quota_jobs", "0"));
const maxConcurrent = parseStrictInteger(
effectiveValue("ai.max_concurrent_jobs", "subtitle_ai.max_concurrent_jobs", "2"),
);
// With no settings loaded there is nothing to save over, and the form's
// own save says to reload; checking the fields first would hide that.
if (!form.loaded) {
await form.save();
return;
}
// Only a value this save sends is checked: an untouched field holds what
// the server has.
const invalidCount = (key: string, min: number, max = Number.MAX_SAFE_INTEGER) => {
Comment thread
Quick104 marked this conversation as resolved.
Resolved
if (!form.isDirty(key)) return false;
const parsed = parseStrictInteger(value(key));
return parsed === null || parsed < min || parsed > max;
};

// None releases the text provider; it saves while nothing translates.
const textCleared = authMode !== "chatgpt" && textProviderID === "";
Expand All @@ -830,23 +833,23 @@ export default function AISettings() {
toast.error(t("web.admin.settings.ai.page.chooseReasoning"));
return;
}
if (maxConcurrent === null || maxConcurrent < 1) {
if (invalidCount("ai.max_concurrent_jobs", 1)) {
toast.error(t("web.admin.settings.ai.page.maxConcurrentInvalid"));
return;
}
if (batchSize === null || batchSize < 1) {
if (invalidCount("subtitle_ai.batch_size", 1)) {
toast.error(t("web.admin.settings.ai.page.batchSizeInvalid"));
return;
}
if (contextLines === null || contextLines < 0) {
if (invalidCount("subtitle_ai.context_neighbors", 0)) {
toast.error(t("web.admin.settings.ai.page.contextLinesInvalid"));
return;
}
if (chunkSeconds === null || chunkSeconds < 60 || chunkSeconds > 600) {
if (invalidCount("subtitle_ai.asr_chunk_seconds", 60, 600)) {
toast.error(t("web.admin.settings.ai.page.chunkInvalid"));
return;
}
if (quotaJobs === null || quotaJobs < 0) {
if (invalidCount("subtitle_ai.transcribe_quota_jobs", 0)) {
toast.error(t("web.admin.settings.ai.page.quotaInvalid"));
return;
}
Expand Down Expand Up @@ -1033,11 +1036,7 @@ export default function AISettings() {
<SettingField
label={t("web.admin.settings.ai.tuning.jobsAtOnce")}
type="number"
value={effectiveValue(
"ai.max_concurrent_jobs",
"subtitle_ai.max_concurrent_jobs",
"2",
)}
value={value("ai.max_concurrent_jobs")}
onChange={(next) => setValue("ai.max_concurrent_jobs", next)}
// Each server process builds its own dispatch semaphore at start
// (internal/api/router.go), so a cluster runs this many per process.
Expand All @@ -1047,22 +1046,22 @@ export default function AISettings() {
<SettingField
label={t("web.admin.settings.ai.tuning.batchSize")}
type="number"
value={value("subtitle_ai.batch_size", "40")}
value={value("subtitle_ai.batch_size")}
onChange={(next) => setValue("subtitle_ai.batch_size", next)}
restartRequired={restartKeys.has("subtitle_ai.batch_size")}
/>
<SettingField
label={t("web.admin.settings.ai.tuning.contextLines")}
type="number"
value={value("subtitle_ai.context_neighbors", "2")}
value={value("subtitle_ai.context_neighbors")}
onChange={(next) => setValue("subtitle_ai.context_neighbors", next)}
restartRequired={restartKeys.has("subtitle_ai.context_neighbors")}
/>
<SettingField
label={t("web.admin.settings.ai.tuning.audioPerRequest")}
type="number"
unit={t("web.admin.settings.ai.unit.seconds")}
value={value("subtitle_ai.asr_chunk_seconds", "600")}
value={value("subtitle_ai.asr_chunk_seconds")}
onChange={(next) => setValue("subtitle_ai.asr_chunk_seconds", next)}
description={t("web.admin.settings.ai.tuning.audioPerRequestRange")}
restartRequired={restartKeys.has("subtitle_ai.asr_chunk_seconds")}
Expand All @@ -1074,7 +1073,7 @@ export default function AISettings() {
>
<LimitField
label={t("web.admin.settings.ai.tuning.transcriptions")}
value={value("subtitle_ai.transcribe_quota_jobs", "0")}
value={value("subtitle_ai.transcribe_quota_jobs")}
onChange={(next) => setValue("subtitle_ai.transcribe_quota_jobs", next)}
fallbackValue="10"
hint={t("web.admin.settings.ai.tuning.transcriptionsHint")}
Expand Down
12 changes: 11 additions & 1 deletion web/src/pages/admin-settings/GeneralSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ export default function GeneralSettings() {
const anyDirty = (keys: string[]) => keys.some((key) => form.isDirty(key));
const [saveInProgress, setSaveInProgress] = useState(false);
const saveInProgressRef = useRef(false);
// Each save and discard ends the Use Redis switch's own choice.
const [savesAndDiscards, setSavesAndDiscards] = useState(0);

// The Redis URL is a credential: its editors are frozen while a save is in
// flight so a late keystroke cannot ride along with it.
Expand Down Expand Up @@ -80,6 +82,7 @@ export default function GeneralSettings() {
? form.dirtyKeys.filter((key) => !REDIS_KEYS.includes(key))
: undefined,
);
setSavesAndDiscards((count) => count + 1);
} finally {
saveInProgressRef.current = false;
setSaveInProgress(false);
Expand All @@ -89,6 +92,8 @@ export default function GeneralSettings() {
function handleDiscard() {
if (saveInProgressRef.current) return;
form.discard();
// Discard clears nothing until the settings have loaded.
if (form.loaded) setSavesAndDiscards((count) => count + 1);
}

// Redis reads whether a URL is saved from the protected-credential status,
Expand Down Expand Up @@ -228,7 +233,12 @@ export default function GeneralSettings() {
</div>
</div>
) : (
<RedisGroup form={form} restartKeys={restartKeys} secrets={redisUrlEditors} />
<RedisGroup
form={form}
restartKeys={restartKeys}
secrets={redisUrlEditors}
savesAndDiscards={savesAndDiscards}
/>
)}
</div>

Expand Down
2 changes: 1 addition & 1 deletion web/src/pages/admin-settings/LibraryMetadataSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ export default function LibraryMetadataSettings() {
"web.admin.settings.libraryMetadata.subtitleSync.capacity.description",
)}
dirty={form.isDirty("subtitles.sync_node_capacity")}
value={form.getValue("subtitles.sync_node_capacity") || "1"}
value={form.getValue("subtitles.sync_node_capacity")}
onChange={(value) => form.setValue("subtitles.sync_node_capacity", value)}
restartRequired={restartKeys.has("subtitles.sync_node_capacity")}
/>
Expand Down
Loading
Loading