Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(config-sync): keep cloud backup settings ready on revisit
vastsac78faf778f67
diff --git a/apps/desktop/src/components/settings/ConfigSyncPage.tsx b/apps/desktop/src/components/settings/ConfigSyncPage.tsxindex f23ff7c52..c463b99a7 100644--- a/apps/desktop/src/components/settings/ConfigSyncPage.tsx+++ b/apps/desktop/src/components/settings/ConfigSyncPage.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import type {ConfigSyncCategory,@@ -14,6 +14,16 @@ import { Badge, Button, Checkbox, Field, Input, PasswordInput, SettingsToggle }import { IconCloudDown, IconRefresh, IconShield, IconTrash } from "../icons";import { SettingsCard, SettingsRow } from "../../features/settings/primitives";import { configSyncProgressView } from "../../features/settings/config-sync-progress";+import {+ cacheConfigSyncHistory,+ cacheConfigSyncState,+ clearConfigSyncDraft,+ getCachedConfigSyncHistory,+ getCachedConfigSyncState,+ hasFreshConfigSyncHistory,+ readConfigSyncDraft,+ writeConfigSyncDraft,+} from "../../features/settings/config-sync-preferences";import { ConfigSyncError } from "./ConfigSyncError";import { SettingsMenuSelect } from "./SettingsMenuSelect";@@ -51,6 +61,55 @@ const DEFAULT_SELECTION: ConfigSyncCategorySelection = {memory: false,};+type ConfigSyncForm = {+ endpoint: string;+ username: string;+ appPassword: string;+ directory: string;+ deviceLabel: string;+ backupPassword: string;+ currentBackupPassword: string;+ newBackupPassword: string;+};++function selectionFromDraft(+ categories?: Partial<ConfigSyncCategorySelection>,+): ConfigSyncCategorySelection {+ return {+ ...DEFAULT_SELECTION,+ ...(categories ?? {}),+ };+}++function initialConfigSyncForm(draft = readConfigSyncDraft()): ConfigSyncForm {+ return {+ endpoint: draft.endpoint ?? "",+ username: draft.username ?? "",+ appPassword: "",+ directory: draft.directory ?? "pi-desktop",+ deviceLabel: draft.deviceLabel ?? "",+ backupPassword: "",+ currentBackupPassword: "",+ newBackupPassword: "",+ };+}++function draftFromState(next: ConfigSyncState) {+ return {+ endpoint: next.endpoint ?? "",+ username: next.username ?? "",+ directory: next.directory ?? "pi-desktop",+ deviceLabel: next.deviceLabel ?? "",+ remoteMode: next.remoteMode,+ categories: {+ ...next.categories,+ credentials: next.includeSecrets,+ memory: next.includeMemory,+ },+ saved: true,+ };+}+function statusTone(status: ConfigSyncState["status"],): "neutral" | "success" | "error" | "warning" {@@ -66,8 +125,14 @@ function statusTone(export function ConfigSyncPage() {const { t } = useTranslation();- const [state, setState] = useState<ConfigSyncState | null>(null);- const [loading, setLoading] = useState(true);+ const [initialDraft] = useState(() => readConfigSyncDraft());+ const [state, setState] = useState<ConfigSyncState | null>(() =>+ getCachedConfigSyncState(),+ );+ // A cached state paints immediately when the user returns to the page. A+ // first visit still refreshes in the background, but never blocks the draft+ // form from being useful.+ const [loading, setLoading] = useState(() => getCachedConfigSyncState() === null);const [busy, setBusy] = useState<| "test"| "configure"@@ -82,85 +147,164 @@ export function ConfigSyncPage() {>(null);/** The last progress the host reported for a manual sync, if one is running. */const [progress, setProgress] = useState<ConfigSyncProgress | null>(null);- const [history, setHistory] = useState<ConfigSyncHistoryEntry[]>([]);+ const [history, setHistory] = useState<ConfigSyncHistoryEntry[]>(() =>+ getCachedConfigSyncHistory(),+ );const [error, setError] = useState<string | null>(null);const [notice, setNotice] = useState<string | null>(null);- const [form, setForm] = useState({- endpoint: "",- username: "",- appPassword: "",- directory: "pi-desktop",- deviceLabel: "",- backupPassword: "",- currentBackupPassword: "",- newBackupPassword: "",- });- const [selection, setSelection] =- useState<ConfigSyncCategorySelection>(DEFAULT_SELECTION);- const [remoteMode, setRemoteMode] = useState<ConfigSyncRemoteMode>("strict");+ const [form, setForm] = useState<ConfigSyncForm>(() =>+ initialConfigSyncForm(initialDraft),+ );+ const [selection, setSelection] = useState<ConfigSyncCategorySelection>(() =>+ selectionFromDraft(initialDraft.categories),+ );+ const [remoteMode, setRemoteMode] = useState<ConfigSyncRemoteMode>(+ () => initialDraft.remoteMode ?? "strict",+ );+ const mountedRef = useRef(true);+ const formDirtyRef = useRef(initialDraft.saved === false);+ const stateRequestRef = useRef(0);+ const historyRequestRef = useRef(0);++ const applyState = useCallback((next: ConfigSyncState) => {+ // A host event or an explicit action is newer than any page-open refresh+ // still in flight. Invalidating that request prevents stale state from+ // replacing the result the user just triggered.+ stateRequestRef.current += 1;+ cacheConfigSyncState(next);+ setState(next);+ setLoading(false);+ }, []);++ const hydrateSavedFields = useCallback((next: ConfigSyncState) => {+ if (formDirtyRef.current || !next.configured) return;+ const draft = draftFromState(next);+ setForm((current) => ({+ ...current,+ endpoint: draft.endpoint,+ username: draft.username,+ directory: draft.directory,+ deviceLabel: draft.deviceLabel,+ }));+ setSelection(selectionFromDraft(draft.categories));+ setRemoteMode(draft.remoteMode);+ writeConfigSyncDraft({ ...draft, saved: true });+ }, []);++ const refreshHistory = useCallback(async (showError: boolean) => {+ const requestId = ++historyRequestRef.current;+ try {+ const next = await api.configSyncListHistory();+ if (!mountedRef.current || requestId !== historyRequestRef.current) return;+ cacheConfigSyncHistory(next);+ setHistory(next);+ } catch (cause) {+ if (!showError || !mountedRef.current || requestId !== historyRequestRef.current) {+ return;+ }+ setError(cause instanceof Error ? cause.message : String(cause));+ }+ }, []);++ const clearHistory = useCallback(() => {+ historyRequestRef.current += 1;+ cacheConfigSyncHistory([]);+ setHistory([]);+ }, []);const refresh = useCallback(async () => {+ const requestId = ++stateRequestRef.current;try {const next = await api.configSyncGetState();- setState(next);- setRemoteMode(next.remoteMode ?? "strict");- if (next.configured) {- setForm((current) => ({- ...current,- endpoint: next.endpoint ?? current.endpoint,- username: next.username ?? current.username,- directory: next.directory ?? current.directory,- deviceLabel: next.deviceLabel ?? current.deviceLabel,- }));- setSelection((current) => ({- ...current,- ...next.categories,- credentials: next.includeSecrets,- memory: next.includeMemory,- }));- if (!next.locked) {- try {- setHistory(await api.configSyncListHistory());- } catch {- setHistory([]);- }- } else {- setHistory([]);- }+ if (!mountedRef.current || requestId !== stateRequestRef.current) return;+ applyState(next);+ hydrateSavedFields(next);+ if (next.configured && !next.locked) {+ // History is supplementary. It should not hold the whole settings+ // surface behind a remote request, and a short-lived cache avoids a+ // second network round-trip when the user revisits the page.+ if (!hasFreshConfigSyncHistory()) void refreshHistory(false);+ } else {+ clearHistory();}} catch (cause) {+ if (!mountedRef.current || requestId !== stateRequestRef.current) return;setError(cause instanceof Error ? cause.message : String(cause));} finally {- setLoading(false);+ if (mountedRef.current && requestId === stateRequestRef.current) {+ setLoading(false);+ }}- }, []);+ }, [applyState, clearHistory, hydrateSavedFields, refreshHistory]);const loadHistory = useCallback(async () => {if (!state?.configured || state.locked) return;setBusy("history");try {- setHistory(await api.configSyncListHistory());- } catch (cause) {- setError(cause instanceof Error ? cause.message : String(cause));+ await refreshHistory(true);} finally {setBusy(null);}- }, [state?.configured, state?.locked]);+ }, [refreshHistory, state?.configured, state?.locked]);useEffect(() => {void refresh();return api.onConfigSyncChanged((next) => {- setState(next);- setRemoteMode(next.remoteMode ?? "strict");+ applyState(next);+ hydrateSavedFields(next);+ if (next.configured && !next.locked && !hasFreshConfigSyncHistory()) {+ void refreshHistory(false);+ } else if (!next.configured || next.locked) {+ clearHistory();+ }});- }, [refresh]);+ }, [applyState, clearHistory, hydrateSavedFields, refresh, refreshHistory]);++ useEffect(() => {+ return () => {+ mountedRef.current = false;+ historyRequestRef.current += 1;+ };+ }, []);// The report is only shown while the page is running a sync itself, so an// automatic run stays silent; the subscription is dropped with the page.useEffect(() => api.onConfigSyncProgress((next) => setProgress(next)), []);- const updateForm = (key: keyof typeof form, value: string) =>+ const updateForm = (key: keyof ConfigSyncForm, value: string) => {+ formDirtyRef.current = true;setForm((current) => ({ ...current, [key]: value }));+ };++ const updateSelection = (key: keyof ConfigSyncCategorySelection, value: boolean) => {+ formDirtyRef.current = true;+ setSelection((current) => ({ ...current, [key]: value }));+ };++ const updateRemoteMode = (value: ConfigSyncRemoteMode) => {+ formDirtyRef.current = true;+ setRemoteMode(value);+ };++ useEffect(() => {+ if (!formDirtyRef.current) return;+ writeConfigSyncDraft({+ endpoint: form.endpoint,+ username: form.username,+ directory: form.directory,+ deviceLabel: form.deviceLabel,+ remoteMode,+ categories: selection,+ saved: false,+ });+ }, [+ form.deviceLabel,+ form.directory,+ form.endpoint,+ form.username,+ remoteMode,+ selection,+ ]);const run = async (operation: "test" | "configure" | "sync" | "unlock" | "disconnect",@@ -199,7 +343,8 @@ export function ConfigSyncPage() {: t("settings.configSync.testUnsupported"),);} else if (operation === "configure") {- await api.configSyncConfigure({+ clearHistory();+ const configuredState = await api.configSyncConfigure({endpoint: form.endpoint,username: form.username,appPassword: form.appPassword || undefined,@@ -212,20 +357,30 @@ export function ConfigSyncPage() {automaticSync: true,remoteMode,});- setState(await api.configSyncSyncNow());+ // Show the saved connection immediately while the first full sync is+ // still running. The previous flow kept the page in its unconfigured+ // shape until sync completed, which made a slow first setup look stuck.+ applyState(configuredState);+ formDirtyRef.current = false;+ hydrateSavedFields(configuredState);+ applyState(await api.configSyncSyncNow());+ void refreshHistory(false);setForm((current) => ({ ...current, appPassword: "", backupPassword: "" }));setNotice(t("settings.configSync.configured"));} else if (operation === "sync") {- setState(await api.configSyncSyncNow());+ applyState(await api.configSyncSyncNow());+ void refreshHistory(false);} else if (operation === "unlock") {- setState(await api.configSyncUnlock(form.backupPassword));+ applyState(await api.configSyncUnlock(form.backupPassword));setForm((current) => ({ ...current, backupPassword: "" }));} else {- setState(await api.configSyncDisconnect());- setHistory([]);+ applyState(await api.configSyncDisconnect());+ clearConfigSyncDraft();+ clearHistory();setRemoteMode("strict");- setForm((current) => ({ ...current, appPassword: "", backupPassword: "" }));- setSelection(DEFAULT_SELECTION);+ formDirtyRef.current = false;+ setForm(initialConfigSyncForm());+ setSelection(selectionFromDraft());}} catch (cause) {setError(cause instanceof Error ? cause.message : String(cause));@@ -243,7 +398,7 @@ export function ConfigSyncPage() {setError(null);setNotice(null);try {- setState(+ applyState(await api.configSyncChangePassword({currentPassword: form.currentBackupPassword,newPassword: form.newBackupPassword,@@ -267,13 +422,13 @@ export function ConfigSyncPage() {setBusy("restore");setError(null);try {- setState(+ applyState(await api.configSyncRestore({revisionId: entry.revisionId,acknowledgePropagation: true,}),);- setHistory(await api.configSyncListHistory());+ await refreshHistory(true);setNotice(t("settings.configSync.restoreStarted"));} catch (cause) {setError(cause instanceof Error ? cause.message : String(cause));@@ -289,7 +444,7 @@ export function ConfigSyncPage() {const next = accepted? await api.configSyncApprove({ approvalId, digest }): await api.configSyncReject({ approvalId, digest });- setState(next);+ applyState(next);} catch (cause) {setError(cause instanceof Error ? cause.message : String(cause));} finally {@@ -304,7 +459,7 @@ export function ConfigSyncPage() {const picked = await api.pickProjectFolders();const paths = picked.folders?.filter(Boolean) ?? [];if (!paths.length) return;- setState(+ applyState(await api.configSyncMapProject({logicalId,path: paths[0],@@ -322,7 +477,7 @@ export function ConfigSyncPage() {setBusy("sync");setError(null);try {- setState(await api.configSyncPause(!state?.paused));+ applyState(await api.configSyncPause(!state?.paused));} catch (cause) {setError(cause instanceof Error ? cause.message : String(cause));} finally {@@ -373,16 +528,9 @@ export function ConfigSyncPage() {}};- if (loading) {- return (- <div className="settings-recovery" role="status">- {t("common.loading")}- </div>- );- }-const configured = state?.configured === true;const locked = state?.locked === true;+ const stateReady = state !== null;const categories = selection;const vaultPasswordReady =form.backupPassword.length === 0@@ -397,7 +545,16 @@ export function ConfigSyncPage() {: null;return (- <div className="settings-stack settings-config-sync">+ <div+ className="settings-stack settings-config-sync"+ aria-busy={loading || undefined}+ >+ {loading && !state ? (+ <div className="settings-config-sync-refresh" role="status">+ <IconRefresh size={14} />+ {t("common.loading")}+ </div>+ ) : null}{error || state?.lastError ? (<ConfigSyncError message={error ?? state?.lastError ?? ""} />) : null}@@ -435,7 +592,7 @@ export function ConfigSyncPage() {label: t("settings.configSync.remoteModeAppendOnly"),},]}- onChange={(value) => setRemoteMode(value as ConfigSyncRemoteMode)}+ onChange={(value) => updateRemoteMode(value as ConfigSyncRemoteMode)}/></Field>{remoteMode === "appendOnly" ? (@@ -452,7 +609,10 @@ export function ConfigSyncPage() {disabled={busy !== null}/></Field>- <Field label={t("settings.configSync.appPassword")}>+ <Field+ label={t("settings.configSync.appPassword")}+ hint={configured ? t("settings.configSync.appPasswordSavedHint") : undefined}+ ><PasswordInputvalue={form.appPassword}onChange={(event) => updateForm("appPassword", event.target.value)}@@ -488,7 +648,11 @@ export function ConfigSyncPage() {? t("settings.configSync.backupPasswordUnlock"): t("settings.configSync.backupPassword")}- hint={t("settings.configSync.backupPasswordHint")}+ hint={+ configured && !locked+ ? t("settings.configSync.backupPasswordOptional")+ : t("settings.configSync.backupPasswordHint")+ }><PasswordInputvalue={form.backupPassword}@@ -505,7 +669,7 @@ export function ConfigSyncPage() {<Buttonvariant="secondary"onClick={() => void run("test")}- disabled={busy !== null || !form.endpoint}+ disabled={busy !== null || loading || !stateReady || !form.endpoint}><IconRefresh size={14} />{t("settings.configSync.test")}@@ -513,7 +677,9 @@ export function ConfigSyncPage() {<Buttonvariant="primary"onClick={() => void run("configure")}- disabled={busy !== null || !form.endpoint || !vaultPasswordReady}+ disabled={+ busy !== null || loading || !stateReady || !form.endpoint || !vaultPasswordReady+ }><IconCloudDown size={14} />{configured ? t("settings.configSync.save") : t("settings.configSync.enable")}@@ -528,11 +694,6 @@ export function ConfigSyncPage() {</Button>) : null}</div>- {error ? (- <div className="settings-config-sync-message error" role="alert">- {error}- </div>- ) : null}{notice ? (<div className="settings-config-sync-message" role="status">{notice}@@ -688,10 +849,7 @@ export function ConfigSyncPage() {className="settings-config-sync-category"checked={categories[category.id] !== false}onChange={(event) =>- setSelection((current) => ({- ...current,- [category.id]: event.target.checked,- }))+ updateSelection(category.id, event.target.checked)}label={t(category.label)}/>@@ -700,10 +858,7 @@ export function ConfigSyncPage() {className="settings-config-sync-category"checked={selection.memory}onChange={(event) =>- setSelection((current) => ({- ...current,- memory: event.target.checked,- }))+ updateSelection("memory", event.target.checked)}label={t("settings.configSync.categoryMemory")}/>@@ -711,10 +866,7 @@ export function ConfigSyncPage() {className="settings-config-sync-category settings-config-sync-sensitive"checked={selection.credentials}onChange={(event) =>- setSelection((current) => ({- ...current,- credentials: event.target.checked,- }))+ updateSelection("credentials", event.target.checked)}label={t("settings.configSync.categoryCredentials")}/>diff --git a/apps/desktop/src/features/settings/config-sync-preferences.ts b/apps/desktop/src/features/settings/config-sync-preferences.tsnew file mode 100644index 000000000..c1b612f96--- /dev/null+++ b/apps/desktop/src/features/settings/config-sync-preferences.ts@@ -0,0 +1,169 @@+import type {+ ConfigSyncCategory,+ ConfigSyncCategorySelection,+ ConfigSyncHistoryEntry,+ ConfigSyncRemoteMode,+ ConfigSyncState,+} from "@pi-desktop/shared";++/**+ * The draft is deliberately limited to non-sensitive connection fields.+ * The WebDAV app password and derived vault key stay in Host-owned secret+ * storage; the passwords are never copied into renderer persistence, even as a+ * convenience cache.+ */+export type ConfigSyncDraft = {+ endpoint?: string;+ username?: string;+ directory?: string;+ deviceLabel?: string;+ remoteMode?: ConfigSyncRemoteMode;+ categories?: Partial<ConfigSyncCategorySelection>;+ /** False means the user left an unsaved draft; true mirrors Host state. */+ saved?: boolean;+};++type StorageLike = Pick<Storage, "getItem" | "setItem" | "removeItem">;++export const CONFIG_SYNC_DRAFT_STORAGE_KEY = "pi.desktop.configSyncDraft";+export const CONFIG_SYNC_HISTORY_CACHE_TTL_MS = 30_000;++const CATEGORY_KEYS: ConfigSyncCategory[] = [+ "application",+ "providers",+ "credentials",+ "mcp",+ "skills",+ "subagents",+ "instructions",+ "projects",+ "plugins",+ "automation",+ "memory",+];++function storage(): StorageLike | null {+ try {+ return typeof globalThis !== "undefined" && "localStorage" in globalThis+ ? globalThis.localStorage+ : null;+ } catch {+ return null;+ }+}++function object(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++function text(value: unknown): string | undefined {+ if (typeof value !== "string" || value.length > 2048) return undefined;+ return value;+}++function remoteMode(value: unknown): ConfigSyncRemoteMode | undefined {+ return value === "strict" || value === "appendOnly" ? value : undefined;+}++export function readConfigSyncDraft(store: StorageLike | null = storage()): ConfigSyncDraft {+ if (!store) return {};+ try {+ const raw = store.getItem(CONFIG_SYNC_DRAFT_STORAGE_KEY);+ if (!raw) return {};+ const parsed: unknown = JSON.parse(raw);+ if (!object(parsed)) return {};++ const draft: ConfigSyncDraft = {};+ for (const key of ["endpoint", "username", "directory", "deviceLabel"] as const) {+ const value = text(parsed[key]);+ if (value !== undefined) draft[key] = value;+ }+ const mode = remoteMode(parsed.remoteMode);+ if (mode) draft.remoteMode = mode;+ if (typeof parsed.saved === "boolean") draft.saved = parsed.saved;++ if (object(parsed.categories)) {+ const categories: Partial<ConfigSyncCategorySelection> = {};+ for (const key of CATEGORY_KEYS) {+ if (typeof parsed.categories[key] === "boolean") {+ categories[key] = parsed.categories[key] as boolean;+ }+ }+ if (Object.keys(categories).length > 0) draft.categories = categories;+ }+ return draft;+ } catch {+ return {};+ }+}++/** Persist only the explicitly supported, non-sensitive draft fields. */+export function writeConfigSyncDraft(+ draft: ConfigSyncDraft,+ store: StorageLike | null = storage(),+): void {+ if (!store) return;+ try {+ const value: Record<string, unknown> = {};+ for (const key of ["endpoint", "username", "directory", "deviceLabel"] as const) {+ const next = text(draft[key]);+ if (next !== undefined) value[key] = next;+ }+ const mode = remoteMode(draft.remoteMode);+ if (mode) value.remoteMode = mode;+ if (typeof draft.saved === "boolean") value.saved = draft.saved;+ if (draft.categories && object(draft.categories)) {+ const categories: Partial<ConfigSyncCategorySelection> = {};+ for (const key of CATEGORY_KEYS) {+ if (typeof draft.categories[key] === "boolean") {+ categories[key] = draft.categories[key] as boolean;+ }+ }+ if (Object.keys(categories).length > 0) value.categories = categories;+ }+ store.setItem(CONFIG_SYNC_DRAFT_STORAGE_KEY, JSON.stringify(value));+ } catch {+ // A blocked or full localStorage must not prevent cloud sync from working.+ }+}++export function clearConfigSyncDraft(store: StorageLike | null = storage()): void {+ if (!store) return;+ try {+ store.removeItem(CONFIG_SYNC_DRAFT_STORAGE_KEY);+ } catch {+ // Best effort cleanup; disconnect still remains authoritative in Host.+ }+}++let cachedState: ConfigSyncState | null = null;+let cachedHistory: ConfigSyncHistoryEntry[] | null = null;+let cachedHistoryAt = 0;++export function getCachedConfigSyncState(): ConfigSyncState | null {+ return cachedState;+}++export function cacheConfigSyncState(next: ConfigSyncState): void {+ cachedState = next;+}++export function getCachedConfigSyncHistory(): ConfigSyncHistoryEntry[] {+ return cachedHistory ? [...cachedHistory] : [];+}++export function cacheConfigSyncHistory(+ next: ConfigSyncHistoryEntry[],+ now = Date.now(),+): void {+ cachedHistory = [...next];+ cachedHistoryAt = now;+}++export function hasFreshConfigSyncHistory(now = Date.now()): boolean {+ return (+ cachedHistory !== null &&+ now - cachedHistoryAt >= 0 &&+ now - cachedHistoryAt < CONFIG_SYNC_HISTORY_CACHE_TTL_MS+ );+}diff --git a/apps/desktop/src/styles/settings.css b/apps/desktop/src/styles/settings.cssindex 47bb31485..c1359934a 100644--- a/apps/desktop/src/styles/settings.css+++ b/apps/desktop/src/styles/settings.css@@ -490,7 +490,8 @@gap: 8px;}-.settings-config-sync > .settings-card-block:first-child .settings-config-sync-actions {+.settings-config-sync > .settings-card-block:first-child .settings-config-sync-actions,+.settings-config-sync > .settings-card-block:first-of-type .settings-config-sync-actions {padding: 0 16px 14px;}@@ -506,6 +507,15 @@color: var(--ds-danger);}+.settings-config-sync-refresh {+ display: flex;+ align-items: center;+ gap: 6px;+ margin: 0 16px;+ color: var(--ds-text-muted);+ font-size: var(--text-sm);+}+/** A manual sync reports itself while its request is still open: the phase it* is in, a bar once it announced a total, and the figures it has moved so far.diff --git a/apps/desktop/test/config-sync-preferences.test.mjs b/apps/desktop/test/config-sync-preferences.test.mjsnew file mode 100644index 000000000..eb400d966--- /dev/null+++ b/apps/desktop/test/config-sync-preferences.test.mjs@@ -0,0 +1,95 @@+import assert from "node:assert/strict";+import { createRequire } from "node:module";+import { readFile } from "node:fs/promises";+import test from "node:test";++const source = await readFile(+ new URL("../src/features/settings/config-sync-preferences.ts", import.meta.url),+ "utf8",+);+const require = createRequire(new URL("../../../packages/agent-runtime/package.json", import.meta.url));+const { transform } = require("esbuild");+const compiled = await transform(source, {+ loader: "ts",+ format: "esm",+ target: "es2022",+});+const preferences = await import(+ `data:text/javascript,${encodeURIComponent(compiled.code)}`,+);++function fakeStorage() {+ const values = new Map();+ return {+ values,+ getItem(key) {+ return values.get(key) ?? null;+ },+ setItem(key, value) {+ values.set(key, value);+ },+ removeItem(key) {+ values.delete(key);+ },+ };+}++test("config sync draft persists connection choices without secrets", () => {+ const store = fakeStorage();+ preferences.writeConfigSyncDraft(+ {+ endpoint: "http://127.0.0.1:49152/dav/",+ username: "alice",+ directory: "pi-desktop",+ deviceLabel: "MacBook",+ remoteMode: "strict",+ categories: { providers: true, credentials: false },+ saved: false,+ },+ store,+ );++ const raw = store.values.get(preferences.CONFIG_SYNC_DRAFT_STORAGE_KEY);+ assert.ok(raw);+ assert.doesNotMatch(raw, /password|secret/i);+ assert.deepEqual(preferences.readConfigSyncDraft(store), {+ endpoint: "http://127.0.0.1:49152/dav/",+ username: "alice",+ directory: "pi-desktop",+ deviceLabel: "MacBook",+ remoteMode: "strict",+ categories: { providers: true, credentials: false },+ saved: false,+ });+});++test("config sync draft ignores malformed or overlong local storage values", () => {+ const store = fakeStorage();+ store.setItem(+ preferences.CONFIG_SYNC_DRAFT_STORAGE_KEY,+ JSON.stringify({+ endpoint: "x".repeat(2049),+ remoteMode: "unsafe",+ categories: { providers: "yes", mcp: true },+ saved: "no",+ }),+ );+ assert.deepEqual(preferences.readConfigSyncDraft(store), {+ categories: { mcp: true },+ });+});++test("config sync history cache expires without blocking the state cache", () => {+ const entries = [{+ revisionId: "revision-a",+ createdAt: "2026-09-25T00:00:00.000Z",+ parentRevisionIds: [],+ entityCount: 1,+ resourceCount: 1,+ current: true,+ }];+ preferences.cacheConfigSyncHistory(entries, 1000);+ assert.equal(preferences.hasFreshConfigSyncHistory(1000), true);+ assert.equal(preferences.hasFreshConfigSyncHistory(1000 + preferences.CONFIG_SYNC_HISTORY_CACHE_TTL_MS), false);+ assert.deepEqual(preferences.getCachedConfigSyncHistory(), entries);+});diff --git a/apps/desktop/test/config-sync-settings.test.mjs b/apps/desktop/test/config-sync-settings.test.mjsindex 3e8111d76..5efb9fa51 100644--- a/apps/desktop/test/config-sync-settings.test.mjs+++ b/apps/desktop/test/config-sync-settings.test.mjs@@ -14,6 +14,9 @@ const read = (relativePath) =>const settingsPage = await read("../src/features/settings/SettingsPage.tsx");const settingsIndex = await read("../src/lib/settings-search.ts");const syncPage = await read("../src/components/settings/ConfigSyncPage.tsx");+const syncPreferences = await read(+ "../src/features/settings/config-sync-preferences.ts",+);const syncIpc = await read("../electron/main/ipc/config-sync-ipc.ts");const styles = await loadStyles();const syncProtocol = await read("../../../packages/shared/src/protocol.ts");@@ -33,7 +36,7 @@ test("cloud sync rendering follows the settings visibility gate", () => {test("cloud sync keeps credentials and vault operations on the host boundary", () => {assert.match(syncPage, /api\.configSyncConfigure\(/);- assert.match(syncPage, /setState\(await api\.configSyncSyncNow\(\)\)/);+ assert.match(syncPage, /applyState\(await api\.configSyncSyncNow\(\)\)/);// The plaintext opt-in is the network mode now, not a WebDAV switch: the page// carries no per-endpoint HTTP acknowledgement of its own.assert.doesNotMatch(syncPage, /allowInsecureHttp/);@@ -55,6 +58,19 @@ test("cloud sync keeps credentials and vault operations on the host boundary", (assert.match(syncIpc, /callHost\("configSync\.changePassword"/);});+test("cloud sync keeps a non-sensitive draft and paints cached state first", () => {+ assert.match(syncPage, /getCachedConfigSyncState\(\)/);+ assert.match(syncPage, /getCachedConfigSyncHistory\(\)/);+ assert.match(syncPage, /writeConfigSyncDraft\(/);+ assert.match(syncPage, /appPasswordSavedHint/);+ assert.doesNotMatch(syncPage, /if \(loading\) \{[\s\S]{0,180}return \(/);+ assert.match(syncPreferences, /passwords are never copied into renderer persistence/);+ assert.match(syncPreferences, /CONFIG_SYNC_DRAFT_STORAGE_KEY/);+ assert.match(syncPreferences, /saved\?: boolean/);+ assert.match(syncPreferences, /store\.setItem\(CONFIG_SYNC_DRAFT_STORAGE_KEY/);+ assert.doesNotMatch(syncPreferences, /appPassword|backupPassword/);+});+test("cloud sync settings remain usable on narrow surfaces", () => {assert.match(styles,diff --git a/docs/spec/03-runtime/22-config-sync.md b/docs/spec/03-runtime/22-config-sync.mdindex 51406fb28..aa454f319 100644--- a/docs/spec/03-runtime/22-config-sync.md+++ b/docs/spec/03-runtime/22-config-sync.md@@ -176,6 +176,16 @@ support. The renderer displaysand `error` as distinct states. Disconnect keeps local data and does not deleteremote data.+Reopening the page paints the last redacted host state and history from a+short-lived renderer cache, then refreshes the host in the background. The+connection draft (endpoint, username, remote directory, device label,+compatibility mode, and category choices) is kept in renderer-local storage so+an unfinished form survives navigation or reload. It is marked saved again+when the host confirms the persisted configuration. WebDAV app passwords stay+in the Host secret store and are reused only for the same endpoint and account;+the renderer never stores either password, and a vault password is only needed+when a new or locked device must open the vault.+A manual sync reports what it is doing while it runs. `configSync.progress`carries the current phase — `capture`, `download`, `merge`, `upload`, `apply`,or `cleanup` — the units finished in that phase, and the bytes when they arediff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.mdindex 25dff4ec3..625984149 100644--- a/docs/spec/04-ux/06-settings-ia.md+++ b/docs/spec/04-ux/06-settings-ia.md@@ -202,6 +202,13 @@ Settings is a **full-window page** that replaces the app sidebar + main chrome (Users can sync now, unlock, pause this device, approve/reject staged items,and disconnect. The page does not imply convergence from an old successfulrun while a pending state remains.+- **Fast revisit and drafts**: render the last redacted state and history from+ a short-lived local cache while the host refresh runs in the background. Keep+ endpoint, username, remote directory, device label, compatibility mode, and+ category choices in renderer-local storage so an unfinished form survives+ navigation or reload. WebDAV app passwords remain in Host-owned secret+ storage and are reused only for the same endpoint and account; vault+ passwords are never written to renderer storage.### 全局 AI (`ai` tab)- **Permissions** card: the global permission-mode controldiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 877f801d5..6b555bbe7 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -8458,7 +8458,12 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.history. Cancel the confirmation once and verify configuration is not saved.11) Use the explicit LAN HTTP acknowledgement with a loopback/private fixture,verify the setting survives a state refresh, and confirm a public HTTP- endpoint is rejected even when the checkbox is selected.+ endpoint is rejected even when the checkbox is selected. 12) Leave the+ Cloud sync page with an unfinished connection edit, reopen it, and confirm+ the non-sensitive draft is painted immediately while host state/history+ refreshes in the background. Confirm a configured endpoint reuses its stored+ WebDAV app password, while password fields themselves remain blank and no+ vault password is written to renderer storage.- **Expected:** With developer mode off, Cloud sync is absent from the rail andsettings search; enabling developer mode reveals the destination and itsExperimental badges without changing sync behavior. Strict mode refuses@@ -8475,16 +8480,19 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.appear in renderer state or logs. Identical and disjoint edits converge,conflicts remain reviewable, explicit deletions use tombstones, categoryopt-out is not deletion, and executable imports remain inactive until local- approval and mapping. Recovery never exposes a partial local apply.+ approval and mapping. Reopening Settings does not block on history, and+ unfinished non-sensitive connection choices survive navigation or reload.+ Recovery never exposes a partial local apply.- **Specs:** `04-ux/06-settings-ia.md`, `03-runtime/22-config-sync.md`,`03-runtime/14-secrets-storage.md`, `05-security/01-security.md`, ADR 0300,ADR 0301.- **Acceptance:** F (persistence), Security, Quality.- **Milestone:** M6+.-- **Status:** Draft; merge/crypto and in-process WebDAV conditional-write- coverage exists. The Settings visibility gate is automated by- `pnpm test:e2e:settings-scroll`; the remaining automation is the full- two-device process path and checkpoint-level local recovery fault injection.+- **Status:** Draft; merge/crypto, in-process WebDAV conditional-write+ coverage, and the two-device host/WebDAV path are automated by+ `pnpm test:e2e:config-sync`. The Settings visibility gate is automated by+ `pnpm test:e2e:settings-scroll`; full renderer-driven password persistence+ assertions and checkpoint-level local recovery fault injection remain.## 8. Traceability Matrixdiff --git a/docs/zh-CN/spec/03-runtime/22-config-sync.md b/docs/zh-CN/spec/03-runtime/22-config-sync.mdindex 73172c49e..4f9b9d51d 100644--- a/docs/zh-CN/spec/03-runtime/22-config-sync.md+++ b/docs/zh-CN/spec/03-runtime/22-config-sync.md@@ -70,6 +70,8 @@ Host 绝不会仅因为 UI flag 被设置就激活暂存的可执行内容。新设置 → 云同步提供 WebDAV endpoint 凭据、vault 密码、设备标签、服务器兼容模式、类别选择、能力测试、立即同步、解锁、暂停、文件夹映射、批准/拒绝、revision history/restore、vault 密码重新包裹以及断开连接控制。严格 CAS 是默认模式。选择追加式兼容模式会显示持续风险提示,并在保存配置前要求确认;其测试成功提示目录列表支持,而不是条件写支持。Renderer 将 `notConfigured`、`locked`、`upToDate`、`localChangesPending`、`syncing`、`offline`、`unsupportedServer`、`conflict`、`awaitingActivation`、`paused` 和 `error` 显示为不同状态。断开连接会保留本地数据,不会删除远端数据。+重新打开页面时,先用短时的 Renderer 缓存绘制最近一次脱敏的 Host 状态和历史记录,随后在后台刷新 Host。连接草稿(endpoint、用户名、远程目录、设备标签、兼容模式和类别选择)保存在 Renderer 本地存储中,因此离开页面或重载后未完成的表单仍会保留;Host 确认已保存的配置后,草稿会重新标记为已保存。WebDAV 应用密码留在 Host secret store 中,且只对同一 endpoint 和账户复用;Renderer 永远不会存储任一密码,只有新设备或已锁定设备需要打开 vault 时才需要输入 vault 密码。+手动同步会在运行期间报告它正在做什么。`configSync.progress` 携带当前阶段(`capture`、`download`、`merge`、`upload`、`apply` 或 `cleanup`)、该阶段已完成的单位数,以及已知时的字节数:`done`/`total` 在传输时计资源对象(追加式模式下计正在读取的设备 tip)、其他阶段计实体;`total` 为 0 表示该阶段无法预知总量;`bytesTotal` 为 0 表示字节数未知,这是下载阶段的常态。报告会节流,阶段变化绝不丢弃,状态事件与调用的返回值仍是终态信号。后台轮询不报告进度:只有手动路径有调用方在等待。凭据和 memory 默认未选中。设置预览报告 supported、excluded、secret-bearing、mapping-required 和 pending-activation 计数。原始秘密值、vault key 和备份密码永远不会跨过 Renderer 边界。diff --git a/docs/zh-CN/spec/04-ux/06-settings-ia.md b/docs/zh-CN/spec/04-ux/06-settings-ia.mdindex b257b49f4..bfbccfdf7 100644--- a/docs/zh-CN/spec/04-ux/06-settings-ia.md+++ b/docs/zh-CN/spec/04-ux/06-settings-ia.md@@ -308,6 +308,14 @@ Token 用量**不是设置目的地**(D335 / ADR 0173)。已完成回合历打开该项目后按最新活动列出匹配会话,以 8 条一批显示,而不是截断历史- 激活项目或项目会话返回聊天;归档和关闭仍使项目归档页保持打开+### 云同步++- **连接**:提供 WebDAV URL、用户名、应用密码、远程目录、设备标签、独立的备份/vault 密码和服务器兼容模式。默认使用严格 CAS;能力测试只使用临时远端对象。选择追加式兼容模式时显示持续风险提示,并在保存前要求确认。+- **可移植配置**:支持的类别默认选中;凭据和项目 memory 必须明确选择。预览显示 supported、excluded、secret-bearing、mapping-required 和 pending-approval 计数。+- **安全**:页面不渲染原始凭据或 vault key。导入的 MCP、skills、subagents、plugins、automations 和项目作用域数据在本地激活审批及必要的文件夹映射完成前保持暂存。断开连接保留本地和远端数据。+- **状态与恢复**:显示已配置、已锁定、同步中、离线、不支持服务器、冲突、等待激活、暂停和错误等不同状态。用户可以立即同步、解锁、暂停本设备、批准/拒绝暂存项目以及断开连接。存在待处理状态时,页面不会根据旧的成功记录暗示已经收敛。+- **快速重返和草稿**:Host 在后台刷新时,先用短时本地缓存绘制最近一次脱敏的状态和历史记录。endpoint、用户名、远程目录、设备标签、兼容模式和类别选择保存在 Renderer 本地存储中,因此离开页面或重载后未完成的表单仍会保留。WebDAV 应用密码继续保存在 Host 管理的 secret storage 中,且只对同一 endpoint 和账户复用;vault 密码永远不会写入 Renderer 存储。+### 信息- app/host/protocol版本+开放日志- **问题反馈**行:一项操作在系统浏览器中打开 GitHub bug 表单。diff --git a/package.json b/package.jsonindex 561e3d4cc..53749ac50 100644--- a/package.json+++ b/package.json@@ -41,6 +41,7 @@"test:e2e:oauth-retry": "node --test apps/desktop/test/anthropic-oauth-retry.test.mjs","test:e2e:boot": "node scripts/e2e-electron-boot.mjs","test:e2e:settings-scroll": "node scripts/e2e-settings-scroll.mjs",+ "test:e2e:config-sync": "node scripts/e2e-config-sync-multidevice.mjs","test:e2e:layout": "node scripts/e2e-three-column-layout.mjs","test:e2e:window-controls": "node scripts/e2e-window-controls.mjs","test:e2e:work-panel-reorder": "node scripts/e2e-work-panel-reorder.mjs",diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex a658b13c1..e999d3ef7 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -748,6 +748,7 @@ sklm: {"Dieser Server kann bedingte Schreibvorgänge nicht erzwingen. Der Kompatibilitätsmodus behält den Verlauf, bietet aber kein atomares Compare-and-Swap. Fortfahren?",username: "Username",appPassword: "App password",+ appPasswordSavedHint: "Sicher auf diesem Gerät gespeichert. Leer lassen, um es wiederzuverwenden.",directory: "Remote directory",deviceLabel: "Device label",defaultDevice: "This device",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 56e272229..3b73354a8 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -1025,6 +1025,7 @@ sklm: {"This server mode cannot enforce conditional writes. Compatibility mode retains history but cannot provide atomic compare-and-swap. Continue?",username: "Username",appPassword: "App password",+ appPasswordSavedHint: "Saved securely on this device. Leave blank to reuse it.",directory: "Remote directory",deviceLabel: "Device label",defaultDevice: "This device",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 317f205a5..08a502cad 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -748,6 +748,7 @@ sklm: {"Este servidor no puede aplicar escrituras condicionales. El modo de compatibilidad conserva el historial, pero no ofrece un compare-and-swap atómico. ¿Continuar?",username: "Username",appPassword: "App password",+ appPasswordSavedHint: "Guardada de forma segura en este dispositivo. Déjala vacía para reutilizarla.",directory: "Remote directory",deviceLabel: "Device label",defaultDevice: "This device",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex f2fdc09fb..b03eb810d 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -748,6 +748,7 @@ sklm: {"Ce serveur ne peut pas appliquer les écritures conditionnelles. Le mode de compatibilité conserve l’historique, mais ne fournit pas de compare-and-swap atomique. Continuer ?",username: "Username",appPassword: "App password",+ appPasswordSavedHint: "Enregistré de façon sécurisée sur cet appareil. Laissez vide pour le réutiliser.",directory: "Remote directory",deviceLabel: "Device label",defaultDevice: "This device",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex a7036def6..472a6b034 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -756,6 +756,7 @@ sklm: {"이 서버는 조건부 쓰기를 적용할 수 없습니다. 호환 모드는 기록을 보존하지만 원자적 compare-and-swap을 제공하지 않습니다. 계속하시겠습니까?",username: "Username",appPassword: "App password",+ appPasswordSavedHint: "이 기기에 안전하게 저장됩니다. 재사용하려면 비워 두세요.",directory: "Remote directory",deviceLabel: "Device label",defaultDevice: "This device",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 4869d1d4b..f35ae8faa 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -993,6 +993,7 @@ export const ptBR = {appendOnlyConfirm: "Este modo de servidor não consegue impor gravações condicionais. O modo de compatibilidade preserva o histórico, mas não fornece compare-and-swap atômico. Continuar?",username: "Nome de usuário",appPassword: "Senha do aplicativo",+ appPasswordSavedHint: "Salva com segurança neste dispositivo. Deixe em branco para reutilizá-la.",directory: "Diretório remoto",deviceLabel: "Identificação do dispositivo",defaultDevice: "Este dispositivo",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 161c6fbd6..8e14e561a 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -755,6 +755,7 @@ sklm: {"Bu sunucu koşullu yazmaları uygulayamıyor. Uyumluluk modu geçmişi korur ancak atomik compare-and-swap sağlayamaz. Devam edilsin mi?",username: "Kullanıcı adı",appPassword: "Uygulama parolası",+ appPasswordSavedHint: "Bu cihazda güvenle saklanır. Yeniden kullanmak için boş bırakın.",directory: "Uzak dizin",deviceLabel: "Cihaz etiketi",defaultDevice: "Bu cihaz",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 581e42a54..444d6b042 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -742,6 +742,7 @@ sklm: {appendOnlyConfirm: "此服务器无法执行条件写入。兼容模式会保留历史,但无法提供原子比较并交换。要继续吗?",username: "用户名",appPassword: "应用密码",+ appPasswordSavedHint: "已安全保存在本设备。留空即可复用。",directory: "远程目录",deviceLabel: "设备名称",defaultDevice: "此设备",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 4c3bc3b7a..b1d53530a 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -742,6 +742,7 @@ sklm: {appendOnlyConfirm: "此伺服器無法執行條件寫入。相容模式會保留歷史,但無法提供原子比較並交換。要繼續嗎?",username: "使用者名稱",appPassword: "應用程式密碼",+ appPasswordSavedHint: "已安全儲存在此裝置。留白即可重複使用。",directory: "遠端目錄",deviceLabel: "裝置名稱",defaultDevice: "此裝置",diff --git a/scripts/README.md b/scripts/README.mdindex d7c6d8472..33aaa6005 100644--- a/scripts/README.md+++ b/scripts/README.md@@ -54,6 +54,7 @@ they cover are specified in| `e2e-plan-ui.mjs` | `pnpm test:e2e:plan-ui` | Plan approval through the rendered UI || `e2e-electron-boot.mjs` | `pnpm test:e2e:boot` | Electron boot probe || `e2e-provider-recovery.mjs` | `node scripts/e2e-provider-recovery.mjs` | Isolated desktop with a localhost fault-injection provider: socket failures, interrupted streams, Responses recovery, exhausted retries, Continue, and recovery across eleven real Read calls. Requires a built desktop/runtime and host binary (`PI_DESKTOP_HOST_BIN` when outside the checkout); retains screenshots and JSON under `.artifacts/issue-699/` |+| `e2e-config-sync-multidevice.mjs` | `pnpm test:e2e:config-sync` | Two isolated host-core devices against an ephemeral local WebDAV fixture; covers encrypted sync, new-device approval, cross-device edits, conditional requests, and ciphertext-only remote storage || `e2e-supervision.mjs` | `pnpm test:e2e:supervision` | Process supervision and restart behavior || `e2e-subagents.mjs` | `pnpm test:e2e:subagents` | Subagent registry over RPC, then through the real loader (D202) || `e2e-agent-live.mjs` | `node scripts/e2e-agent-live.mjs` | Live streaming chat through agent-runtime + host-core. Requires `PI_DESKTOP_TEST_API_KEY`, `PI_DESKTOP_TEST_BASE_URL`, and `PI_DESKTOP_TEST_MODEL` (no defaults), so it has no `pnpm` alias |diff --git a/scripts/e2e-config-sync-multidevice.mjs b/scripts/e2e-config-sync-multidevice.mjsnew file mode 100644index 000000000..5f8b40277--- /dev/null+++ b/scripts/e2e-config-sync-multidevice.mjs@@ -0,0 +1,323 @@+#!/usr/bin/env node+/**+ * Two-device configuration-sync E2E against an ephemeral local WebDAV server.+ *+ * The fixture is intentionally in this script instead of using a real account:+ * it proves conditional writes, encrypted remote objects, and the approval+ * boundary without network credentials or production data. Each Host process+ * has its own data directory, while both point at the same WebDAV collection.+ */+import assert from "node:assert/strict";+import { createServer } from "node:http";+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { Host, resolveHostBinary } from "./e2e/host.mjs";++const PASSWORD = "portable-backup-password";+const WEBDAV_USERNAME = "alice";+const WEBDAV_PASSWORD = "webdav-fixture-password";++function xmlEscape(value) {+ return value+ .replaceAll("&", "&")+ .replaceAll("<", "<")+ .replaceAll(">", ">")+ .replaceAll('"', """)+ .replaceAll("'", "'");+}++async function readBody(request) {+ const chunks = [];+ for await (const chunk of request) chunks.push(chunk);+ return Buffer.concat(chunks);+}++function normalizePath(rawPath) {+ return decodeURIComponent(rawPath).replace(/^\/+|\/+$/g, "");+}++async function startWebDavFixture() {+ const state = {+ collections: new Set(["dav"]),+ objects: new Map(),+ nextEtag: 0,+ requests: [],+ };++ const server = createServer(async (request, response) => {+ const path = normalizePath(+ new URL(request.url ?? "/", "http://127.0.0.1").pathname,+ );+ const method = request.method ?? "GET";+ const body = method === "PUT" ? await readBody(request) : Buffer.alloc(0);+ state.requests.push({ method, path });++ const send = (status, payload = Buffer.alloc(0), headers = {}) => {+ response.writeHead(status, {+ "Content-Length": payload.length,+ Connection: "close",+ ...headers,+ });+ response.end(payload);+ };++ const expectedAuthorization = `Basic ${Buffer.from(+ `${WEBDAV_USERNAME}:${WEBDAV_PASSWORD}`,+ ).toString("base64")}`;+ if (request.headers.authorization !== expectedAuthorization) {+ return send(401, Buffer.alloc(0), { "WWW-Authenticate": 'Basic realm="fixture"' });+ }++ if (method === "MKCOL") {+ const parent = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";+ if (parent && !state.collections.has(parent)) return send(409);+ if (state.collections.has(path)) return send(405);+ state.collections.add(path);+ return send(201);+ }++ if (method === "GET") {+ const value = state.objects.get(path);+ if (!value) return send(404);+ return send(200, value.body, { ETag: `"${value.etag}"` });+ }++ if (method === "PROPFIND") {+ if (!state.collections.has(path)) return send(404);+ const prefix = `${path}/`;+ const entries = new Set([`${path}/`]);+ for (const candidate of [...state.collections, ...state.objects.keys()]) {+ if (+ candidate.startsWith(prefix) &&+ !candidate.slice(prefix.length).includes("/")+ ) {+ entries.add(candidate);+ }+ }+ const xml = [+ '<?xml version="1.0" encoding="utf-8"?>',+ '<D:multistatus xmlns:D="DAV:">',+ ...[...entries].map(+ (entry) => `<D:response><D:href>/${xmlEscape(entry)}</D:href></D:response>`,+ ),+ "</D:multistatus>",+ ].join("");+ return send(207, Buffer.from(xml), { "Content-Type": "application/xml" });+ }++ if (method === "PUT") {+ const existing = state.objects.get(path);+ const ifNoneMatch = request.headers["if-none-match"];+ const ifMatch = request.headers["if-match"];+ if (+ (ifNoneMatch === "*" && existing) ||+ (ifMatch && (!existing || ifMatch !== `"${existing.etag}"`))+ ) {+ return send(412);+ }+ const etag = ++state.nextEtag;+ state.objects.set(path, { body, etag });+ return send(201, Buffer.alloc(0), { ETag: `"${etag}"` });+ }++ if (method === "DELETE") {+ state.objects.delete(path);+ return send(204);+ }++ return send(405);+ });++ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ const address = server.address();+ assert.equal(typeof address, "object");+ return {+ endpoint: `http://127.0.0.1:${address.port}/dav/`,+ state,+ close: () =>+ new Promise((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve())),+ ),+ };+}++function syncConfig(endpoint, deviceLabel, appPassword, backupPassword = PASSWORD) {+ const config = {+ endpoint,+ username: WEBDAV_USERNAME,+ directory: "pi-desktop",+ deviceLabel,+ backupPassword,+ categories: {+ application: true,+ providers: true,+ credentials: false,+ mcp: true,+ skills: true,+ subagents: true,+ instructions: true,+ projects: true,+ plugins: true,+ automation: true,+ memory: false,+ },+ includeSecrets: false,+ includeMemory: false,+ automaticSync: false,+ remoteMode: "strict",+ };+ if (appPassword !== undefined) config.appPassword = appPassword;+ return config;+}++async function approveAll(host, state) {+ let next = state;+ for (let attempt = 0; next.pendingApprovals.length > 0; attempt += 1) {+ assert.ok(attempt < 64, "approval queue did not converge");+ const item = next.pendingApprovals[0];+ next = await host.call(+ "configSync.approve",+ { approvalId: item.id, digest: item.digest },+ 120_000,+ );+ }+ return next;+}++const fixture = await startWebDavFixture();+const dataRoot = await mkdtemp(join(tmpdir(), "pi-config-sync-multidevice-"));+const hostBinary = resolveHostBinary();+const hostA = new Host(hostBinary, join(dataRoot, "device-a"));+const hostB = new Host(hostBinary, join(dataRoot, "device-b"));+const previousAgentsDir = process.env.PI_DESKTOP_AGENTS_DIR;+process.env.PI_DESKTOP_AGENTS_DIR = join(dataRoot, "agents");++try {+ await Promise.all([hostA.start(), hostB.start()]);+ // The fixture intentionally uses loopback HTTP. Set the same explicit+ // relaxed LAN policy a user would choose before entering a plaintext URL.+ await Promise.all([+ hostA.call("settings.set", { networkPolicy: { mode: "relaxed" } }),+ hostB.call("settings.set", { networkPolicy: { mode: "relaxed" } }),+ ]);++ const configuredA = await hostA.call(+ "configSync.configure",+ syncConfig(fixture.endpoint, "Device A", WEBDAV_PASSWORD),+ 120_000,+ );+ assert.equal(configuredA.configured, true);+ assert.equal(configuredA.remoteMode, "strict");++ // Re-saving with the same endpoint/account and no appPassword must reuse+ // the Host-owned WebDAV secret instead of asking the renderer for it again.+ const reusedPasswordA = await hostA.call(+ "configSync.configure",+ syncConfig(fixture.endpoint, "Device A", undefined, ""),+ 120_000,+ );+ assert.equal(reusedPasswordA.configured, true);++ await hostA.call("configSync.syncNow", {}, 120_000);+ const { provider: sharedProvider } = await hostA.call("providers.create", {+ name: "Shared provider",+ vendorKey: "webdav-fixture",+ type: "openai_compatible",+ protocol: "openai_compatible",+ authKind: "api_key_and_base_url",+ secretValue: "fixture-provider-secret",+ baseUrl: "http://127.0.0.1:9/v1",+ apiStyle: "chat_completions",+ defaultModelId: "shared-model",+ models: [{+ id: "shared-model",+ contextWindow: 128_000,+ maxTokens: 8_192,+ thinkingLevels: ["off"],+ defaultThinkingLevel: "off",+ }],+ });+ await hostA.call("configSync.syncNow", {}, 120_000);++ const configuredB = await hostB.call(+ "configSync.configure",+ syncConfig(fixture.endpoint, "Device B", WEBDAV_PASSWORD),+ 120_000,+ );+ assert.equal(configuredB.configured, true);+ assert.equal(configuredB.endpoint, fixture.endpoint);++ const reusedPasswordB = await hostB.call(+ "configSync.configure",+ syncConfig(fixture.endpoint, "Device B", undefined, ""),+ 120_000,+ );+ assert.equal(reusedPasswordB.configured, true);++ let stateB = await hostB.call("configSync.syncNow", {}, 120_000);+ assert.ok(+ stateB.pendingApprovals.some((item) => item.entityId.includes(sharedProvider.id)),+ `device B should stage device A's provider for local approval (provider=${sharedProvider.id}, pending=${JSON.stringify(+ stateB.pendingApprovals.map((item) => ({+ entityId: item.entityId,+ label: item.label,+ reason: item.reason,+ })),+ )})`,+ );+ stateB = await approveAll(hostB, stateB);+ assert.equal(stateB.pendingApprovals.length, 0);++ const providersB = await hostB.call("providers.list", { includeDisabled: true });+ assert.ok(+ providersB.providers.some((provider) => provider.name === "Shared provider"),+ "approved provider should be available on device B",+ );++ await hostB.call("settings.set", { theme: "light" });+ const stateAfterLocalEdit = await hostB.call("configSync.syncNow", {}, 120_000);+ assert.ok(["upToDate", "localChangesPending"].includes(stateAfterLocalEdit.status));+ const stateA = await hostA.call("configSync.syncNow", {}, 120_000);+ assert.notEqual(stateA.status, "error");++ const immutableFiles = [...fixture.state.objects.keys()].filter(+ (path) => path.includes("/revisions/") || path.includes("/objects/"),+ );+ assert.ok(+ immutableFiles.length > 0,+ "WebDAV should contain encrypted immutable files",+ );+ const remotePayloads = [...fixture.state.objects.values()].map(({ body }) => body.toString("utf8"));+ assert.ok(+ remotePayloads.every((payload) => !payload.includes("Shared provider")),+ "WebDAV payloads must not expose provider labels in plaintext",+ );+ assert.ok(+ remotePayloads.every((payload) => !payload.includes("fixture-provider-secret")),+ "WebDAV payloads must not expose provider secrets in plaintext",+ );+ assert.ok(+ fixture.state.requests.some(({ method }) => method === "PROPFIND"),+ "fixture should observe WebDAV capability/listing requests",+ );+ console.log(+ "CONFIG_SYNC_MULTIDEVICE " ++ JSON.stringify({+ endpoint: fixture.endpoint,+ devices: 2,+ providerId: sharedProvider.id,+ remoteObjects: immutableFiles.length,+ requests: fixture.state.requests.length,+ statusA: stateA.status,+ statusB: stateAfterLocalEdit.status,+ }),+ );+} finally {+ await Promise.all([hostA.stop(), hostB.stop()]).catch(() => undefined);+ await fixture.close().catch(() => undefined);+ await rm(dataRoot, { recursive: true, force: true });+ if (previousAgentsDir === undefined) delete process.env.PI_DESKTOP_AGENTS_DIR;+ else process.env.PI_DESKTOP_AGENTS_DIR = previousAgentsDir;+}