refactor(ui): share one reviewed-write dialog between Pi and OMP extensions

The Pi and Oh My Pi extension tabs each carried a ReviewDialog with the
same flow, nearly line for line: preview once, apply only that plan's
revision, show busy and stale refusals, and offer "review again" when the
server reports the plan stale. A third target of this kind would have
added a third copy.

ExtensionsReviewDialog now owns that flow and the dialog frame. Each
target supplies its plan rows, texts and endpoints, so the two protocols
stay as they were: Pi previews without a revision, OMP previews against
the view's revision, and both apply the previewed plan's revision.

Hooks, MCP and Plugins use different protocols and are left alone.

Refs #447
This commit is contained in:
Willie
2026-10-07 00:04:57 +08:00
parent d60d739f55
commit 15922be060
3 changed files with 158 additions and 146 deletions
@@ -0,0 +1,78 @@
import { useState } from 'react';
import type { ReactNode } from 'react';
import { useQuery, useQueryClient, type QueryKey } from '@tanstack/react-query';
import { AlertCircle, X } from 'lucide-react';
import { ApiError } from '../../api/client';
import { invalidate } from '../../lib/queryEvents';
import { useT } from '../../i18n';
import Button from '../Button';
import DialogShell from '../DialogShell';
/**
* The reviewed write of a Pi or Oh My Pi target's extension settings: preview once, apply only that
* plan's revision, and send the user back to review again when the server says the plan is stale.
* How a preview is asked for (with or without the view's revision) is the target's own protocol.
*/
export default function ExtensionsReviewDialog<Plan extends { revision: string }>({ kind, name, text, previewKey, preview: fetchPreview, apply: applyPlan, children, onClose, onApplied }: {
kind: 'pi' | 'omp';
name: string;
text: { title: string; subtitle: string; loading: string; apply: string; reviewAgain: string; stale: string; busy: string };
previewKey: QueryKey;
preview: () => Promise<Plan>;
apply: (revision: string) => Promise<Plan>;
/** What the plan would write, above the failure note. */
children: (plan: Plan) => ReactNode;
onClose: () => void;
onApplied: (plan: Plan) => void;
}) {
const t = useT();
const queryClient = useQueryClient();
const preview = useQuery({ queryKey: previewKey, queryFn: fetchPreview, retry: false, gcTime: 0, staleTime: Infinity });
const [applying, setApplying] = useState(false);
const [error, setError] = useState<Error | null>(null);
const plan = preview.data;
const apply = async () => {
if (!plan) return;
setApplying(true);
setError(null);
try {
const done = await applyPlan(plan.revision);
await invalidate(queryClient, `${kind}ExtensionsChanged`, name);
onApplied(done);
} catch (err) {
setError(err as Error);
setApplying(false);
}
};
const failure = error ?? preview.error;
const code = failure instanceof ApiError ? failure.code : undefined;
const stale = code === `${kind}_extensions_stale`;
const busy = code === `${kind}_extensions_busy`;
return (
<DialogShell open onClose={onClose} padding="none" preventClose={applying} ariaLabel={text.title} className="!max-w-[680px]">
<div className="dh">
<div className="flex flex-col gap-1">
<h2 className="ss-h2">{text.title}</h2>
<p className="text-[13px] text-ink-2">{text.subtitle}</p>
</div>
<button type="button" className="ss-ib" aria-label={t('common.close')} onClick={onClose} disabled={applying}><X size={16} /></button>
</div>
<div className="db !gap-3 text-[13.5px]">
{!plan && !failure && <p className="text-ink-3">{text.loading}</p>}
{plan && children(plan)}
{failure && (
<div className={`ss-note ${stale || busy ? 'warn' : 'bad'}`} role="alert">
<AlertCircle size={16} />
<span className="flex-1">{stale ? text.stale : busy ? text.busy : failure.message}</span>
</div>
)}
</div>
<div className="df">
<Button variant="ghost" onClick={onClose} disabled={applying}>{t('common.cancel')}</Button>
{stale
? <Button variant="secondary" onClick={() => { void invalidate(queryClient, `${kind}ExtensionsStale`, name); onClose(); }}>{text.reviewAgain}</Button>
: <Button variant="primary" onClick={apply} loading={applying} disabled={!plan || Boolean(preview.error)}>{text.apply}</Button>}
</div>
</DialogShell>
);
}
@@ -1,18 +1,16 @@
import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useQuery } from '@tanstack/react-query';
import { Link } from 'react-router-dom';
import { AlertCircle, ArrowRight, ChevronDown, CircleCheck, FileDiff, Folder, Info, Lock, Package, Puzzle, X } from 'lucide-react';
import { ApiError } from '../../api/client';
import { ompExtensionsApi, type OmpExtensionChange, type OmpExtensionRow, type OmpExtensionsPlan, type OmpExtensionsView } from '../../api/ompExtensions';
import Button from '../Button';
import DialogShell from '../DialogShell';
import EmptyState from '../EmptyState';
import ExtensionsReviewDialog from './ExtensionsReviewDialog';
import Tooltip from '../Tooltip';
import { PageSkeleton } from '../Skeleton';
import { messagesByLocale, useT } from '../../i18n';
import { queryKeys } from '../../lib/queryKeys';
import { fileName, shortenHome } from '../../lib/paths';
import { invalidate } from '../../lib/queryEvents';
type T = ReturnType<typeof useT>;
type Pending = Record<string, boolean>;
@@ -222,73 +220,45 @@ function Row({ row, dir, name, switchable, showLock, draft, onFlip, t }: { row:
/** Previews the drafts against the view's revision, then applies exactly that plan. */
function ReviewDialog({ name, view, changes, onClose, onApplied, t }: { name: string; view: OmpExtensionsView; changes: OmpExtensionChange[]; onClose: () => void; onApplied: (plan: OmpExtensionsPlan) => void; t: T }) {
const queryClient = useQueryClient();
const preview = useQuery({ queryKey: queryKeys.ompExtensionsPreview(name, view.revision, changes), queryFn: () => ompExtensionsApi.preview(name, changes, view.revision), retry: false, gcTime: 0, staleTime: Infinity });
const [applying, setApplying] = useState(false);
const [error, setError] = useState<Error | null>(null);
const plan = preview.data;
const refresh = () => invalidate(queryClient, 'ompExtensionsStale', name);
const apply = async () => {
if (!plan) return;
setApplying(true);
setError(null);
try {
const done = await ompExtensionsApi.apply(name, changes, plan.revision);
await invalidate(queryClient, 'ompExtensionsChanged', name);
onApplied(done);
} catch (err) {
setError(err as Error);
setApplying(false);
}
};
const failure = error ?? preview.error;
const code = failure instanceof ApiError ? failure.code : undefined;
const stale = code === 'omp_extensions_stale';
const title = t('targetDetail.ompExtensions.dialog.title', { name });
const rowOf = (key: string) => view.rows.find((r) => r.key === key);
return (
<DialogShell open onClose={onClose} padding="none" preventClose={applying} ariaLabel={title} className="!max-w-[680px]">
<div className="dh">
<div className="flex flex-col gap-1">
<h2 className="ss-h2">{title}</h2>
<p className="text-[13px] text-ink-2">{t('targetDetail.ompExtensions.dialog.subtitle', { path: shortenHome(view.settingsPath) })}</p>
</div>
<button type="button" className="ss-ib" aria-label={t('common.close')} onClick={onClose} disabled={applying}><X size={16} /></button>
</div>
<div className="db !gap-3 text-[13.5px]">
{!plan && !failure && <p className="text-ink-3">{t('targetDetail.ompExtensions.dialog.loading')}</p>}
{plan && (
<>
<ul className="flex flex-col gap-1.5">
{plan.rows.map((r) => (
<li key={r.key} className="flex flex-wrap items-center gap-x-2">
<span className="flex min-w-0 flex-col">
<span className="font-mono text-[13px] font-semibold">{rowOf(r.key)?.name ?? r.derivedId}</span>
<span className="truncate font-mono text-[12px] text-ink-3">{rowOf(r.key)?.path ?? r.key}</span>
</span>
<span className="flex-1" />
<span>{t(`targetDetail.ompExtensions.sel.${selOf(r.before)}`)} → <span className="font-semibold">{t(`targetDetail.ompExtensions.sel.${selOf(r.after)}`)}</span></span>
</li>
))}
</ul>
{plan.warnings.map((w) => <div key={w} className="ss-note warn" role="alert"><AlertCircle size={16} /><span className="flex-1">{guidance(w, t)}</span></div>)}
<p className="text-[12.5px] text-ink-2">{t('targetDetail.ompExtensions.dialog.kept')}</p>
<p className="text-[12.5px] text-ink-3">{t('targetDetail.ompExtensions.dialog.revision', { revision: plan.revision.slice(0, 7) })}</p>
</>
)}
{failure && (
<div className={`ss-note ${stale || code === 'omp_extensions_busy' ? 'warn' : 'bad'}`} role="alert">
<AlertCircle size={16} />
<span className="flex-1">{stale ? t('targetDetail.ompExtensions.stale') : code === 'omp_extensions_busy' ? t('targetDetail.ompExtensions.busy') : failure.message}</span>
</div>
)}
</div>
<div className="df">
<Button variant="ghost" onClick={onClose} disabled={applying}>{t('common.cancel')}</Button>
{stale
? <Button variant="secondary" onClick={() => { void refresh(); onClose(); }}>{t('targetDetail.ompExtensions.reviewAgain')}</Button>
: <Button variant="primary" onClick={apply} loading={applying} disabled={!plan || Boolean(preview.error)}>{t('targetDetail.ompExtensions.dialog.apply')}</Button>}
</div>
</DialogShell>
<ExtensionsReviewDialog
kind="omp"
name={name}
text={{
title: t('targetDetail.ompExtensions.dialog.title', { name }),
subtitle: t('targetDetail.ompExtensions.dialog.subtitle', { path: shortenHome(view.settingsPath) }),
loading: t('targetDetail.ompExtensions.dialog.loading'),
apply: t('targetDetail.ompExtensions.dialog.apply'),
reviewAgain: t('targetDetail.ompExtensions.reviewAgain'),
stale: t('targetDetail.ompExtensions.stale'),
busy: t('targetDetail.ompExtensions.busy'),
}}
previewKey={queryKeys.ompExtensionsPreview(name, view.revision, changes)}
preview={() => ompExtensionsApi.preview(name, changes, view.revision)}
apply={(revision) => ompExtensionsApi.apply(name, changes, revision)}
onClose={onClose}
onApplied={onApplied}
>
{(plan) => (
<>
<ul className="flex flex-col gap-1.5">
{plan.rows.map((r) => (
<li key={r.key} className="flex flex-wrap items-center gap-x-2">
<span className="flex min-w-0 flex-col">
<span className="font-mono text-[13px] font-semibold">{rowOf(r.key)?.name ?? r.derivedId}</span>
<span className="truncate font-mono text-[12px] text-ink-3">{rowOf(r.key)?.path ?? r.key}</span>
</span>
<span className="flex-1" />
<span>{t(`targetDetail.ompExtensions.sel.${selOf(r.before)}`)} → <span className="font-semibold">{t(`targetDetail.ompExtensions.sel.${selOf(r.after)}`)}</span></span>
</li>
))}
</ul>
{plan.warnings.map((w) => <div key={w} className="ss-note warn" role="alert"><AlertCircle size={16} /><span className="flex-1">{guidance(w, t)}</span></div>)}
<p className="text-[12.5px] text-ink-2">{t('targetDetail.ompExtensions.dialog.kept')}</p>
<p className="text-[12.5px] text-ink-3">{t('targetDetail.ompExtensions.dialog.revision', { revision: plan.revision.slice(0, 7) })}</p>
</>
)}
</ExtensionsReviewDialog>
);
}
@@ -1,9 +1,8 @@
import { useState } from 'react';
import type { ReactNode } from 'react';
import { Link } from 'react-router-dom';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useQuery } from '@tanstack/react-query';
import { AlertCircle, ArrowRight, ChevronDown, CircleCheck, FileDiff, Folder, Info, Lock, Package, Puzzle, RotateCcw, X } from 'lucide-react';
import { ApiError } from '../../api/client';
import { piExtensionsApi } from '../../api/piExtensions';
import PiPackageIcon from '../PiPackageIcon';
import type { PiExtensionAction, PiExtensionChange, PiExtensionFolder, PiExtensionPackage, PiExtensionRow, PiExtensionsPlan, PiExtensionsView, PiSelection } from '../../api/piExtensions';
@@ -11,11 +10,10 @@ import { queryKeys } from '../../lib/queryKeys';
import { shortenHome } from '../../lib/paths';
import { useT } from '../../i18n';
import Button from '../Button';
import DialogShell from '../DialogShell';
import EmptyState from '../EmptyState';
import ExtensionsReviewDialog from './ExtensionsReviewDialog';
import { PageSkeleton } from '../Skeleton';
import Tooltip from '../Tooltip';
import { invalidate } from '../../lib/queryEvents';
type T = ReturnType<typeof useT>;
type Scope = PiExtensionChange['scope'];
@@ -355,74 +353,51 @@ function OddSelection({ value, t }: { value: PiSelection; t: T }) {
function ReviewDialog({ name, view, changes, onClose, onApplied, t }: {
name: string; view: PiExtensionsView; changes: PiExtensionChange[]; onClose: () => void; onApplied: (plan: PiExtensionsPlan) => void; t: T;
}) {
const queryClient = useQueryClient();
const preview = useQuery({ queryKey: queryKeys.piExtensionsPreview(name, changes), queryFn: () => piExtensionsApi.preview(name, changes), retry: false, gcTime: 0, staleTime: Infinity });
const [applying, setApplying] = useState(false);
const [error, setError] = useState<ApiError | Error | null>(null);
const plan = preview.data;
const project = view.scope === 'project';
const refresh = () => invalidate(queryClient, 'piExtensionsStale', name);
const apply = async () => {
if (!plan) return;
setApplying(true);
setError(null);
try {
const done = await piExtensionsApi.apply(name, changes, plan.revision);
await invalidate(queryClient, 'piExtensionsChanged', name);
onApplied(done);
} catch (err) {
setError(err as Error);
setApplying(false);
}
};
const failure = error ?? preview.error;
const code = failure instanceof ApiError ? failure.code : undefined;
const stale = code === 'pi_extensions_stale';
const title = t(project ? 'targetDetail.piExtensions.dialog.titleProject' : 'targetDetail.piExtensions.dialog.title', { name });
const pkgName = (scope: Scope | undefined, index: number, identity?: string) => {
const p = view.packages.find((x) => x.scope === (scope ?? 'global') && x.index === index);
return identity || p?.identity || p?.source || String(index);
};
return (
<DialogShell open onClose={onClose} padding="none" preventClose={applying} ariaLabel={title} className="!max-w-[680px]">
<div className="dh">
<div className="flex flex-col gap-1">
<h2 className="ss-h2">{title}</h2>
<p className="text-[13px] text-ink-2">{t(project ? 'targetDetail.piExtensions.dialog.subtitleProject' : 'targetDetail.piExtensions.dialog.subtitle', { path: shortenHome(view.settingsPath) })}</p>
</div>
<button type="button" className="ss-ib" aria-label={t('common.close')} onClick={onClose} disabled={applying}><X size={16} /></button>
</div>
<div className="db !gap-3 text-[13.5px]">
{!plan && !failure && <p className="text-ink-3">{t('targetDetail.piExtensions.dialog.loading')}</p>}
{plan && (
<>
<ul className="flex flex-col gap-1">
{plan.rows.map((r) => (
<li key={keyOf(r.scope ?? 'global', r.index, r.path)} className="flex flex-wrap items-center gap-x-2">
<span className="font-mono text-[13px] font-semibold">{r.path}</span>
<span className="text-[12px] text-ink-3">{pkgName(r.scope, r.index)}</span>
<span className="flex-1" />
<span>{t(`targetDetail.piExtensions.sel.${r.before}`)} → <span className="font-semibold">{t(`targetDetail.piExtensions.sel.${r.after}`)}</span></span>
</li>
))}
</ul>
{plan.entries.map((e) => (
<EntryDiff key={`${e.scope ?? 'global'}:${e.index}`} entry={e} pkg={pkgName(e.scope, e.index, e.identity)} t={t} />
<ExtensionsReviewDialog
kind="pi"
name={name}
text={{
title: t(project ? 'targetDetail.piExtensions.dialog.titleProject' : 'targetDetail.piExtensions.dialog.title', { name }),
subtitle: t(project ? 'targetDetail.piExtensions.dialog.subtitleProject' : 'targetDetail.piExtensions.dialog.subtitle', { path: shortenHome(view.settingsPath) }),
loading: t('targetDetail.piExtensions.dialog.loading'),
apply: t(project ? 'targetDetail.piExtensions.dialog.applyProject' : 'targetDetail.piExtensions.dialog.apply'),
reviewAgain: t('targetDetail.piExtensions.reviewAgain'),
stale: t('targetDetail.piExtensions.stale'),
busy: t('targetDetail.piExtensions.busy'),
}}
previewKey={queryKeys.piExtensionsPreview(name, changes)}
preview={() => piExtensionsApi.preview(name, changes)}
apply={(revision) => piExtensionsApi.apply(name, changes, revision)}
onClose={onClose}
onApplied={onApplied}
>
{(plan) => (
<>
<ul className="flex flex-col gap-1">
{plan.rows.map((r) => (
<li key={keyOf(r.scope ?? 'global', r.index, r.path)} className="flex flex-wrap items-center gap-x-2">
<span className="font-mono text-[13px] font-semibold">{r.path}</span>
<span className="text-[12px] text-ink-3">{pkgName(r.scope, r.index)}</span>
<span className="flex-1" />
<span>{t(`targetDetail.piExtensions.sel.${r.before}`)} → <span className="font-semibold">{t(`targetDetail.piExtensions.sel.${r.after}`)}</span></span>
</li>
))}
<p className="text-[12.5px] text-ink-2">{t('targetDetail.piExtensions.dialog.kept')}</p>
{project && <p className="text-[12.5px] text-ink-2">{t('targetDetail.piExtensions.dialog.mayNotLoad')}</p>}
<p className="text-[12.5px] text-ink-3">{t('targetDetail.piExtensions.dialog.revision', { revision: plan.revision.slice(0, 7) })}</p>
</>
)}
{failure && <ReviewFailure failure={failure} code={code} t={t} />}
</div>
<div className="df">
<Button variant="ghost" onClick={onClose} disabled={applying}>{t('common.cancel')}</Button>
{stale
? <Button variant="secondary" onClick={() => { void refresh(); onClose(); }}>{t('targetDetail.piExtensions.reviewAgain')}</Button>
: <Button variant="primary" onClick={apply} loading={applying} disabled={!plan || Boolean(preview.error)}>{t(project ? 'targetDetail.piExtensions.dialog.applyProject' : 'targetDetail.piExtensions.dialog.apply')}</Button>}
</div>
</DialogShell>
</ul>
{plan.entries.map((e) => (
<EntryDiff key={`${e.scope ?? 'global'}:${e.index}`} entry={e} pkg={pkgName(e.scope, e.index, e.identity)} t={t} />
))}
<p className="text-[12.5px] text-ink-2">{t('targetDetail.piExtensions.dialog.kept')}</p>
{project && <p className="text-[12.5px] text-ink-2">{t('targetDetail.piExtensions.dialog.mayNotLoad')}</p>}
<p className="text-[12.5px] text-ink-3">{t('targetDetail.piExtensions.dialog.revision', { revision: plan.revision.slice(0, 7) })}</p>
</>
)}
</ExtensionsReviewDialog>
);
}
@@ -443,14 +418,3 @@ function EntryDiff({ entry: e, pkg, t }: { entry: PiExtensionsPlan['entries'][nu
</div>
);
}
function ReviewFailure({ failure, code, t }: { failure: Error; code?: string; t: T }) {
const stale = code === 'pi_extensions_stale';
const busy = code === 'pi_extensions_busy';
return (
<div className={`ss-note ${stale || busy ? 'warn' : 'bad'}`} role="alert">
<AlertCircle size={16} />
<span className="flex-1">{stale ? t('targetDetail.piExtensions.stale') : busy ? t('targetDetail.piExtensions.busy') : failure.message}</span>
</div>
);
}