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
1 change: 1 addition & 0 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ <h3 id="setup-conflict-title">Resolve setup conflict</h3>
<p id="setup-conflict-guidance"></p>
<div class="setup-recovery-actions">
<button id="restore-setup-definition" class="primary" type="button" hidden>Restore Journal’s version (keep backup)</button>
<button id="retry-setup-conflict" type="button">Try again</button>
<button id="switch-setup-collection" type="button" hidden>Switch collection</button>
<button id="cancel-setup-conflict" type="button">Cancel</button>
</div>
Expand Down
2 changes: 1 addition & 1 deletion public/journal.css

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

88 changes: 40 additions & 48 deletions src/setup-conflicts.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
describeError,
isMdbaseError,
revisionOf,
type Mdbase,
type MdbaseApplicationConnection,
type MdbaseSetupConflict,
Expand All @@ -15,10 +16,14 @@ export interface BundledSetupDefinition {
readonly document: string;
}

interface ReviewedSetupDefinition extends BundledSetupDefinition {
readonly reviewedRevision?: string;
}

export interface SetupConflictGuidance {
readonly collectionId: string;
readonly conflicts: readonly MdbaseSetupConflict[];
readonly restorable: readonly BundledSetupDefinition[];
readonly restorable: readonly ReviewedSetupDefinition[];
readonly manualOnly: readonly MdbaseSetupConflict[];
readonly canRestoreWithBackup: boolean;
readonly backupFolder: string | null;
Expand Down Expand Up @@ -77,28 +82,28 @@ export function backupFolderFor(connection: MdbaseApplicationConnection | null):
return allowed ? `${allowed}/${DEFAULT_BACKUP_FOLDER}` : null;
}

/** Non-adoptable setup conflicts that leave the shared setup review stuck at only "Try again". */
/** Match a remapped target only when Core's review stages Journal's exact bytes there. */
export function inspectSetupConflicts(
plan: MdbaseSetupPlan,
collectionId: string,
connection: MdbaseApplicationConnection | null,
staged: MdbaseSetupPlan["staged"] = plan.staged,
): SetupConflictGuidance | null {
if (plan.canApply || plan.conflicts.length === 0) return null;
if (plan.refusal?.code === "setup_forbidden" || plan.refusal?.code === "installed_newer") return null;
const conflicts = plan.conflicts.filter(
conflict => !conflict.adoptable && !Object.hasOwn(plan.adoptable, conflict.target),
);
if (conflicts.length === 0) return null;
if (plan.refusal?.code === "installed_newer" || plan.refusal?.code === "setup_downgrade") return null;
const conflicts = plan.conflicts;
const bundled = bundledSetupDefinitions();
const restorable: BundledSetupDefinition[] = [];
const restorable: ReviewedSetupDefinition[] = [];
const manualOnly: MdbaseSetupConflict[] = [];
for (const conflict of conflicts) {
const definition = bundled.get(conflict.target);
if (definition) restorable.push(definition);
const stagedDocument = staged.find(item => item.path === conflict.target)?.document;
const definition = bundled.get(conflict.target) ?? [...bundled.values()].find(item => item.document === stagedDocument);
const reviewedRevision = conflict.adoptable?.digest ?? (Object.hasOwn(plan.adoptable, conflict.target) ? plan.adoptable[conflict.target] : undefined);
if (definition) restorable.push({...definition, target: conflict.target, ...(reviewedRevision ? {reviewedRevision} : {})});
else manualOnly.push(conflict);
}
const live = connection !== null && connection.id === collectionId && connection.isCurrent();
const canManage = live && connection.records.hello.grant.capabilities.includes("definitions.manage");
const canManage = live && plan.refusal?.code !== "setup_forbidden" && connection.records.hello.grant.capabilities.includes("definitions.manage");
const backupFolder = live ? backupFolderFor(connection) : null;
const canRestoreWithBackup = restorable.length > 0 && canManage && backupFolder !== null;
const unavailableReason: SetupConflictGuidance["unavailableReason"] =
Expand Down Expand Up @@ -196,9 +201,9 @@ function errorDetail(error: unknown, fallback: string): string {
* Never overwrites a hand-edited file if saving its backup fails.
*/
export async function restoreSetupDefinitions(
mdbase: Pick<Mdbase, "connection" | "assess">,
mdbase: Pick<Mdbase, "connection">,
collectionId: string,
targets: readonly string[],
definitions: readonly ReviewedSetupDefinition[],
options: RestoreSetupOptions = {},
): Promise<RestoreSetupResult> {
const connection = mdbase.connection(collectionId);
Expand All @@ -212,69 +217,57 @@ export async function restoreSetupDefinitions(
if (!backupFolder) {
throw new Error("Journal can't save a backup copy in this collection, so nothing was overwritten.");
}
const bundled = bundledSetupDefinitions();
const encoder = new TextEncoder();
const now = options.now ?? (() => new Date());
const readOptions = options.signal ? { signal: options.signal } : undefined;
const restored: RestoredSetupDefinition[] = [];

for (const target of targets) {
for (const canonical of definitions) {
const {target, reviewedRevision} = canonical;
options.signal?.throwIfAborted();
const canonical = bundled.get(target);
if (!canonical) {
throw new Error(`Journal does not ship a definition for ${target}. Resolve it by hand.`);
}
let existing: { text: string; revision: string } | null = null;
let existing: { text: string; revision: string };
try {
const view = await connection.records.resources.get(target, readOptions);
if (typeof view.text !== "string") {
if (view.path !== target || typeof view.text !== "string" || revisionOf(view.text) !== view.revision) {
throw new Error(`Could not read the current contents of ${target}, so Journal left your file unchanged.`);
}
existing = { text: view.text, revision: view.revision };
} catch (error) {
if (!isMdbaseError(error, "not_found")) {
throw new Error(`Could not read ${target} before restoring: ${errorDetail(error, "nothing was changed.")}`);
}
throw new Error(`Could not read ${target} before restoring: ${errorDetail(error, "nothing was changed.")}`);
}
if (!connection.isCurrent()) {
throw new Error("This collection changed while restoring. Nothing further was changed.");
}
if (existing && existing.text === canonical.document) {
if (existing.text === canonical.document) {
restored.push(Object.freeze({ target, backupPath: null, unchanged: true }));
continue;
}

let backupPath: string | null = null;
if (existing) {
backupPath = backupPathFor(target, now(), backupFolder, options.suffix?.());
try {
const upload = await connection.files.upload(
backupPath,
encoder.encode(existing.text),
options.signal ? { signal: options.signal } : undefined,
);
await upload.confirmed;
} catch (error) {
throw new Error(
`Could not save a backup copy of ${target} (${errorDetail(error, "backup failed")}), so Journal left your file unchanged.`,
);
}
if (!connection.isCurrent()) {
throw new Error(`This collection changed after saving your backup at ${backupPath}. Your original file was left unchanged.`);
}
if (reviewedRevision && existing.revision !== reviewedRevision) {
throw new Error(`${target} changed since setup was reviewed. Choose Try again to review the current file.`);
}
const backupPath = backupPathFor(target, now(), backupFolder, options.suffix?.());
try {
const upload = await connection.files.upload(backupPath, encoder.encode(existing.text), readOptions);
await upload.confirmed;
} catch (error) {
throw new Error(
`Could not save a backup copy of ${target} (${errorDetail(error, "backup failed")}), so Journal left your file unchanged.`,
);
}
if (!connection.isCurrent()) {
throw new Error(`This collection changed after saving your backup at ${backupPath}. Your original file was left unchanged.`);
}

try {
const write = await connection.records.resources.put(
target,
canonical.document,
existing
? { baseRevision: existing.revision, ...(options.signal ? { signal: options.signal } : {}) }
: { mustNotExist: true, ...(options.signal ? { signal: options.signal } : {}) },
{ baseRevision: existing.revision, ...(options.signal ? { signal: options.signal } : {}) },
);
await write.confirmed;
} catch (error) {
const backupNote = backupPath ? ` Your backup copy was saved to ${backupPath}.` : "";
const backupNote = ` Your backup copy was saved to ${backupPath}.`;
if (isMdbaseError(error, "conflict")) {
throw new Error(`${target} changed while restoring, so Journal didn't overwrite it.${backupNote} Try again.`);
}
Expand All @@ -284,6 +277,5 @@ export async function restoreSetupDefinitions(
restored.push(Object.freeze({ target, backupPath, unchanged: false }));
}

await mdbase.assess(options.signal ? { signal: options.signal } : undefined);
return Object.freeze({ restored: Object.freeze(restored) });
}
67 changes: 52 additions & 15 deletions src/view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {DELETED_ENTRY_NOTICE, JournalCatalogError, JournalData, type JournalEntr
import {DraftOpens} from "./draft-opens.js";
import {connectionNotice, connectionNoticeLabels} from "./connection-notice.js";
import {
bundledSetupDefinitions,
inspectSetupConflicts,
restoreConfirmationText,
restoreSetupDefinitions,
Expand Down Expand Up @@ -57,6 +58,7 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase:
let setupConflictCollectionId: string | null = null;
let setupConflictChecking = false;
let setupConflictController: AbortController | null = null;
let recheckingSetup = false;
let restoringSetup = false;
let switchingSetupCollection = false;
let setupConflictFeedback: string | null = null;
Expand Down Expand Up @@ -291,18 +293,25 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase:
element("menu-connection").textContent = openId && catalogProblem ? `${catalogProblem.title}. ${catalogProblem.detail}` :
openId ? `Notes save to ${name}.` : "Notes stay on this device until a collection is open.";
const recovery = element("setup-conflict-recovery");
// The shared panel still owns normal setup and its collection navigation.
// While Journal reviews a conflict, hide the shared replacement controls.
element("collection-panel").toggleAttribute("data-journal-recovery", !!setupConflictController || !!setupConflict);
recovery.hidden = !setupConflict;
if (setupConflict) {
element("setup-conflict-guidance").textContent = setupConflictGuidanceText(setupConflict);
const restoreButton = element<HTMLButtonElement>("restore-setup-definition");
restoreButton.hidden = !setupConflict.canRestoreWithBackup;
restoreButton.textContent = restoringSetup ? "Restoring…" : "Restore Journal’s version (keep backup)";
restoreButton.disabled = restoringSetup || switchingSetupCollection;
const busy = restoringSetup || switchingSetupCollection || recheckingSetup;
restoreButton.disabled = busy || !!setupConflictController;
const switchButton = element<HTMLButtonElement>("switch-setup-collection");
switchButton.hidden = state?.signIn?.state !== "paired";
switchButton.textContent = switchingSetupCollection ? "Switching…" : "Switch collection";
switchButton.disabled = restoringSetup || switchingSetupCollection;
element<HTMLButtonElement>("cancel-setup-conflict").disabled = restoringSetup || switchingSetupCollection;
switchButton.disabled = busy;
const retrySetup = element<HTMLButtonElement>("retry-setup-conflict");
retrySetup.disabled = busy;
retrySetup.textContent = recheckingSetup ? "Checking…" : "Try again";
element<HTMLButtonElement>("cancel-setup-conflict").disabled = busy;
const feedback = element("setup-conflict-feedback");
feedback.hidden = !setupConflictFeedback;
feedback.textContent = setupConflictFeedback ?? "";
Expand Down Expand Up @@ -457,15 +466,27 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase:
setupConflictController?.abort();
const controller = new (document.defaultView?.AbortController ?? AbortController)();
setupConflictController = controller;
void mdbase.setup.plan({signal: controller.signal}).then(plan => {
if (disposed || controller.signal.aborted || setupConflictController !== controller) return;
const signal = controller.signal;
const inspect = async () => {
const plan = await mdbase.setup.plan({signal});
const adopt = Object.fromEntries(Object.entries(plan.adoptable).filter(([target]) => !bundledSetupDefinitions().has(target)));
let staged = plan.staged;
if (plan.refusal?.code === "setup_conflict" && Object.keys(adopt).length) {
// A dry replan gives the exact staged document at Core's resolved path.
// It never applies the SDK's unbacked replacement.
try {staged = (await mdbase.setup.plan({adopt, signal})).staged;} catch {/* Unknown paths stay manual. */}
}
const currentPhase = snapshot()?.phase;
if (currentPhase?.kind !== "needs_setup" || currentPhase.collectionId !== collectionId) return;
setupConflict = inspectSetupConflicts(plan, collectionId, mdbase.connection(collectionId));
render();
}, () => {
if (signal.aborted || currentPhase?.kind !== "needs_setup" || currentPhase.collectionId !== collectionId) return;
setupConflict = inspectSetupConflicts(plan, collectionId, mdbase.connection(collectionId), staged);
};
void inspect().catch(() => {
if (disposed || controller.signal.aborted || setupConflictController !== controller) return;
setupConflict = null;
// An existing review stays in place if a recheck fails.
if (setupConflict) setupConflictFeedback = "Could not check setup right now. Try again.";
}).finally(() => {
if (disposed || controller.signal.aborted || setupConflictController !== controller) return;
setupConflictController = null;
render();
});
}
Expand All @@ -484,7 +505,7 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase:
setupConflictCollectionId = currentPhase.collectionId;
setupConflictChecking = checking;
if (entered) {setupConflict = null; setupConflictFeedback = null;}
if ((entered || settled) && !restoringSetup) inspectSetupPlan(currentPhase.collectionId);
if ((entered || settled) && !restoringSetup && !recheckingSetup) inspectSetupPlan(currentPhase.collectionId);
} else {
setupConflictController?.abort();
setupConflictController = null;
Expand Down Expand Up @@ -615,13 +636,18 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase:
});
listen(element("restore-setup-definition"), "click", () => {
const active = setupConflict;
if (!mdbase || disposed || restoringSetup || switchingSetupCollection || !active?.canRestoreWithBackup) return;
if (!mdbase || disposed || setupConflictController || restoringSetup || switchingSetupCollection || recheckingSetup || !active?.canRestoreWithBackup) return;
restoringSetup = true; setupConflictFeedback = null; setupConflictNotice = null; render();
void restoreSetupDefinitions(mdbase, active.collectionId, active.restorable.map(item => item.target), {signal: caller.signal}).then(result => {
void restoreSetupDefinitions(mdbase, active.collectionId, active.restorable, {signal: caller.signal}).then(async result => {
if (disposed) return;
const confirmation = restoreConfirmationText(result);
setupConflictNotice = confirmation;
setupConflictFeedback = confirmation;
try {await mdbase.assess({signal: caller.signal});}
catch {
setupConflictNotice = `${confirmation} Journal could not recheck setup. Open Settings to try again.`;
setupConflictFeedback = setupConflictNotice;
}
}, error => {
if (disposed) return;
setupConflictFeedback = error instanceof Error && error.message.trim() ? error.message : "Could not restore Journal’s definition. Your file was left unchanged.";
Expand All @@ -633,8 +659,19 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase:
render();
});
});
listen(element("retry-setup-conflict"), "click", () => {
const active = setupConflict;
if (!mdbase || !active || disposed || restoringSetup || switchingSetupCollection || recheckingSetup) return;
recheckingSetup = true; setupConflictFeedback = null; render();
void mdbase.assess({signal: caller.signal}).then(() => {
const phase = snapshot()?.phase;
if (!disposed && phase?.kind === "needs_setup" && phase.collectionId === active.collectionId) inspectSetupPlan(active.collectionId);
}, () => {
if (!disposed && setupConflict === active) setupConflictFeedback = "Could not check setup right now. Try again.";
}).finally(() => {recheckingSetup = false; render();});
});
listen(element("switch-setup-collection"), "click", () => {
if (!mdbase || disposed || restoringSetup || switchingSetupCollection) return;
if (!mdbase || disposed || restoringSetup || switchingSetupCollection || recheckingSetup) return;
switchingSetupCollection = true; setupConflictFeedback = null; render();
void mdbase.chooseAnother({signal: caller.signal}).catch(error => {
if (disposed) return;
Expand All @@ -648,7 +685,7 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase:
});
});
listen(element("cancel-setup-conflict"), "click", () => {
if (disposed || restoringSetup || switchingSetupCollection) return;
if (disposed || restoringSetup || switchingSetupCollection || recheckingSetup) return;
setupConflictNotice = null;
setupConflictFeedback = null;
if (menu.open) menu.close();
Expand Down
Loading