Skip to content

Commit 8a0dccf

Browse files
feat(studio): add external conflict recovery UI (#2992)
1 parent a99caad commit 8a0dccf

2 files changed

Lines changed: 371 additions & 0 deletions

File tree

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
// @vitest-environment happy-dom
2+
import { act } from "react";
3+
import { createRoot } from "react-dom/client";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { StudioFileConflictError } from "../utils/studioSaveDiagnostics";
6+
import type { ExternalFileChangeCoordinatorHandle } from "../hooks/useExternalFileChangeCoordinator";
7+
import { ExternalFileConflictBanner } from "./ExternalFileConflictBanner";
8+
9+
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
10+
11+
describe("ExternalFileConflictBanner", () => {
12+
afterEach(() => {
13+
document.body.replaceChildren();
14+
vi.restoreAllMocks();
15+
});
16+
17+
it("keeps destructive choices explicit and exposes both full versions for review", async () => {
18+
const container = document.createElement("div");
19+
document.body.append(container);
20+
const root = createRoot(container);
21+
const conflict = new StudioFileConflictError({
22+
filePath: "index.html",
23+
currentVersion: "v2",
24+
currentContent: "<html>external</html>",
25+
attemptedContent: "<html>studio</html>",
26+
});
27+
const coordinator: ExternalFileChangeCoordinatorHandle = {
28+
blocked: { status: "conflict", generation: 1, error: conflict, payload: {} },
29+
retry: vi.fn(async () => undefined),
30+
useExternalFile: vi.fn(async () => undefined),
31+
keepStudioFile: vi.fn(async () => undefined),
32+
};
33+
34+
await act(async () => root.render(<ExternalFileConflictBanner coordinator={coordinator} />));
35+
expect(document.querySelector('[role="alert"]')?.textContent).toContain(
36+
"Preview is paused so neither version is lost",
37+
);
38+
expect(document.body.textContent).toContain("Discard Studio edits and reload file");
39+
expect(document.body.textContent).toContain("Overwrite file with Studio version");
40+
41+
const review = Array.from(document.querySelectorAll("button")).find((button) =>
42+
button.textContent?.includes("Review or export both"),
43+
);
44+
await act(async () => review?.click());
45+
expect(document.querySelector('[role="dialog"]')).not.toBeNull();
46+
expect(Array.from(document.querySelectorAll("textarea"), (field) => field.value)).toEqual([
47+
"<html>external</html>",
48+
"<html>studio</html>",
49+
]);
50+
51+
await act(async () => root.unmount());
52+
});
53+
54+
it("lets authors review and export the local candidate after a drain failure", async () => {
55+
const container = document.createElement("div");
56+
document.body.append(container);
57+
const root = createRoot(container);
58+
const coordinator: ExternalFileChangeCoordinatorHandle = {
59+
blocked: {
60+
status: "failed",
61+
generation: 1,
62+
path: "index.html",
63+
error: new Error("offline"),
64+
payload: {},
65+
studioContent: "<html>recover me</html>",
66+
recovered: false,
67+
},
68+
retry: vi.fn(async () => undefined),
69+
useExternalFile: vi.fn(async () => undefined),
70+
keepStudioFile: vi.fn(async () => undefined),
71+
};
72+
73+
await act(async () => root.render(<ExternalFileConflictBanner coordinator={coordinator} />));
74+
const review = Array.from(document.querySelectorAll("button")).find((button) =>
75+
button.textContent?.includes("Review or export Studio draft"),
76+
);
77+
await act(async () => review?.click());
78+
expect(document.querySelector("textarea")?.value).toBe("<html>recover me</html>");
79+
expect(document.body.textContent).toContain("Copy");
80+
expect(document.body.textContent).toContain("Download");
81+
await act(async () => root.unmount());
82+
});
83+
84+
it("does not offer a fake retry after remount and instead offers explicit overwrite", async () => {
85+
const container = document.createElement("div");
86+
document.body.append(container);
87+
const root = createRoot(container);
88+
const keepStudioFile = vi.fn(async () => undefined);
89+
const coordinator: ExternalFileChangeCoordinatorHandle = {
90+
blocked: {
91+
status: "failed",
92+
generation: 1,
93+
path: "index.html",
94+
error: new Error("offline"),
95+
payload: { path: "index.html", version: "v2", content: "external" },
96+
studioContent: "recovered draft",
97+
recovered: true,
98+
},
99+
retry: vi.fn(async () => undefined),
100+
useExternalFile: vi.fn(async () => undefined),
101+
keepStudioFile,
102+
};
103+
104+
await act(async () => root.render(<ExternalFileConflictBanner coordinator={coordinator} />));
105+
expect(document.body.textContent).not.toContain("Retry save");
106+
const overwrite = Array.from(document.querySelectorAll("button")).find((button) =>
107+
button.textContent?.includes("Overwrite file with recovered Studio draft"),
108+
);
109+
expect(overwrite).toBeTruthy();
110+
vi.spyOn(window, "confirm").mockReturnValue(true);
111+
await act(async () => overwrite?.click());
112+
expect(keepStudioFile).toHaveBeenCalledOnce();
113+
114+
await act(async () => root.unmount());
115+
});
116+
});
Lines changed: 255 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,255 @@
1+
import { useRef, useState } from "react";
2+
import type {
3+
ExternalFileChangeBlockedState,
4+
ExternalFileChangeCoordinatorHandle,
5+
} from "../hooks/useExternalFileChangeCoordinator";
6+
import { useDialogBehavior } from "./ui/useDialogBehavior";
7+
8+
function errorMessage(error: unknown): string {
9+
return error instanceof Error ? error.message : String(error);
10+
}
11+
12+
function downloadText(filename: string, content: string): void {
13+
const url = URL.createObjectURL(new Blob([content], { type: "text/html;charset=utf-8" }));
14+
const anchor = document.createElement("a");
15+
anchor.href = url;
16+
anchor.download = filename;
17+
anchor.click();
18+
URL.revokeObjectURL(url);
19+
}
20+
21+
function ConflictReview({
22+
conflict,
23+
onClose,
24+
}: {
25+
conflict: Extract<ExternalFileChangeBlockedState, { status: "conflict" }>;
26+
onClose: () => void;
27+
}) {
28+
const containerRef = useRef<HTMLDivElement>(null);
29+
useDialogBehavior({ open: true, onClose, containerRef });
30+
const external = conflict.error.currentContent ?? "(The server did not return file contents.)";
31+
const studio = conflict.error.attemptedContent;
32+
33+
return (
34+
<div
35+
className="fixed inset-0 z-[110] flex items-center justify-center bg-black/70 px-5 backdrop-blur-sm"
36+
onClick={onClose}
37+
>
38+
<div
39+
ref={containerRef}
40+
role="dialog"
41+
aria-modal="true"
42+
aria-labelledby="external-conflict-title"
43+
tabIndex={-1}
44+
className="max-h-[88vh] w-full max-w-5xl overflow-auto rounded-xl border border-amber-400/30 bg-neutral-950 p-5 text-neutral-100 shadow-2xl outline-none"
45+
onClick={(event) => event.stopPropagation()}
46+
>
47+
<div className="flex items-start justify-between gap-4">
48+
<div>
49+
<h2 id="external-conflict-title" className="text-base font-semibold">
50+
Review both versions of {conflict.error.filePath}
51+
</h2>
52+
<p className="mt-1 text-xs text-neutral-400">
53+
Reviewing or exporting does not change either version.
54+
</p>
55+
</div>
56+
<button type="button" onClick={onClose} className="rounded px-2 py-1 text-neutral-400">
57+
Close
58+
</button>
59+
</div>
60+
<div className="mt-4 grid gap-4 md:grid-cols-2">
61+
{[
62+
{ title: "File on disk", content: external, suffix: "external" },
63+
{ title: "Unsaved Studio version", content: studio, suffix: "studio" },
64+
].map((side) => (
65+
<section key={side.suffix} aria-label={side.title}>
66+
<div className="mb-2 flex items-center justify-between gap-2">
67+
<h3 className="text-sm font-medium">{side.title}</h3>
68+
<div className="flex gap-2">
69+
<button
70+
type="button"
71+
className="rounded border border-neutral-700 px-2 py-1 text-[11px]"
72+
onClick={() => void navigator.clipboard.writeText(side.content)}
73+
>
74+
Copy
75+
</button>
76+
<button
77+
type="button"
78+
className="rounded border border-neutral-700 px-2 py-1 text-[11px]"
79+
onClick={() =>
80+
downloadText(`${conflict.error.filePath}.${side.suffix}.html`, side.content)
81+
}
82+
>
83+
Download
84+
</button>
85+
</div>
86+
</div>
87+
<textarea
88+
readOnly
89+
value={side.content}
90+
className="h-80 w-full resize-y rounded border border-neutral-800 bg-neutral-900 p-3 font-mono text-[11px] leading-relaxed text-neutral-300"
91+
/>
92+
</section>
93+
))}
94+
</div>
95+
</div>
96+
</div>
97+
);
98+
}
99+
100+
function FailedDraftReview({
101+
path,
102+
content,
103+
onClose,
104+
}: {
105+
path: string;
106+
content: string;
107+
onClose: () => void;
108+
}) {
109+
const containerRef = useRef<HTMLDivElement>(null);
110+
useDialogBehavior({ open: true, onClose, containerRef });
111+
return (
112+
<div
113+
className="fixed inset-0 z-[110] flex items-center justify-center bg-black/70 px-5 backdrop-blur-sm"
114+
onClick={onClose}
115+
>
116+
<div
117+
ref={containerRef}
118+
role="dialog"
119+
aria-modal="true"
120+
aria-labelledby="failed-draft-title"
121+
tabIndex={-1}
122+
className="max-h-[88vh] w-full max-w-3xl overflow-auto rounded-xl border border-amber-400/30 bg-neutral-950 p-5 text-neutral-100 shadow-2xl outline-none"
123+
onClick={(event) => event.stopPropagation()}
124+
>
125+
<div className="flex items-start justify-between gap-4">
126+
<div>
127+
<h2 id="failed-draft-title" className="text-base font-semibold">
128+
Recover unsaved Studio draft for {path}
129+
</h2>
130+
<p className="mt-1 text-xs text-neutral-400">
131+
Copy or download this draft before choosing to discard it.
132+
</p>
133+
</div>
134+
<button type="button" onClick={onClose} className="rounded px-2 py-1 text-neutral-400">
135+
Close
136+
</button>
137+
</div>
138+
<div className="mt-4 flex justify-end gap-2">
139+
<button
140+
type="button"
141+
className="rounded border border-neutral-700 px-2 py-1 text-[11px]"
142+
onClick={() => void navigator.clipboard.writeText(content)}
143+
>
144+
Copy
145+
</button>
146+
<button
147+
type="button"
148+
className="rounded border border-neutral-700 px-2 py-1 text-[11px]"
149+
onClick={() => downloadText(`${path}.studio.html`, content)}
150+
>
151+
Download
152+
</button>
153+
</div>
154+
<textarea
155+
readOnly
156+
value={content}
157+
className="mt-2 h-80 w-full resize-y rounded border border-neutral-800 bg-neutral-900 p-3 font-mono text-[11px] leading-relaxed text-neutral-300"
158+
/>
159+
</div>
160+
</div>
161+
);
162+
}
163+
164+
export function ExternalFileConflictBanner({
165+
coordinator,
166+
}: {
167+
coordinator: ExternalFileChangeCoordinatorHandle;
168+
}) {
169+
const [reviewing, setReviewing] = useState(false);
170+
const blocked = coordinator.blocked;
171+
if (!blocked) return null;
172+
173+
const conflict = blocked.status === "conflict" ? blocked : null;
174+
const failure = blocked.status === "failed" ? blocked : null;
175+
return (
176+
<>
177+
<div
178+
role="alert"
179+
className="absolute left-1/2 top-14 z-[94] flex max-w-[calc(100vw-32px)] -translate-x-1/2 flex-wrap items-center gap-3 rounded-md border border-amber-400/30 bg-amber-950/95 px-4 py-2 text-[12px] font-medium text-amber-50 shadow-lg"
180+
>
181+
<span>
182+
{conflict
183+
? `${conflict.error.filePath} changed outside Studio. Preview is paused so neither version is lost.`
184+
: `Studio could not safely finish local saves: ${errorMessage(blocked.error)}. Preview is paused.`}
185+
</span>
186+
{conflict && (
187+
<button type="button" onClick={() => setReviewing(true)} className="underline">
188+
Review or export both
189+
</button>
190+
)}
191+
{failure?.studioContent != null && (
192+
<button type="button" onClick={() => setReviewing(true)} className="underline">
193+
Review or export Studio draft
194+
</button>
195+
)}
196+
{failure && !failure.recovered && (
197+
<button type="button" onClick={() => void coordinator.retry()} className="underline">
198+
Retry save
199+
</button>
200+
)}
201+
<button
202+
type="button"
203+
onClick={() => void coordinator.useExternalFile()}
204+
className="rounded border border-amber-200/30 px-2 py-1"
205+
>
206+
Discard Studio edits and reload file
207+
</button>
208+
{conflict && (
209+
<button
210+
type="button"
211+
onClick={() => {
212+
if (
213+
window.confirm(
214+
"Overwrite the externally changed file with the Studio version? The server will preserve its normal backup before writing.",
215+
)
216+
) {
217+
void coordinator.keepStudioFile();
218+
}
219+
}}
220+
className="rounded border border-red-300/40 px-2 py-1 text-red-100"
221+
>
222+
Overwrite file with Studio version
223+
</button>
224+
)}
225+
{failure?.recovered && failure.studioContent != null && (
226+
<button
227+
type="button"
228+
onClick={() => {
229+
if (
230+
window.confirm(
231+
"Overwrite the file with the recovered Studio draft? The current file will be preserved by the server's normal backup before writing.",
232+
)
233+
) {
234+
void coordinator.keepStudioFile();
235+
}
236+
}}
237+
className="rounded border border-red-300/40 px-2 py-1 text-red-100"
238+
>
239+
Overwrite file with recovered Studio draft
240+
</button>
241+
)}
242+
</div>
243+
{reviewing && conflict && (
244+
<ConflictReview conflict={conflict} onClose={() => setReviewing(false)} />
245+
)}
246+
{reviewing && failure?.studioContent != null && (
247+
<FailedDraftReview
248+
path={failure.path}
249+
content={failure.studioContent}
250+
onClose={() => setReviewing(false)}
251+
/>
252+
)}
253+
</>
254+
);
255+
}

0 commit comments

Comments
 (0)