Skip to content
Merged
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
15 changes: 15 additions & 0 deletions apps/presentation/dashboard/src/data/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,21 @@ export function exportConfigurationBackup(goalIds?: string[]) {
});
}

export type ConfigurationBackupComparison = {
ok: boolean; status: "compared"; before_sha256: string; after_sha256: string;
before_goal_ids: string[]; after_goal_ids: string[]; only_in_before: string[]; only_in_after: string[];
before_machine_configuration_present: boolean; after_machine_configuration_present: boolean;
change_count: number; changes: {path: string; before_present: boolean; after_present: boolean; before?: unknown; after?: unknown}[];
};

export function compareConfigurationSnapshots(before: Record<string, unknown>, after: Record<string, unknown>) {
const body = JSON.stringify({before, after});
if (new TextEncoder().encode(body).byteLength > 64 * 1024 * 1024) {
throw new Error("Combined configuration snapshots exceed the 64 MiB comparison limit.");
}
return requestJson<ConfigurationBackupComparison>("/api/chat/configuration-backup/compare", {method: "POST", body});
}

export function restoreConfigurationCheckpoint(backup: Record<string, unknown>, execute: boolean) {
return requestJson<ConfigurationBackupResult>("/api/chat/configuration-backup/restore", {
method: "POST", body: JSON.stringify({backup, expected_sha256: backup.sha256, execute}),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
.personal-backup-comparison { display: grid; gap: 0.75rem; min-width: 0; margin-block: 1.25rem; }
.personal-backup-comparison h3, .personal-backup-comparison h4, .personal-backup-comparison p { margin: 0; overflow-wrap: anywhere; }
.personal-backup-files { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; }
.personal-backup-files > * { min-width: 0; }
.personal-backup-files label { display: grid; gap: 0.5rem; }
.personal-backup-files input { max-width: 100%; }
.personal-backup-comparison details { margin-block: 0.5rem; }
.personal-backup-comparison summary { overflow-wrap: anywhere; cursor: pointer; }
.personal-backup-comparison code { overflow-wrap: anywhere; white-space: pre-wrap; }
.personal-backup-comparison pre { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 20rem; overflow: auto; }
@media (max-width: 640px) { .personal-backup-files { grid-template-columns: minmax(0, 1fr); } }

.personal-configuration-preview-digest { display: block; max-width: 100%; overflow-wrap: anywhere; white-space: normal; }
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import {useEffect, useRef, useState} from "react";
import {compareConfigurationSnapshots, type ConfigurationBackupComparison} from "../../data/chat";
import {useWorkspaceI18n} from "./i18n";
import "./configuration-backup-comparison.css";

type Snapshot = {name: string; data: Record<string, unknown>};
export function ConfigurationBackupComparisonSettings({disabled, onChange, onReview, onBusyChange}: {
disabled: boolean; onBusyChange: (busy: boolean) => void; onChange: () => void; onReview: (backup: Record<string, unknown>) => void;
}) {
const zh = useWorkspaceI18n().locale === "zh-CN";
const [snapshots, setSnapshots] = useState<[Snapshot | null, Snapshot | null]>([null, null]);
const [comparison, setComparison] = useState<ConfigurationBackupComparison | null>(null);
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const alive = useRef(true);
useEffect(() => {alive.current = true; return () => {alive.current = false;};}, []);
const labels = zh ? ["比较前文件", "比较后文件"] : ["Before snapshot", "After snapshot"];
async function select(file: File | undefined, index: number) {
setComparison(null); setError(""); onChange();
setSnapshots(previous => index === 0 ? [null, previous[1]] : [previous[0], null]);
if (!file) return;
setBusy(true); onBusyChange(true);
try {
if (file.size > 64 * 1024 * 1024) throw new Error(zh ? "文件超过 64 MiB 比较限制。" : "File exceeds the 64 MiB comparison limit.");
const data: unknown = JSON.parse(await file.text());
if (!data || Array.isArray(data) || typeof data !== "object") throw new Error(zh ? "请选择配置快照 JSON 文件。" : "Select a configuration snapshot JSON object.");
if (!alive.current) return;
const selected = {name: file.name, data: data as Record<string, unknown>};
setSnapshots(previous => index === 0 ? [selected, previous[1]] : [previous[0], selected]);
} catch (failure) {if (alive.current) setError(String(failure));} finally {if (alive.current) {setBusy(false); onBusyChange(false);}}
}
async function compare() {
if (!snapshots[0] || !snapshots[1]) return;
setBusy(true); onBusyChange(true); setComparison(null); setError(""); onChange();
try {const compared = await compareConfigurationSnapshots(snapshots[0].data, snapshots[1].data); if (alive.current) setComparison(compared);}
catch (failure) {if (alive.current) setError(String(failure));} finally {if (alive.current) {setBusy(false); onBusyChange(false);}}
}
return <section className="personal-backup-comparison" aria-label={zh ? "比较配置快照" : "Compare configuration snapshots"}>
<h3>{zh ? "比较配置快照" : "Compare configuration snapshots"}</h3>
<p>{zh ? "先比较两个保存的文件,再选择要核对恢复的快照。比较不会修改当前设置;Goal 仅在某一文件出现可能是备份范围不同,不代表已新建或删除。" : "Compare two saved files before choosing a snapshot to review for recovery. Comparison changes no live settings. Goals present in only one file may reflect different backup cohorts, not creation or deletion."}</p>
<p>{zh ? "两文件请求合计最多 64 MiB;完整差异最多 56 MiB,超限时不返回部分结果。" : "Combined request limit: 64 MiB. Complete comparison limit: 56 MiB; oversized comparisons return no partial result."}</p>
<div className="personal-backup-files">{labels.map((label, index) => <label key={index}>{label}
<input type="file" accept=".json,application/json" aria-label={label} disabled={busy || disabled} onChange={event => {
void select(event.currentTarget.files?.[0], index);
}}/><span>{snapshots[index]?.name ?? (zh ? "尚未选择" : "No file selected")}</span>
</label>)}</div>
<button type="button" className="personal-secondary-action" disabled={busy || disabled || !snapshots[0] || !snapshots[1]} onClick={() => void compare()}>{busy ? (zh ? "正在读取…" : "Reading…") : (zh ? "比较两个文件" : "Compare files")}</button>
{error ? <p role="alert">{error}</p> : null}
{comparison ? <>
<p role="status">{zh ? `已比较:${comparison.change_count} 项差异。当前设置未改变。` : `Compared: ${comparison.change_count} differences. Live settings unchanged.`}</p>
<div className="personal-backup-files">{snapshots.map((snapshot, index) => {
const before = index === 0;
const ids = before ? comparison.before_goal_ids : comparison.after_goal_ids;
const only = before ? comparison.only_in_before : comparison.only_in_after;
return <div key={index}>
<h4>{labels[index]}: {snapshot?.name}</h4>
<p>{ids.length} Goal · {(before ? comparison.before_machine_configuration_present : comparison.after_machine_configuration_present) ? (zh ? "包含设备配置" : "Includes device configuration") : (zh ? "设备配置缺省" : "Device configuration absent")}</p>
<details><summary>{zh ? "散列与备份范围" : "Hash and cohort"}</summary>
<p>SHA-256: <code>{before ? comparison.before_sha256 : comparison.after_sha256}</code></p>
<p>Goal: {ids.join(", ") || (zh ? "无" : "None")}</p>
<p>{zh ? "仅在此文件: " : "Only in this file: "}{only.join(", ") || (zh ? "无" : "None")}</p>
</details>
<button type="button" className="personal-secondary-action" disabled={busy || disabled} onClick={() => {if (snapshot) onReview(snapshot.data);}}>{before ? (zh ? "核对比较前快照以恢复" : "Review before snapshot for recovery") : (zh ? "核对比较后快照以恢复" : "Review after snapshot for recovery")}</button>
</div>;
})}</div>
{comparison.changes.length === 0 ? <p>{zh ? "保存的配置内容一致。" : "Stored configuration contents are identical."}</p> : <div aria-label={zh ? "配置差异" : "Configuration differences"}>{comparison.changes.map(change => <details key={change.path}>
<summary><code>{change.path}</code></summary>
<div className="personal-backup-files">{[true, false].map(before => <div key={String(before)}><h4>{labels[before ? 0 : 1]}</h4>
<pre>{(before ? change.before_present : change.after_present) ? JSON.stringify(before ? change.before : change.after, null, 2) : (zh ? "不存在" : "Absent")}</pre>
</div>)}</div>
</details>)}</div>}
</> : null}
</section>;
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {useEffect, useState} from "react";
import {useEffect, useRef, useState} from "react";
import {exportConfigurationBackup, restoreConfigurationCheckpoint, type ConfigurationBackupResult} from "../../data/chat";
import {useWorkspaceI18n} from "./i18n";
import {ConfigurationBackupComparisonSettings} from "./configuration-backup-comparison";
import {StateRecoverySettings} from "./state-recovery-settings";

export function ConfigurationBackupSettings({goalId}: {goalId: string | null}) {
Expand All @@ -11,43 +12,56 @@ export function ConfigurationBackupSettings({goalId}: {goalId: string | null}) {
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const [kind, setKind] = useState<"configuration" | "state">("configuration");
useEffect(() => {setBackup(null); setResult(null); setError(""); setKind("configuration");}, [goalId]);
async function perform(action: () => Promise<void>) {
const generation = useRef(0);
useEffect(() => {generation.current++; setBusy(false); setBackup(null); setResult(null); setError(""); setKind("configuration"); return () => {generation.current++;};}, [goalId]);
async function perform(action: (current: () => boolean) => Promise<void>) {
const request = generation.current;
const current = () => request === generation.current;
setBusy(true); setError("");
try {await action();} catch (failure) {setError(String(failure));}
finally {setBusy(false);}
try {await action(current);} catch (failure) {if (current()) setError(String(failure));}
finally {if (current()) setBusy(false);}
}
return <details className="personal-detail-card">
<summary>{zh ? "配置备份与恢复" : "Configuration backup and recovery"}</summary>
{goalId === null ? <fieldset className="personal-recovery-kind">
<legend>{zh ? "备份类型" : "Backup type"}</legend>
<label><input type="radio" name="backup-kind" checked={kind === "configuration"} onChange={() => setKind("configuration")} />{zh ? "配置快照" : "Configuration snapshot"}</label>
<label><input type="radio" name="backup-kind" checked={kind === "state"} onChange={() => setKind("state")} />{zh ? "完整归档检查" : "Full archive inspection"}</label>
<label><input type="radio" disabled={busy} name="backup-kind" checked={kind === "configuration"} onChange={() => setKind("configuration")} />{zh ? "配置快照" : "Configuration snapshot"}</label>
<label><input type="radio" disabled={busy} name="backup-kind" checked={kind === "state"} onChange={() => setKind("state")} />{zh ? "完整归档检查" : "Full archive inspection"}</label>
</fieldset> : null}
{kind === "configuration" || goalId !== null ? <>
<p>{zh ? "备份包含私有路径、Goal 设置及设备默认值,需自行保管和审查。凭据文件不包含在此组件中。恢复只建立隔离检查点;启用仍在原配置页面办理。" : "Keep and review this private backup: it includes Goal settings, paths and device defaults. Credential files are outside this component. Recovery creates an isolated checkpoint; activate settings through their existing editors."}</p>
<button className="personal-secondary-action" disabled={busy} type="button" onClick={() => void perform(async () => {
<button className="personal-secondary-action" disabled={busy} type="button" onClick={() => void perform(async current => {
const exported = await exportConfigurationBackup(goalId ? [goalId] : undefined);
if (!current()) return;
const url = URL.createObjectURL(new Blob([JSON.stringify(exported.backup, null, 2) + "\n"], {type: "application/json"}));
const anchor = document.createElement("a"); anchor.href = url; anchor.download = "loopx-configuration-backup.json";
anchor.click(); URL.revokeObjectURL(url);
setResult(exported);
})}>{zh ? "下载配置备份" : "Download configuration backup"}</button>
<ConfigurationBackupComparisonSettings key={goalId ?? "machine"} disabled={busy} onBusyChange={setBusy} onChange={() => {setBackup(null); setResult(null); setError("");}} onReview={candidate => {
setBackup(null); setResult(null);
void perform(async current => {
const preview = await restoreConfigurationCheckpoint(candidate, false);
if (current()) {setBackup(candidate); setResult(preview);}
});
}} />
<label>{zh ? "恢复备份文件" : "Recover backup file"}<input aria-label={zh ? "恢复备份文件" : "Recover backup file"} disabled={busy} type="file" accept=".json,application/json" onChange={(event) => {
const file = event.currentTarget.files?.[0]; event.currentTarget.value = "";
setBackup(null); setResult(null);
if (file) void perform(async () => {
if (file) void perform(async current => {
const candidate = JSON.parse(await file.text()) as Record<string, unknown>;
const preview = await restoreConfigurationCheckpoint(candidate, false);
setBackup(candidate); setResult(preview);
if (current()) {setBackup(candidate); setResult(preview);}
});
}}/></label>
{backup && result?.status === "preview" ? <button className="personal-primary-action" disabled={busy} type="button" onClick={() => void perform(async () => {
setResult(await restoreConfigurationCheckpoint(backup, true));
{backup && result?.status === "preview" ? <button className="personal-primary-action" disabled={busy} type="button" onClick={() => void perform(async current => {
const restored = await restoreConfigurationCheckpoint(backup, true);
if (current()) setResult(restored);
})}>{zh ? "恢复为隔离检查点" : "Restore isolated checkpoint"}</button> : null}
{result ? <p role="status">{result.status === "restored"
? (zh ? "检查点已恢复并核对;当前设置及存储 provider 未改变。" : "Checkpoint restored and verified. Live settings and storage provider are unchanged.")
: (zh ? "配置备份已核对" : "Configuration backup verified")}: {result.goal_count} Goal · {result.machine_configuration_present ? (zh ? "包含设备配置" : "includes device configuration") : (zh ? "设备配置缺省" : "device configuration absent")}
{result.status === "preview" ? <code className="personal-configuration-preview-digest">SHA-256: {result.sha256}</code> : null}
{result.checkpoint_ref ? <code>{result.checkpoint_ref}</code> : null}</p> : null}
{error ? <p role="alert">{error}</p> : null}
</> : <StateRecoverySettings />}
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading