feat(ui): Add interpreter… and Remove from list on Environments

The header and the empty state offer Add interpreter…, which asks for a
python.exe and selects what it added; an added row, broken or not,
offers Remove from list. Busy is aria-disabled with a click guard, an
add and a scan refuse to overlap, the result is said in a status region
mounted before its words, and focus goes to the heading when the row
holding it leaves. Ctrl+K has the add too. PD-ENV-001's copy now covers
a file PipDock will not run, in both catalogues.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5.5 committed 2026-11-21 23:22:12 +07:00
1 parent ab16742989
commit c9128e479e
10 files changed
+461 -23

No files matched your search

+12
View File
@@ -49,6 +49,7 @@ export function PdPalette({ onClose }: { onClose: () => void }) {
const setNav = useUiStore((s) => s.setNav)
const scan = useEnvStore((s) => s.scan)
const addManual = useEnvStore((s) => s.addManual)
const loadPackages = useEnvStore((s) => s.loadPackages)
const loadOutdated = useEnvStore((s) => s.loadOutdated)
const takeSnapshot = useEnvStore((s) => s.takeSnapshot)
@@ -79,6 +80,16 @@ export function PdPalette({ onClose }: { onClose: () => void }) {
void scan()
},
},
{
// The picker opens over whichever screen is showing; Environments is where the row lands.
id: 'env:add-manual',
label: t('palette.addInterpreter'),
group: t('nav.environments'),
run: () => {
setNav('environments')
void addManual(t('env.addTitle'))
},
},
{
id: 'pkg:refresh',
label: t('palette.refreshPackages'),
@@ -137,6 +148,7 @@ export function PdPalette({ onClose }: { onClose: () => void }) {
t,
setNav,
scan,
addManual,
loadPackages,
loadOutdated,
clearSelection,
+13
View File
@@ -55,6 +55,7 @@ export const COMMANDS = [
'app_info',
'env_scan',
'env_add_manual',
'env_remove_manual',
'env_probe',
'pkg_list',
'pkg_outdated',
@@ -210,6 +211,18 @@ export const envScan = (): Promise<EnvRow[]> => invoke('env_scan')
export const envProbe = (interpreter: string, source?: EnvSource): Promise<EnvRow> =>
invoke('env_probe', source === undefined ? { interpreter } : { interpreter, source })
/**
* Add an interpreter the person picked to the list discovery is shown beside, and return its row —
* *Add interpreter…* (PRD P0-1). Rust validates the path before anything runs it, probes it, and
* stores it only when both succeed; the row carries the canonical path it stored.
*/
export const envAddManual = (interpreter: string): Promise<EnvRow> =>
invoke('env_add_manual', { interpreter })
/** Take an added interpreter off that list. Nothing on disk is touched. `false` if it was not on it. */
export const envRemoveManual = (envHash: string): Promise<boolean> =>
invoke('env_remove_manual', { envHash })
/**
* Everything installed in `env` — the Installed table.
*
+10 -3
View File
@@ -48,7 +48,7 @@
"pipUpgradeNoSnapshot": "No snapshot is taken: restoring one would need the pip being replaced.",
"title": "Environments",
"empty": "no Python environments found",
"emptyHint": "Install Python, or create a virtual environment named .venv, venv, env or .env in this folder.",
"emptyHint": "Install Python, or add one you already have — the python.exe inside a virtual environment’s Scripts folder, for example.",
"scanning": "Discovering environments…",
"scanPhase": {
"registry": "Reading the Windows registry",
@@ -66,7 +66,13 @@
},
"managed": "MANAGED",
"managedDetail": "Externally managed (PEP 668). Create a virtual environment instead; the override lives in Settings and is discouraged.",
"selected": "Selected"
"selected": "Selected",
"add": "Add interpreter…",
"addTitle": "Choose a Python interpreter (python.exe)",
"added": "Added {{path}} to the list.",
"remove": "Remove from list",
"removeLabel": "Remove from list: {{path}}",
"removed": "Removed {{path}} from the list. Nothing on disk was changed."
},
"packages": {
"installedTitle": "Installed",
@@ -198,7 +204,8 @@
"clearQueue": "Empty the install queue",
"groups": {
"go": "Go to"
}
},
"addInterpreter": "Add a Python interpreter…"
},
"pins": {
"empty": "no pins in this environment",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"errors": {
"PD-ENV-001": "That interpreter is missing or cannot be run.",
"PD-ENV-001": "That interpreter is missing, or PipDock cannot run it.",
"PD-ENV-002": "This Python is managed by the operating system.",
"PD-ENV-003": "PipDock could not read this environment.",
"PD-ENG-001": "The selected engine is not installed or not on PATH.",
+10 -3
View File
@@ -47,7 +47,7 @@
"pipUpgradeNoSnapshot": "Không tạo bản chụp: khôi phục nó sẽ cần chính pip đang được thay thế.",
"title": "Môi trường",
"empty": "không tìm thấy môi trường Python nào",
"emptyHint": "Hãy cài Python, hoặc tạo một môi trường ảo tên .venv, venv, env hoặc .env trong thư mục này.",
"emptyHint": "Hãy cài Python, hoặc thêm một trình thông dịch bạn đã có — ví dụ python.exe trong thư mục Scripts của một môi trường ảo.",
"scanning": "Đang tìm môi trường…",
"scanPhase": {
"registry": "Đang đọc registry của Windows",
@@ -65,7 +65,13 @@
},
"managed": "HỆ THỐNG",
"managedDetail": "Môi trường do hệ điều hành quản lý (PEP 668). Hãy tạo một môi trường ảo; tuỳ chọn ghi đè nằm trong Cài đặt và không được khuyến khích.",
"selected": "Đang chọn"
"selected": "Đang chọn",
"add": "Thêm trình thông dịch…",
"addTitle": "Chọn trình thông dịch Python (python.exe)",
"added": "Đã thêm {{path}} vào danh sách.",
"remove": "Bỏ khỏi danh sách",
"removeLabel": "Bỏ khỏi danh sách: {{path}}",
"removed": "Đã bỏ {{path}} khỏi danh sách. Không có gì trên đĩa bị thay đổi."
},
"packages": {
"installedTitle": "Đã cài",
@@ -185,7 +191,8 @@
"clearQueue": "Xoá hàng đợi cài đặt",
"groups": {
"go": "Đi tới"
}
},
"addInterpreter": "Thêm trình thông dịch Python…"
},
"pins": {
"empty": "môi trường này chưa có gói nào được ghim",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"errors": {
"PD-ENV-001": "Không tìm thấy hoặc không chạy được trình thông dịch đó.",
"PD-ENV-001": "Không tìm thấy trình thông dịch đó, hoặc PipDock không thể chạy nó.",
"PD-ENV-002": "Bản Python này do hệ điều hành quản lý.",
"PD-ENV-003": "PipDock không đọc được môi trường này.",
"PD-ENG-001": "Bộ máy đã chọn chưa được cài, hoặc không có trong PATH.",
+230
View File
@@ -0,0 +1,230 @@
/**
* *Add interpreter…* and *Remove from list* — PRD P0-1's manual browse (1.6.0).
*
* The store half and the screen half, because the seam between them is where this app's bugs have
* lived (CLAUDE.md, `PdPlanPanel`): the store merges by `envHash` and the screen renders by
* interpreter path, and a test of either alone would not see the two disagree.
*/
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import * as ipc from '@/ipc'
import type { EnvRow, PdError } from '@/ipc'
import { PdEnvironments } from '@/screens/PdEnvironments'
import { useEnvStore } from '@/stores'
import { resetStore } from '@/test/stores'
vi.mock('@/ipc', async () => {
const actual = await vi.importActual<typeof import('@/ipc')>('@/ipc')
const { ipcMock } = await import('@/test/ipc')
return {
...actual,
...ipcMock(),
onScanProgress: vi.fn().mockResolvedValue(() => undefined),
}
})
const row = (name: string, source: EnvRow['source'] = 'venv-scan'): EnvRow => {
const interpreter = `D:\\work\\${name}\\Scripts\\python.exe`
return {
interpreter,
source,
envHash: `hash-${name}`,
env: {
interpreter,
prefix: `D:\\work\\${name}`,
pythonVersion: '3.13.9',
externallyManaged: false,
hiddenUserSite: null,
source,
},
}
}
const DISCOVERED = row('discovered', 'registry')
const ADDED = row('myenv', 'manual')
const missing: PdError = { code: 'PD-ENV-001', message: 'no interpreter at E:\\gone\\python.exe' }
const GONE: EnvRow = {
interpreter: 'E:\\gone\\python.exe',
source: 'manual',
envHash: 'hash-gone',
error: missing,
}
beforeEach(() => {
vi.clearAllMocks()
resetStore(useEnvStore)
})
describe('the store', () => {
it('asks for a python.exe with the title it was given, and a cancelled picker changes nothing', async () => {
vi.mocked(ipc.pickOpenFile).mockResolvedValueOnce(null)
useEnvStore.setState({ rows: [DISCOVERED], selected: DISCOVERED.interpreter })
await useEnvStore.getState().addManual('Choose one')
expect(ipc.pickOpenFile).toHaveBeenCalledWith('Choose one', ['exe'])
expect(ipc.envAddManual).not.toHaveBeenCalled()
const state = useEnvStore.getState()
expect(state.addingManual).toBe(false)
expect(state.rows).toEqual([DISCOVERED])
expect(state.selected).toBe(DISCOVERED.interpreter)
})
it('appends the new row, selects it and says so', async () => {
vi.mocked(ipc.pickOpenFile).mockResolvedValueOnce('d:\\work\\myenv\\scripts\\python.exe')
vi.mocked(ipc.envAddManual).mockResolvedValueOnce(ADDED)
useEnvStore.setState({ rows: [DISCOVERED], selected: DISCOVERED.interpreter })
await useEnvStore.getState().addManual('Choose one')
expect(ipc.envAddManual).toHaveBeenCalledWith('d:\\work\\myenv\\scripts\\python.exe')
const state = useEnvStore.getState()
// The row Rust returned, with the canonical path it stored — not the spelling picked.
expect(state.rows).toEqual([DISCOVERED, ADDED])
expect(state.selected).toBe(ADDED.interpreter)
expect(state.manualNotice).toEqual({ kind: 'added', path: ADDED.interpreter })
expect(state.addingManual).toBe(false)
})
it('does not list an interpreter twice when discovery already has it', async () => {
// The same environment under the registry's spelling: one row, the discovered one, selected.
vi.mocked(ipc.pickOpenFile).mockResolvedValueOnce(DISCOVERED.interpreter)
vi.mocked(ipc.envAddManual).mockResolvedValueOnce({
...ADDED,
envHash: DISCOVERED.envHash,
interpreter: DISCOVERED.interpreter.toUpperCase(),
})
useEnvStore.setState({ rows: [DISCOVERED], selected: null })
await useEnvStore.getState().addManual('Choose one')
const state = useEnvStore.getState()
expect(state.rows).toEqual([DISCOVERED])
expect(state.selected).toBe(DISCOVERED.interpreter)
})
it('keeps a refused path off the list and shows why', async () => {
const refused: PdError = {
code: 'PD-ENV-001',
message: 'D:\\notepad.exe is not a Python interpreter PipDock will run',
}
vi.mocked(ipc.pickOpenFile).mockResolvedValueOnce('D:\\notepad.exe')
vi.mocked(ipc.envAddManual).mockRejectedValueOnce(refused)
useEnvStore.setState({ rows: [DISCOVERED] })
await useEnvStore.getState().addManual('Choose one')
const state = useEnvStore.getState()
expect(state.rows).toEqual([DISCOVERED])
expect(state.error?.code).toBe('PD-ENV-001')
expect(state.addingManual).toBe(false)
})
it('refuses to add while a scan runs, and to scan while an add runs', async () => {
// A scan that read the list before the add wrote it would replace `rows` without the new row.
useEnvStore.setState({ scanning: true })
await useEnvStore.getState().addManual('Choose one')
expect(ipc.pickOpenFile).not.toHaveBeenCalled()
useEnvStore.setState({ scanning: false, addingManual: true })
await useEnvStore.getState().scan()
expect(ipc.envScan).not.toHaveBeenCalled()
})
it('removes a row, falls back from a selection it held and closes its detail', async () => {
useEnvStore.setState({
rows: [DISCOVERED, ADDED],
selected: ADDED.interpreter,
openFor: ADDED.interpreter,
})
await useEnvStore.getState().removeManual(ADDED.envHash)
expect(ipc.envRemoveManual).toHaveBeenCalledWith(ADDED.envHash)
const state = useEnvStore.getState()
expect(state.rows).toEqual([DISCOVERED])
expect(state.selected).toBe(DISCOVERED.interpreter)
expect(state.openFor).toBeNull()
expect(state.manualNotice).toEqual({ kind: 'removed', path: ADDED.interpreter })
expect(state.removingManual).toBeNull()
})
it('leaves the selection alone when another row is removed', async () => {
useEnvStore.setState({ rows: [DISCOVERED, GONE], selected: DISCOVERED.interpreter })
await useEnvStore.getState().removeManual(GONE.envHash)
expect(useEnvStore.getState().selected).toBe(DISCOVERED.interpreter)
expect(useEnvStore.getState().rows).toEqual([DISCOVERED])
})
})
describe('the screen', () => {
it('offers Add interpreter… beside Rescan, busy while a scan runs', () => {
const addManual = vi.fn()
useEnvStore.setState({ rows: [DISCOVERED], scanning: true, scan: vi.fn(), addManual })
render(<PdEnvironments />)
const add = screen.getByRole('button', { name: 'Add interpreter…' })
expect(add).toHaveAttribute('aria-disabled', 'true')
expect(add).not.toBeDisabled()
fireEvent.click(add)
expect(addManual).not.toHaveBeenCalled()
act(() => {
useEnvStore.setState({ scanning: false })
})
fireEvent.click(add)
expect(addManual).toHaveBeenCalledWith('Choose a Python interpreter (python.exe)')
})
it('makes Add interpreter… the empty state’s one action', () => {
useEnvStore.setState({ rows: [], scanning: false, scan: vi.fn() })
render(<PdEnvironments />)
expect(screen.getAllByRole('button', { name: 'Add interpreter…' })).toHaveLength(2)
})
it('offers Remove from list on added rows only, broken ones included', () => {
useEnvStore.setState({ rows: [DISCOVERED, ADDED, GONE], scan: vi.fn() })
render(<PdEnvironments />)
const removes = screen.getAllByRole('button', { name: /^Remove from list: / })
expect(removes.map((b) => b.getAttribute('aria-label'))).toEqual([
`Remove from list: ${ADDED.interpreter}`,
`Remove from list: ${GONE.interpreter}`,
])
// Forgetting an entry deletes nothing, so it is not drawn as destructive (UI-SPEC §7).
for (const button of removes) expect(button).not.toHaveAttribute('data-destructive')
})
it('says what was added in a status region that was there before the words', () => {
useEnvStore.setState({ rows: [DISCOVERED], scan: vi.fn() })
render(<PdEnvironments />)
const status = screen.getByRole('status')
expect(status).toHaveTextContent('')
act(() => {
useEnvStore.setState({
rows: [DISCOVERED, ADDED],
manualNotice: { kind: 'added', path: ADDED.interpreter },
})
})
expect(screen.getByRole('status')).toBe(status)
expect(status).toHaveTextContent(`Added ${ADDED.interpreter} to the list.`)
})
it('moves focus to the heading when the row whose button had it goes', async () => {
useEnvStore.setState({ rows: [DISCOVERED, ADDED], selected: DISCOVERED.interpreter, scan: vi.fn() })
render(<PdEnvironments />)
const remove = screen.getByRole('button', { name: `Remove from list: ${ADDED.interpreter}` })
remove.focus()
expect(remove).toHaveFocus()
fireEvent.click(remove)
await waitFor(() => {
expect(screen.queryByRole('button', { name: /^Remove from list: / })).toBeNull()
})
expect(screen.getByRole('heading', { level: 1, name: 'Environments' })).toHaveFocus()
})
})
+93 -14
View File
@@ -7,9 +7,14 @@
*
* A row whose probe failed renders **in place** with its code rather than disappearing: one broken
* interpreter must not hide the rest, which is the rule `pipdock env list` already follows.
*
* *Add interpreter…* (PRD P0-1's manual browse, 1.6.0) puts any `python.exe` on the list — the GUI
* has no working directory worth scanning, so before it a venv anywhere but the four folder names
* beside the program was out of reach. An added row carries *Remove from list*, broken or not: a
* venv deleted from disk stays listed with `PD-ENV-001` precisely so it can be removed.
*/
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { PdDialog } from '@/components/PdDialog'
@@ -34,6 +39,49 @@ function SourceChip({ row }: { row: EnvRow }) {
)
}
/** *Remove from list*, on a row *Add interpreter…* put there. Never `data-destructive`: it forgets
* an entry, deletes nothing, and the same picker adds it back. */
function RemoveButton({ row }: { row: EnvRow }) {
const { t } = useTranslation()
const removeManual = useEnvStore((s) => s.removeManual)
const busy = useEnvStore((s) => s.removingManual !== null)
return (
<button
type="button"
onClick={() => {
if (!busy) void removeManual(row.envHash)
}}
aria-disabled={busy}
// The visible words first, then the path: the name contains what is on the button.
aria-label={t('env.removeLabel', { path: row.interpreter })}
data-action="remove-manual"
className="rounded-pd border border-border px-3 py-1 text-data aria-disabled:opacity-40"
>
{t('env.remove')}
</button>
)
}
/** *Add interpreter…*, in the header and as the empty state's one action (UI-SPEC §7). */
function AddButton() {
const { t } = useTranslation()
const addManual = useEnvStore((s) => s.addManual)
const busy = useEnvStore((s) => s.addingManual || s.scanning)
return (
<button
type="button"
onClick={() => {
if (!busy) void addManual(t('env.addTitle'))
}}
aria-disabled={busy}
data-action="add-manual"
className="rounded-pd border border-border px-3 py-1 text-data aria-disabled:opacity-40"
>
{t('env.add')}
</button>
)
}
function Row({ row }: { row: EnvRow }) {
const { t } = useTranslation()
const selected = useEnvStore((s) => s.selected)
@@ -87,8 +135,9 @@ function Row({ row }: { row: EnvRow }) {
) : null}
{row.error !== undefined ? (
<div className="mt-2">
<div className="mt-2 space-y-2">
<PdErrorRow error={row.error} />
{row.source === 'manual' ? <RemoveButton row={row} /> : null}
</div>
) : (
<div className="mt-2 flex items-center gap-2">
@@ -134,6 +183,7 @@ function Row({ row }: { row: EnvRow }) {
{upgrading ? t('env.pipUpgrading') : t('env.pipUpgrade')}
</button>
) : null}
{row.source === 'manual' ? <RemoveButton row={row} /> : null}
</div>
)}
@@ -181,12 +231,28 @@ export function PdEnvironments() {
// 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 adding = useEnvStore((s) => s.addingManual)
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)
const manualNotice = useEnvStore((s) => s.manualNotice)
const { open, failed: openFailed } = useOpenExternal()
const headingRef = useRef<HTMLHeadingElement>(null)
// *Remove from list* unmounts the button that was pressed, so focus fell to <body> and the next
// Tab started from the top of the window. App's lost-focus rule covers screens being replaced;
// a row leaving the list is this screen's own business. Same condition: only when focus was
// actually lost, so a rescan never pulls anyone off the control they are on.
useEffect(() => {
const active = document.activeElement
if (active !== null && active !== document.body && active.isConnected) return
const heading = headingRef.current
if (heading === null) return
heading.setAttribute('tabindex', '-1')
heading.focus()
}, [rows])
useEffect(() => {
// Subscribe before scanning, or the first phases are emitted into nothing.
@@ -209,21 +275,34 @@ export function PdEnvironments() {
return (
<section aria-labelledby="env-title" className="h-full overflow-auto p-6">
<div className="flex items-center justify-between">
<h1 id="env-title" className="text-accent">
<h1 id="env-title" ref={headingRef} className="text-accent">
{t('env.title')}
</h1>
<button
type="button"
onClick={() => {
if (!scanning) void scan()
}}
aria-disabled={scanning}
className="rounded-pd border border-border px-3 py-1 text-data aria-disabled:opacity-40"
>
{t('actions.rescan')}
</button>
<div className="flex items-center gap-2">
<AddButton />
<button
type="button"
onClick={() => {
if (!scanning && !adding) void scan()
}}
aria-disabled={scanning || adding}
className="rounded-pd border border-border px-3 py-1 text-data aria-disabled:opacity-40"
>
{t('actions.rescan')}
</button>
</div>
</div>
{/* Mounted from the start and only its text changes: a live region that arrives together
with its words may never be announced (ACCESSIBILITY.md, backlog A2). */}
<p role="status" className="mt-2 text-data text-text-dim">
{manualNotice === null
? ''
: t(manualNotice.kind === 'added' ? 'env.added' : 'env.removed', {
path: manualNotice.path,
})}
</p>
{scanning ? (
<p aria-live="polite" className="mt-4 text-text-dim">
{progress === null
@@ -239,7 +318,7 @@ export function PdEnvironments() {
) : null}
{!scanning && rows.length === 0 && error === null ? (
<PdEmptyState message={t('env.empty')} hint={t('env.emptyHint')} />
<PdEmptyState message={t('env.empty')} hint={t('env.emptyHint')} action={<AddButton />} />
) : null}
<ul className="mt-4 space-y-2">
+87 -1
View File
@@ -23,7 +23,9 @@ import i18n, {
type Locale,
} from '@/i18n'
import {
envAddManual,
envProbe,
envRemoveManual,
envScan,
legalConsentGet,
legalConsentSet,
@@ -32,6 +34,7 @@ import {
pinRemove,
pinSuggestions,
pipUpgrade,
pickOpenFile,
pkgList,
pkgOutdated,
snapshotCreate,
@@ -176,6 +179,29 @@ interface EnvState {
*/
upgradePip: (interpreter: string) => Promise<void>
/** An *Add interpreter…* in flight, from the picker opening to the row arriving. */
addingManual: boolean
/**
* *Add interpreter…* (PRD P0-1): ask for a `python.exe`, put it on the list, select it.
*
* `title` arrives localized — `@/ipc` has no `t`. Cancelling the picker changes nothing. The new
* row is merged **by `envHash`**, not by path: Rust returns the canonical path it stored, and the
* same interpreter may already be listed under the spelling discovery found. Pins and snapshots
* key on the hash, so a second row would split nothing — it would only show one environment
* twice. Refused while a scan runs: the scan read the list before this add wrote to it, and its
* result would replace `rows` without the new one.
*/
addManual: (title: string) => Promise<void>
/** Which added interpreter is being taken off the list, by `envHash`. */
removingManual: string | null
/**
* Take an added interpreter off the list. Nothing on disk is touched. A selected or opened row
* that goes is deselected or closed; selection falls back as a rescan's would.
*/
removeManual: (envHash: string) => Promise<void>
/** What the last add or removal did, for the screen's status region — a path, or null. */
manualNotice: { kind: 'added' | 'removed'; path: string } | null
// -- the package slice, for Installed and Updates ------------------------------------------
/** Raw responses, one field per command, kept so any one can be refreshed on its own. */
@@ -337,7 +363,9 @@ export const useEnvStore = create<EnvState>((set, get) => ({
// expensive thing the app can do twice. `PdEnvironments` has started two on every mount since
// Stage 1 — StrictMode runs effects twice in development — which was invisible because both
// produce the same rows.
if (get().scanning) return
// Nor while an *Add interpreter…* is in flight: a scan that read the list before the add wrote
// to it would replace `rows` without the row the add is about to append.
if (get().scanning || get().addingManual) return
set({ scanning: true, error: null })
try {
const rows = await envScan()
@@ -391,6 +419,64 @@ export const useEnvStore = create<EnvState>((set, get) => ({
}
},
addingManual: false,
removingManual: null,
manualNotice: null,
addManual: async (title) => {
const { addingManual, scanning } = get()
if (addingManual || scanning) return
set({ addingManual: true, error: null })
try {
const picked = await pickOpenFile(title, ['exe'])
if (picked === null) {
set({ addingManual: false })
return
}
const row = await envAddManual(picked)
set((state) => {
const listed = state.rows.find((r) => r.envHash === row.envHash)
const interpreter = listed?.interpreter ?? row.interpreter
return {
rows: listed === undefined ? [...state.rows, row] : state.rows,
addingManual: false,
manualNotice: { kind: 'added', path: interpreter },
...(state.selected === interpreter ? {} : { selected: interpreter, ...NO_PACKAGES }),
}
})
} catch (e) {
set({ addingManual: false, error: asPdError(e) })
}
},
removeManual: async (envHash) => {
if (get().removingManual !== null) return
set({ removingManual: envHash, error: null })
try {
await envRemoveManual(envHash)
set((state) => {
const gone = state.rows.find((r) => r.envHash === envHash)
if (gone === undefined) return { removingManual: null }
const rows = state.rows.filter((r) => r.envHash !== envHash)
const deselect = state.selected === gone.interpreter
return {
rows,
removingManual: null,
manualNotice: { kind: 'removed', path: gone.interpreter },
...(deselect
? {
selected: rows.find((r) => r.env !== undefined)?.interpreter ?? null,
...NO_PACKAGES,
}
: {}),
...(state.openFor === gone.interpreter ? { openFor: null, ...NO_SNAPSHOTS } : {}),
}
})
} catch (e) {
set({ removingManual: null, error: asPdError(e) })
}
},
// Clearing the package slice here is load-bearing: without it, switching environments shows the
// previous one's packages under the new one's name. Invisible to any test that loads one env.
select: (interpreter) =>
+4
View File
@@ -48,6 +48,8 @@ export interface IpcMock {
onPlanProgress: ReturnType<typeof vi.fn>
envScan: ReturnType<typeof vi.fn>
envProbe: ReturnType<typeof vi.fn>
envAddManual: ReturnType<typeof vi.fn>
envRemoveManual: ReturnType<typeof vi.fn>
pipUpgrade: ReturnType<typeof vi.fn>
healthRun: ReturnType<typeof vi.fn>
auditRun: ReturnType<typeof vi.fn>
@@ -114,6 +116,8 @@ export function ipcMock(): IpcMock {
onPlanProgress: vi.fn().mockResolvedValue(() => undefined),
envScan: vi.fn().mockResolvedValue([]),
envProbe: vi.fn(),
envAddManual: vi.fn(),
envRemoveManual: vi.fn().mockResolvedValue(true),
pipUpgrade: vi.fn().mockResolvedValue(undefined),
healthRun: vi.fn(),
auditRun: vi.fn(),