feat(ui): the env detail, the snapshot timeline, and a rollback that says what it cannot restore

UI-SPEC §4 puts Snapshots "under Environments → env detail" and there was no env
detail — the screen was a flat list with a *Use* button. It is a **mode** of the
Environments tab rather than a ninth sidebar entry, because a ninth entry would
renumber `Ctrl+1..8`, which the keyboard map fixes in place.

`openFor` lives in `useEnvStore`, not in the screen's `useState`. The plan panel
replaces the whole content area while a rollback runs, so local state would be
unmounted with it and the user would land back on the flat list the moment their
rollback finished — the same shape as Stage 4's bug, one screen along.

`PdSnapshotTimeline` shows the trigger, which is not decoration: an update writes
a `Plan` snapshot before mutating and a rollback writes a `Rollback` one before
restoring, so a single restore moves `latest` **twice**. That is what made
TESTING L2's first run report every package as changed when the rollback had
actually worked, and it is why nothing here ever names `latest` — the timeline
hands ids to every command.

`PdRollbackPreview` lists `unrestorable` under its code before the confirm rather
than in the summary afterwards. §8 says those entries are "listed explicitly;
user may proceed partially", and a preview reporting "12 packages" while quietly
leaving two behind is a success message for a restore that did not happen.

`PdPlanPanel` grows a `kind`. A rollback produces no `FlowStep` — nothing to
resolve, nothing to decide — so all six `step`-shaped guards answered "no" and
would have disabled the one button the flow needs. Confirm also takes the danger
styling there, because a restore removes things.

A dead interpreter still reaches the detail view: snapshots are keyed by
`envHash` and outlive the Python that made them, so the timeline lists while
diff and rollback are disabled with a line saying why.

`PdEnvironments` switches to per-field selectors. It was a bare `useEnvStore()`,
which subscribes to every field — including the timeline and the diff, so opening
a detail would have re-rendered the whole environment list.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 committed 2026-08-09 21:46:25 +07:00
1 parent 1df526c1ed
commit d6ae948cda
10 files changed
+624 -19

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
/**
* What a rollback would do — DATA-FLOW §8, rendered before it happens.
*
* The `unrestorable` list is the reason this component is not just a count. §8 says a release that
* can no longer be fetched "cannot be restored → PD-SNP-002, listed explicitly; user may proceed
* partially", and a preview that reported "12 packages" while silently leaving two behind would be
* a success message for a restore that did not happen. So the list is shown, with its code, before
* the confirm rather than in the summary afterwards.
*/
import { useTranslation } from 'react-i18next'
import type { RollbackPreview } from '@/ipc'
export function PdRollbackPreview({ preview }: { preview: RollbackPreview }) {
const { t } = useTranslation()
const { restore, unrestorable, target } = preview
const empty = restore.uninstall.length === 0 && restore.install.length === 0
return (
<div>
<p className="text-data text-text-dim">
{t('snapshots.restoringTo')} <code className="font-mono">{target.id}</code>
</p>
{empty ? (
<p className="mt-3 text-data text-text-dim">{t('snapshots.alreadyMatches')}</p>
) : null}
{restore.uninstall.length > 0 ? (
<section className="mt-4" data-section="uninstall">
<h2 className="text-data text-warn">
{t('snapshots.willRemove', { count: restore.uninstall.length })}
</h2>
<ul className="mt-1 space-y-0.5">
{restore.uninstall.map((pkg) => (
<li key={pkg}>
<code className="font-mono text-data">{pkg}</code>
</li>
))}
</ul>
</section>
) : null}
{restore.install.length > 0 ? (
<section className="mt-4" data-section="install">
<h2 className="text-data text-accent">
{t('snapshots.willRestore', { count: restore.install.length })}
</h2>
<ul className="mt-1 space-y-0.5">
{restore.install.map((spec) => (
<li key={spec.name}>
{/* Restored *at the snapshot's version*, which is the whole point — a bare name
would leave the reader unable to tell this from a plain reinstall. */}
<code className="font-mono text-data">{`${spec.name}==${spec.version}`}</code>
</li>
))}
</ul>
</section>
) : null}
{unrestorable.length > 0 ? (
<section className="mt-4" data-section="unrestorable">
<h2 className="text-data text-danger">
<code className="font-mono">{'PD-SNP-002'}</code>{' '}
{t('snapshots.unrestorable', { count: unrestorable.length })}
</h2>
<p className="mt-1 text-data text-text-dim">{t('snapshots.unrestorableDetail')}</p>
<ul className="mt-1 space-y-0.5">
{unrestorable.map((line) => (
<li key={line}>
{/* Verbatim freeze lines: an editable install or a direct URL, exactly as the
snapshot recorded it. Never reshaped (I18N §2). */}
<code className="font-mono text-data text-text-dim">{line}</code>
</li>
))}
</ul>
</section>
) : null}
</div>
)
}
+80
View File
@@ -0,0 +1,80 @@
/**
* The snapshot timeline — UI-SPEC §4, "timeline of snapshots with trigger label".
*
* The trigger label is not decoration. `update --all` writes a `Plan` snapshot before mutating and
* a rollback writes a `Rollback` one before restoring, so a single restore moves `latest` **twice**
* — the trap that made TESTING L2's first run report every package as changed when the rollback
* had in fact worked. Showing which is which is what stops a user picking the wrong entry, and it
* is why nothing in the UI ever names `latest`.
*/
import { useTranslation } from 'react-i18next'
import type { SnapshotMeta } from '@/ipc'
interface PdSnapshotTimelineProps {
snapshots: readonly SnapshotMeta[]
selected: string | null
onSelect: (id: string) => void
/** False when the environment's interpreter is gone: it can be listed but not compared. */
selectable: boolean
}
export function PdSnapshotTimeline({
snapshots,
selected,
onSelect,
selectable,
}: PdSnapshotTimelineProps) {
const { t, i18n } = useTranslation()
/** The trigger, as a label. `restoring` is an id and is never translated. */
const triggerLabel = (meta: SnapshotMeta): string => {
if (meta.trigger === 'manual') return t('snapshots.trigger.manual')
if ('plan' in meta.trigger) return t('snapshots.trigger.plan')
return t('snapshots.trigger.rollback', { id: meta.trigger.rollback.restoring })
}
return (
<ul className="mt-3 space-y-1">
{snapshots.map((meta) => {
const isSelected = meta.id === selected
return (
<li key={meta.id}>
<button
type="button"
disabled={!selectable}
onClick={() => {
onSelect(meta.id)
}}
data-snapshot={meta.id}
data-selected={isSelected}
aria-current={isSelected}
className={`flex w-full flex-wrap items-baseline gap-3 rounded-pd border px-3 py-2 text-left disabled:opacity-40 ${
isSelected ? 'border-accent bg-surface-2' : 'border-border bg-surface'
}`}
>
{/* The id is the handle every command takes, so it is shown verbatim and in mono. */}
<code className="font-mono text-data">{meta.id}</code>
<span className="text-data text-text-dim">
{/* Dates are localized, ids are not (I18N §2). An unparseable timestamp falls back
to the raw string rather than rendering "Invalid Date". */}
{formatWhen(meta.createdAt, i18n.language)}
</span>
<span className="text-data text-text-dim">
{t('status.packages', { count: meta.packageCount })}
</span>
<span className="text-data text-info">{triggerLabel(meta)}</span>
</button>
</li>
)
})}
</ul>
)
}
function formatWhen(iso: string, locale: string): string {
const at = new Date(iso)
if (Number.isNaN(at.getTime())) return iso
return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short' }).format(at)
}
+35
View File
@@ -36,6 +36,7 @@
"reportBug": "Report bug",
"accept": "Continue",
"decline": "Decline and exit",
"open": "Open",
"use": "Use",
"retry": "Retry",
"openLogs": "Open logs folder"
@@ -161,6 +162,40 @@
"reasonPlaceholder": "Why is this pinned?",
"reasonFor": "Reason for pinning {{pkg}}"
},
"snapshots": {
"title": "Snapshots",
"take": "Take snapshot",
"loading": "Reading snapshots…",
"empty": "no snapshots for this environment",
"emptyHint": "One is taken automatically before every change, and you can take one now.",
"envUnusable": "This interpreter cannot be read, so snapshots can be listed but not compared or restored.",
"diffing": "Comparing with the environment…",
"noDifference": "This environment already matches the snapshot.",
"diffAdded_one": "{{count}} package here but not in the snapshot — restoring removes it",
"diffAdded_other": "{{count}} packages here but not in the snapshot — restoring removes them",
"diffRemoved_one": "{{count}} package in the snapshot but not installed — restoring adds it",
"diffRemoved_other": "{{count}} packages in the snapshot but not installed — restoring adds them",
"diffChanged_one": "{{count}} package at a different version",
"diffChanged_other": "{{count}} packages at different versions",
"rollback": "Rollback…",
"rollbackTitle": "Roll back",
"restoringTo": "Restoring the environment to",
"alreadyMatches": "Nothing to do — this environment already matches the snapshot.",
"willRemove_one": "Will remove {{count}} package",
"willRemove_other": "Will remove {{count}} packages",
"willRestore_one": "Will restore {{count}} package",
"willRestore_other": "Will restore {{count}} packages",
"unrestorable_one": "{{count}} entry cannot be restored",
"unrestorable_other": "{{count}} entries cannot be restored",
"unrestorableDetail": "These were installed from a path or a URL rather than from an index, so PipDock cannot fetch them again. Everything else still restores.",
"confirmRollback_one": "Roll back ({{count}} change)",
"confirmRollback_other": "Roll back ({{count}} changes)",
"trigger": {
"plan": "before a change",
"rollback": "before restoring {{id}}",
"manual": "taken by you"
}
},
"uninstall": {
"title": "Remove packages",
"titleBreaks": "This removal breaks other packages",
+28
View File
@@ -35,6 +35,7 @@
"reportBug": "Báo lỗi",
"accept": "Tiếp tục",
"decline": "Từ chối và thoát",
"open": "Mở",
"use": "Dùng",
"retry": "Thử lại",
"openLogs": "Mở thư mục nhật ký"
@@ -154,6 +155,33 @@
"reasonPlaceholder": "Vì sao ghim gói này?",
"reasonFor": "Lý do ghim {{pkg}}"
},
"snapshots": {
"title": "Ảnh chụp",
"take": "Chụp ngay",
"loading": "Đang đọc ảnh chụp…",
"empty": "môi trường này chưa có ảnh chụp nào",
"emptyHint": "PipDock tự chụp trước mọi thay đổi, và bạn cũng có thể chụp ngay bây giờ.",
"envUnusable": "Không đọc được trình thông dịch này, nên chỉ liệt kê được ảnh chụp chứ không so sánh hay khôi phục được.",
"diffing": "Đang so sánh với môi trường…",
"noDifference": "Môi trường này vốn đã khớp với ảnh chụp.",
"diffAdded_other": "{{count}} gói có ở đây nhưng không có trong ảnh chụp — khôi phục sẽ gỡ chúng",
"diffRemoved_other": "{{count}} gói có trong ảnh chụp nhưng chưa cài — khôi phục sẽ cài lại",
"diffChanged_other": "{{count}} gói đang ở phiên bản khác",
"rollback": "Khôi phục…",
"rollbackTitle": "Khôi phục",
"restoringTo": "Khôi phục môi trường về",
"alreadyMatches": "Không có gì để làm — môi trường này vốn đã khớp với ảnh chụp.",
"willRemove_other": "Sẽ gỡ {{count}} gói",
"willRestore_other": "Sẽ khôi phục {{count}} gói",
"unrestorable_other": "{{count}} mục không khôi phục được",
"unrestorableDetail": "Những mục này được cài từ đường dẫn hoặc URL chứ không phải từ danh mục, nên PipDock không tải lại được. Mọi thứ còn lại vẫn khôi phục bình thường.",
"confirmRollback_other": "Khôi phục ({{count}} thay đổi)",
"trigger": {
"plan": "trước một thay đổi",
"rollback": "trước khi khôi phục {{id}}",
"manual": "bạn tự chụp"
}
},
"uninstall": {
"title": "Gỡ gói",
"titleBreaks": "Thao tác gỡ này làm hỏng gói khác",
+184
View File
@@ -0,0 +1,184 @@
/**
* One environment, in detail — UI-SPEC §4 puts Snapshots here: "surfaced under Environments → env
* detail".
*
* It is a *mode* of the Environments tab rather than a ninth sidebar entry, because a ninth entry
* would renumber `Ctrl+1..8` and the M2 plan is explicit that the positions stay. `useEnvStore`
* holds which environment is open, not this component's state: the plan panel replaces the whole
* content area while a rollback runs, so local state would be unmounted with it and the user would
* land back on the flat list the moment their rollback finished.
*
* A row whose interpreter is gone still gets here. Snapshots are keyed by `envHash` and outlive the
* Python that made them, so the timeline lists — but nothing can be diffed or restored against an
* interpreter that cannot be frozen, and the screen says which rather than spinning.
*/
import { useTranslation } from 'react-i18next'
import { PdEmptyState } from '@/components/PdEmptyState'
import { PdErrorRow } from '@/components/PdErrorRow'
import { PdSnapshotTimeline } from '@/components/PdSnapshotTimeline'
import { useEnvStore, usePlanStore } from '@/stores'
import { useEnvSnapshots } from '@/screens/useEnvSnapshots'
export function PdEnvDetail() {
const { t } = useTranslation()
const openFor = useEnvStore((s) => s.openFor)
const rows = useEnvStore((s) => s.rows)
const snapshots = useEnvStore((s) => s.snapshots)
const snapshotsLoading = useEnvStore((s) => s.snapshotsLoading)
const snapshotsError = useEnvStore((s) => s.snapshotsError)
const selectedSnapshot = useEnvStore((s) => s.selectedSnapshot)
const diff = useEnvStore((s) => s.diff)
const diffLoading = useEnvStore((s) => s.diffLoading)
const closeEnv = useEnvStore((s) => s.closeEnv)
const selectSnapshot = useEnvStore((s) => s.selectSnapshot)
const takeSnapshot = useEnvStore((s) => s.takeSnapshot)
const rollback = usePlanStore((s) => s.rollback)
useEnvSnapshots()
const row = rows.find((r) => r.interpreter === openFor)
const env = row?.env
const usable = env !== undefined
return (
<section aria-labelledby="detail-title" className="h-full overflow-auto p-6">
<div className="flex flex-wrap items-center justify-between gap-2">
<h1 id="detail-title" className="min-w-0 truncate text-accent">
{t('snapshots.title')}
</h1>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => {
void takeSnapshot()
}}
disabled={!usable}
data-action="take-snapshot"
className="rounded-pd border border-border px-3 py-1 text-data disabled:opacity-40"
>
{t('snapshots.take')}
</button>
<button
type="button"
onClick={closeEnv}
className="rounded-pd border border-border px-3 py-1 text-data"
>
{t('actions.back')}
</button>
</div>
</div>
<p className="mt-1 font-mono text-data text-text-dim">{openFor}</p>
{usable ? null : (
<p className="mt-2 rounded-pd border-l-2 border-warn pl-2 text-data text-text-dim">
{t('snapshots.envUnusable')}
</p>
)}
{snapshotsError !== null ? (
<div className="mt-4">
<PdErrorRow error={snapshotsError} />
</div>
) : null}
{snapshotsLoading === 'loading' ? (
<p aria-live="polite" className="mt-4 text-data text-text-dim">
{t('snapshots.loading')}
</p>
) : null}
{snapshotsLoading === 'ready' && snapshots.length === 0 ? (
<PdEmptyState message={t('snapshots.empty')} hint={t('snapshots.emptyHint')} />
) : (
<PdSnapshotTimeline
snapshots={snapshots}
selected={selectedSnapshot}
selectable={usable}
onSelect={(id) => {
void selectSnapshot(id)
}}
/>
)}
{selectedSnapshot !== null && usable ? (
<div className="mt-6 border-t border-border pt-4">
{diffLoading === 'loading' ? (
<p aria-live="polite" className="text-data text-text-dim">
{t('snapshots.diffing')}
</p>
) : null}
{diff !== null ? (
<>
<DiffView />
<button
type="button"
onClick={() => {
void rollback(env, selectedSnapshot)
}}
data-action="rollback"
className="mt-4 rounded-pd border border-danger px-3 py-1 text-data text-danger"
>
{t('snapshots.rollback')}
</button>
</>
) : null}
</div>
) : null}
</section>
)
}
/** The diff viewer — UI-SPEC §4: "added/removed/changed in mono". */
function DiffView() {
const { t } = useTranslation()
const diff = useEnvStore((s) => s.diff)
if (diff === null) return null
const empty =
diff.added.length === 0 && diff.removed.length === 0 && diff.changed.length === 0
if (empty) return <p className="text-data text-text-dim">{t('snapshots.noDifference')}</p>
return (
<dl className="space-y-3" data-diff>
{/* "Added" means present now and absent from the snapshot — so restoring *removes* it. The
copy says which direction, because the bare word is ambiguous the moment you are looking
at it from the snapshot's side. */}
<Group label={t('snapshots.diffAdded', { count: diff.added.length })} tone="warn">
{diff.added.map((s) => `${s.name}==${s.version}`)}
</Group>
<Group label={t('snapshots.diffRemoved', { count: diff.removed.length })} tone="accent">
{diff.removed.map((s) => `${s.name}==${s.version}`)}
</Group>
<Group label={t('snapshots.diffChanged', { count: diff.changed.length })} tone="info">
{diff.changed.map((c) => `${c.name} ${c.current} → ${c.snapshot}`)}
</Group>
</dl>
)
}
function Group({
label,
tone,
children,
}: {
label: string
tone: 'warn' | 'accent' | 'info'
children: string[]
}) {
if (children.length === 0) return null
const color = tone === 'warn' ? 'text-warn' : tone === 'accent' ? 'text-accent' : 'text-info'
return (
<div>
<dt className={`text-data ${color}`}>{label}</dt>
{children.map((line) => (
<dd key={line}>
<code className="font-mono text-data">{line}</code>
</dd>
))}
</div>
)
}
+41 -11
View File
@@ -16,6 +16,7 @@ import { useTranslation } from 'react-i18next'
import { PdEmptyState } from '@/components/PdEmptyState'
import { PdErrorRow } from '@/components/PdErrorRow'
import { onScanProgress, type EnvRow } from '@/ipc'
import { PdEnvDetail } from '@/screens/PdEnvDetail'
import { useEnvStore } from '@/stores'
function SourceChip({ row }: { row: EnvRow }) {
@@ -31,6 +32,7 @@ function Row({ row }: { row: EnvRow }) {
const { t } = useTranslation()
const selected = useEnvStore((s) => s.selected)
const select = useEnvStore((s) => s.select)
const openEnv = useEnvStore((s) => s.openEnv)
const isSelected = selected === row.interpreter
const managed = row.env?.externallyManaged === true
@@ -79,16 +81,30 @@ function Row({ row }: { row: EnvRow }) {
<PdErrorRow error={row.error} />
</div>
) : (
<button
type="button"
onClick={() => {
select(row.interpreter)
}}
disabled={isSelected}
className="mt-2 rounded-pd border border-border px-3 py-1 text-data disabled:opacity-40"
>
{t('actions.use')}
</button>
<div className="mt-2 flex items-center gap-2">
<button
type="button"
onClick={() => {
select(row.interpreter)
}}
disabled={isSelected}
className="rounded-pd border border-border px-3 py-1 text-data disabled:opacity-40"
>
{t('actions.use')}
</button>
{/* UI-SPEC §5's 4-click rollback starts here: Environments is the landing screen, so
Open → snapshot → Rollback… → Roll back is the whole budget. */}
<button
type="button"
onClick={() => {
openEnv(row.interpreter)
}}
data-action="open"
className="rounded-pd border border-border px-3 py-1 text-data"
>
{t('actions.open')}
</button>
</div>
)}
</li>
)
@@ -96,7 +112,16 @@ function Row({ row }: { row: EnvRow }) {
export function PdEnvironments() {
const { t } = useTranslation()
const { rows, scanning, progress, error, scan, setProgress } = useEnvStore()
// Per-field selectors, not a bare `useEnvStore()`: that subscribes to every field, so opening
// a detail view or selecting a snapshot would re-render the whole environment list.
const rows = useEnvStore((s) => s.rows)
const scanning = useEnvStore((s) => s.scanning)
const progress = useEnvStore((s) => s.progress)
const error = useEnvStore((s) => s.error)
const scan = useEnvStore((s) => s.scan)
const setProgress = useEnvStore((s) => s.setProgress)
const openFor = useEnvStore((s) => s.openFor)
useEffect(() => {
// Subscribe before scanning, or the first phases are emitted into nothing.
@@ -110,6 +135,11 @@ export function PdEnvironments() {
}
}, [scan, setProgress])
// The detail view is a mode of this tab, not a ninth sidebar entry — a ninth entry would
// renumber Ctrl+1..8, which the keyboard map fixes in place. Below the hooks, so the hook order
// is identical whether or not a detail is open.
if (openFor !== null) return <PdEnvDetail />
return (
<section aria-labelledby="env-title" className="h-full overflow-auto p-6">
<div className="flex items-center justify-between">
+34 -6
View File
@@ -14,6 +14,7 @@ import { useTranslation } from 'react-i18next'
import { PdConsoleDrawer } from '@/components/PdConsoleDrawer'
import { PdErrorRow } from '@/components/PdErrorRow'
import { PdPreviewDiff } from '@/components/PdPreviewDiff'
import { PdRollbackPreview } from '@/components/PdRollbackPreview'
import { PdSummarySheet } from '@/components/PdSummarySheet'
import { usePlanStore } from '@/stores'
@@ -27,6 +28,8 @@ export function PdPlanPanel({ onFinished }: PdPlanPanelProps) {
const phase = usePlanStore((s) => s.phase)
const step = usePlanStore((s) => s.step)
const kind = usePlanStore((s) => s.kind)
const preview = usePlanStore((s) => s.preview)
const decisions = usePlanStore((s) => s.decisions)
const consoleLines = usePlanStore((s) => s.console)
const consoleOpen = usePlanStore((s) => s.consoleOpen)
@@ -103,15 +106,29 @@ export function PdPlanPanel({ onFinished }: PdPlanPanelProps) {
)
}
const changeCount = step !== null && 'report' in step ? (step.report.changes ?? []).length : 0
// A rollback produces no `FlowStep` — there is nothing to resolve and nothing to decide — so
// every guard below that reads `step` would answer "no" and disable the one button the flow
// needs. `kind` is what distinguishes "no plan" from "a plan of a different shape".
const isRollback = kind === 'rollback'
const rollbackOps =
preview === null ? 0 : preview.restore.uninstall.length + preview.restore.install.length
const changeCount = isRollback
? rollbackOps
: step !== null && 'report' in step
? (step.report.changes ?? []).length
: 0
const needsDecisions = step?.step === 'needsDecisions'
const exhausted = step?.step === 'roundsExhausted'
const nothingToDo = isRollback ? preview !== null && rollbackOps === 0 : step?.step === 'nothing'
const confirmable = isRollback ? preview !== null && rollbackOps > 0 : step !== null && step.step !== 'nothing'
return (
<section className="flex h-full min-h-0 flex-col">
<div className="min-h-0 flex-1 overflow-auto p-6">
<div className="flex items-baseline justify-between">
<h1 className="text-accent">{t('plan.previewTitle')}</h1>
<h1 className="text-accent">
{isRollback ? t('snapshots.rollbackTitle') : t('plan.previewTitle')}
</h1>
<span aria-live="polite" className="text-data text-text-dim">
{phase === 'resolving' ? t('plan.resolving') : null}
{phase === 'executing'
@@ -137,13 +154,19 @@ export function PdPlanPanel({ onFinished }: PdPlanPanelProps) {
) : null}
{exhausted ? <p className="mt-2 text-data text-warn">{t('plan.roundsExhausted')}</p> : null}
{preview !== null ? (
<div className="mt-4">
<PdRollbackPreview preview={preview} />
</div>
) : null}
{step !== null && 'report' in step ? (
<div className="mt-4">
<PdPreviewDiff report={step.report} decisions={decisions} onChoose={choose} />
</div>
) : null}
{step?.step === 'nothing' ? (
{nothingToDo ? (
<p className="mt-4 text-data text-text-dim">{t('plan.emptyPreview')}</p>
) : null}
</div>
@@ -212,10 +235,15 @@ export function PdPlanPanel({ onFinished }: PdPlanPanelProps) {
onClick={() => {
void execute()
}}
disabled={phase === 'resolving' || step === null || step.step === 'nothing'}
className="rounded-pd border border-accent px-3 py-1 text-data text-accent disabled:border-border disabled:text-text-dim disabled:opacity-40"
disabled={phase === 'resolving' || !confirmable}
className={`rounded-pd border px-3 py-1 text-data disabled:border-border disabled:text-text-dim disabled:opacity-40 ${
// A restore removes things. It gets the danger treatment the update path does not.
isRollback ? 'border-danger text-danger' : 'border-accent text-accent'
}`}
>
{t('plan.confirm', { count: changeCount })}
{isRollback
? t('snapshots.confirmRollback', { count: changeCount })
: t('plan.confirm', { count: changeCount })}
</button>
</>
)}
+20
View File
@@ -0,0 +1,20 @@
/**
* Load the open environment's snapshots, once per environment.
*
* The sibling of `useEnvPackages`, and separate from it because the two are read by different
* screens for different reasons: nothing but the detail view wants a timeline, and paying a
* directory read on every Installed mount to have it ready would be a fetch nobody asked for.
*/
import { useEffect } from 'react'
import { useEnvStore } from '@/stores'
export function useEnvSnapshots(): void {
const openFor = useEnvStore((s) => s.openFor)
const loadSnapshots = useEnvStore((s) => s.loadSnapshots)
useEffect(() => {
if (openFor !== null) void loadSnapshots()
}, [openFor, loadSnapshots])
}
+98
View File
@@ -26,6 +26,9 @@ import {
pinRemove,
pkgList,
pkgOutdated,
snapshotCreate,
snapshotDiff,
snapshotList,
settingsGet,
settingsSet,
type Dist,
@@ -35,6 +38,8 @@ import {
type Pin,
type ScanProgress,
type Settings,
type Diff,
type SnapshotMeta,
} from '@/ipc'
import { joinRows, type LoadState, type PackageRow } from '@/screens/rows'
@@ -169,6 +174,34 @@ interface EnvState {
togglePin: (name: string) => Promise<void>
/** Set or clear a pin's reason, leaving its mode alone. `null` clears it. */
updatePin: (name: string, reason: string | null) => Promise<void>
// -- the snapshot slice, for the env detail (UI-SPEC §4) -------------------------------------
/**
* Which environment's detail view is open, by interpreter path.
*
* In the store rather than the screen's `useState` because the plan panel replaces the whole
* content area while a rollback runs. Local state would be unmounted with it, and the user
* would land back on the flat list the moment their rollback finished.
*/
openFor: string | null
snapshots: SnapshotMeta[]
/** Which environment `snapshots` describes, so re-opening the same one does not refetch. */
snapshotsFor: string | null
snapshotsLoading: LoadState
snapshotsError: PdError | null
/** The timeline entry being inspected. */
selectedSnapshot: string | null
/** Its diff against the environment as it is now. */
diff: Diff | null
diffLoading: LoadState
openEnv: (interpreter: string) => void
closeEnv: () => void
/** `force` refetches even when `snapshotsFor` already matches — used after a rollback. */
loadSnapshots: (force?: boolean) => Promise<void>
selectSnapshot: (id: string | null) => Promise<void>
takeSnapshot: () => Promise<void>
}
/** Everything the package slice resets to. Named so a future field cannot be forgotten. */
@@ -185,6 +218,15 @@ const NO_PACKAGES = {
outdatedStatus: 'idle' as LoadState,
outdatedError: null,
selection: new Set<string>(),
// The timeline belongs to an environment as much as the package list does; leaving it behind on
// a switch would offer one environment's snapshots under another's name.
snapshots: [] as SnapshotMeta[],
snapshotsFor: null,
snapshotsLoading: 'idle' as LoadState,
snapshotsError: null,
selectedSnapshot: null,
diff: null,
diffLoading: 'idle' as LoadState,
}
/** Recompute the joined view from the three raw responses. */
@@ -203,6 +245,7 @@ export const useEnvStore = create<EnvState>((set, get) => ({
scanning: false,
progress: null,
error: null,
openFor: null,
...NO_PACKAGES,
scan: async () => {
@@ -306,6 +349,61 @@ export const useEnvStore = create<EnvState>((set, get) => ({
)
},
openEnv: (interpreter) => set({ openFor: interpreter }),
closeEnv: () => set({ openFor: null, selectedSnapshot: null, diff: null }),
loadSnapshots: async (force = false) => {
const { openFor, rows, snapshotsFor } = get()
const row = rows.find((r) => r.interpreter === openFor)
if (row === undefined) return
if (!force && snapshotsFor === openFor) return
set({ snapshotsLoading: 'loading', snapshotsError: null })
try {
// By `envHash`, not by interpreter: a snapshot outlives the Python that made it, so this
// works on a row whose probe failed and whose `env` is therefore absent.
set({
snapshots: await snapshotList(row.envHash),
snapshotsFor: openFor,
snapshotsLoading: 'ready',
})
} catch (e) {
set({ snapshotsLoading: 'error', snapshotsError: asPdError(e) })
}
},
selectSnapshot: async (id) => {
const { openFor, rows } = get()
set({ selectedSnapshot: id, diff: null })
if (id === null) return
const row = rows.find((r) => r.interpreter === openFor)
// A dead interpreter can list its snapshots but cannot be diffed against — there is nothing
// to freeze. The timeline says so rather than spinning.
if (row?.env === undefined) return
set({ diffLoading: 'loading', snapshotsError: null })
try {
set({ diff: await snapshotDiff(row.env, id), diffLoading: 'ready' })
} catch (e) {
set({ diffLoading: 'error', snapshotsError: asPdError(e) })
}
},
takeSnapshot: async () => {
const { openFor, rows } = get()
const row = rows.find((r) => r.interpreter === openFor)
if (row?.env === undefined) return
set({ snapshotsError: null })
try {
await snapshotCreate(row.env)
await get().loadSnapshots(true)
} catch (e) {
set({ snapshotsError: asPdError(e) })
}
},
updatePin: async (name, reason) => {
const { pins } = get()
const existing = pins.find((p) => p.pkg === name)
+22 -2
View File
@@ -27,6 +27,8 @@ import {
planDecide,
planExecute,
planResolve,
snapshotRollback,
snapshotRollbackPreview,
uninstallExecute,
uninstallGuard,
type Decision,
@@ -37,6 +39,7 @@ import {
type PdError,
type ProgressEvent,
type PyEnv,
type RollbackPreview,
} from '@/ipc'
/**
@@ -85,7 +88,7 @@ export const PANEL_PHASES: ReadonlySet<PlanPhase> = new Set<PlanPhase>([
* in Rust either way, so two stores would be two front ends onto one slot, each able to think it
* owns it.
*/
export type PlanKind = 'update' | 'install' | 'uninstall'
export type PlanKind = 'update' | 'install' | 'uninstall' | 'rollback'
/** One console line, already flattened for rendering. */
export interface ConsoleLine {
@@ -106,6 +109,8 @@ interface PlanState {
env: PyEnv | null
/** What the guard found, while `phase` is `guard`. */
guard: GuardReport | null
/** What a rollback would do, while `kind` is `rollback` — DATA-FLOW §8. */
preview: RollbackPreview | null
/** True while a re-guard is in flight, so the dialog can say so rather than flicker. */
guardBusy: boolean
/** What the flow says it needs next, or null before the first resolve. */
@@ -136,6 +141,8 @@ interface PlanState {
widen: () => Promise<void>
/** Remove. `force` is *Force remove only X*. */
confirmUninstall: (force: boolean) => Promise<void>
/** Preview restoring `id`, which parks the flow that would do it (DATA-FLOW §8). */
rollback: (env: PyEnv, id: string) => Promise<void>
cancel: () => Promise<void>
setConsoleOpen: (open: boolean) => void
/** Return to the table, discarding the preview or the summary. */
@@ -151,6 +158,7 @@ const EMPTY = {
env: null,
guard: null,
guardBusy: false,
preview: null,
step: null,
decisions: {},
console: [] as ConsoleLine[],
@@ -233,7 +241,10 @@ export const usePlanStore = create<PlanState>((set, get) => ({
},
execute: async () => {
await runToSummary(set, planExecute)
// One button, two commands. `PdPlanPanel`'s Confirm is the same control for both flows, and
// which one it sends is the session's kind rather than anything the button knows.
const command = get().kind === 'rollback' ? snapshotRollback : planExecute
await runToSummary(set, command)
},
startUninstall: async (env, pkgs) => {
@@ -267,6 +278,15 @@ export const usePlanStore = create<PlanState>((set, get) => ({
await runToSummary(set, () => uninstallExecute(force))
},
rollback: async (env, id) => {
set({ phase: 'resolving', ...EMPTY, kind: 'rollback', env })
try {
set({ preview: await snapshotRollbackPreview(env, id), phase: 'preview' })
} catch (e) {
set({ phase: 'failed', error: asPdError(e) })
}
},
cancel: async () => {
set({ cancelling: true })
try {