fix(ui): the shell - window, grants, CSP, language, keys, table, contrast

The window (U21). It may now be maximized and snapped; the 1600x1100 cap is gone, and the content
column stops at max-w-content (87.5rem) instead, centred in what is left. The window is created
hidden and src-tauri/src/window.rs fits it to the monitor's work area before showing it: 1180x760
is taller than the work area of a 1920x1080 panel at 150% and of a 1366x768 laptop, so the status
line and the plan panel's Confirm opened under the taskbar. Never below 900x560; pinned to the
corner rather than centred off-screen when even that does not fit. UI-SPEC §5 says so.

The webview's grants (U1, U32). core:default granted some sixty core commands nothing called and
not core:window:allow-close, so Decline on the legal gate did nothing in the installed app while
its component test - which mocks close() - passed. default.json now holds exactly the five the
frontend calls, and a test in lib.rs pins the union of every capability file, plus the opener's
four hosts.

CSP (U56): object-src, base-uri and form-action 'none'. A release build's style-src drops
'unsafe-inline' - React sets styles through CSSOM, which CSP does not govern. index.html keeps it
for `npm run dev`, where Vite injects <style> elements; both policies are enforced, so the
stricter decides. To be confirmed on the installed build.

Language (U3): the choice is stored and applied at start. save() sent locale: null every time, so
choosing Vietnamese lasted until the window closed. Settings now load before the legal gate, so the
gate is in the chosen language too, and <html lang> follows the UI.

Keys: a screen's data-autofocus wins over the heading (U12) - Search's field lost focus to the
shell's effect, which runs after its children's - and `/` works from Search itself. Ctrl+1..9 by
e.code (U49): on AZERTY Ctrl+3 reports `"`. A release build swallows F5, Ctrl+R, Ctrl+P, Ctrl+F,
F3 and Alt+arrows (U20), which reloaded, printed and found in a single-page app.

Also: Security scrolls (U2); the legal gate shows a consent that cannot be recorded (U29); Report
bug asks for the link again with the environment, so the issue carries the Python and engine
versions, at one subprocess per click rather than per row (U31); the package table's header and
rows share one set of widths and one gutter, and narrow tables drop Size so names stay visible at
900px (U22, U23); the grid is focusable (Sonar S6852); --color-danger is #F26A63 and danger badges
use a 15% tint, with tokens.test.ts now compositing every badge tint over every surface (U46 -
3.92:1 before); test seeds typecheck instead of `as never`, the IPC mock uses the real isPdError
and has the audit cache entry (U10).

U14 and U26 were already fixed by earlier commits in this release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5.5 committed 2026-10-17 00:55:27 +07:00
1 parent 8e4b87e4ab
commit 4da4c0f3ec
36 files changed
+1033 -231

No files matched your search

+11 -4
View File
@@ -21,7 +21,7 @@ Anti-goals: gradients-everywhere SaaS look, rounded-blob cards, decorative glow.
| `--color-text` | `#E7F0EA` | primary text |
| `--color-text-dim` | `#8AA394` | secondary text, **dimmed up-to-date rows** |
| `--color-warn` | `#F5B94A` | held-back, warnings |
| `--color-danger` | `#F0574F` | impossible, failures, force actions |
| `--color-danger` | `#F26A63` | impossible, failures, force actions. `#F0574F` until 1.4.0, which read at 3.92:1 on its own badge tint over a selected row |
| `--color-info` | `#5BC0DE` | pinned, informational chips |
Type: **Inter** (UI), **JetBrains Mono** (package names, versions, console, status line — both OFL-licensed, bundled). Base 14 px, mono data 13 px. Radius 6 px; borders 1 px; shadows minimal. Motion: 120–160 ms ease-out; live-activity pulse on the status-line engine badge during execution; `prefers-reduced-motion` respected.
@@ -236,9 +236,16 @@ guarded neither. Nothing looked wrong — the sidebar was disabled and the panel
until the plan finished and dropped the user on a tab they never chose. The shortcuts now also
refuse while the legal gate is on screen, which matters once About can re-open it.
**The window is bounded at 1600×1100 and cannot be maximized or go fullscreen.** The layout is a
fixed sidebar plus one scrolling column; stretched across a 4K panel it is a column of text beside
a metre of empty surface. Still resizable, and `minWidth`/`minHeight` are unchanged.
**The window maximizes and snaps; the content column does not stretch.** Until 1.4.0 the window
was bounded at 1600×1100 and could not be maximized, because the layout — a fixed sidebar plus one
scrolling column — stretched across a 4K panel is a column of text beside a metre of empty surface.
That answered the right worry with the wrong control: the column now stops at `max-w-content`
(87.5rem) and centres in what is left, and the window is the user's to size. Fullscreen stays off.
**The window opens at a size that fits.** 1180×760 is taller than the work area of a 1920×1080 panel
at 150 % and of a 1366×768 laptop, so the status line and the plan panel's Confirm opened under the
taskbar. The window is created hidden and `src-tauri/src/window.rs` shrinks it to the monitor's work
area — never below `minWidth`/`minHeight`, 900×560 — centres it there, then shows it.
## 6. Component inventory (prefix `Pd`)
+4 -2
View File
@@ -1,10 +1,12 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Minimal capability set for the shell. Permissions are added per feature, never broadened preemptively (docs/SECURITY.md §2). dialog:allow-open is Code Health's project-folder picker and the manual Browse… path; dialog:allow-save is Save report. BOTH ONLY ASK FOR A PATH — no fs permission is granted, so the webview cannot read or write a single file. Save report hands its path to a Rust command that writes the two files, because a general fs:allow-write-text-file would be a write-anywhere primitive in the webview of a tool that already runs subprocesses against the user's interpreters.",
"description": "Exactly what the webview calls, and nothing preemptive (docs/SECURITY.md §2); lib.rs pins the set with a test. core:default stood here until 1.4.0: it granted some sixty core commands nothing used and not the one the legal gate's Decline needs, so Decline did nothing in the installed app. core:event:allow-listen/unlisten carry plan-, scan-, health- and audit-progress; core:window:allow-close is Decline. dialog:allow-open is Code Health's project-folder picker and Import requirements; dialog:allow-save is Save report and Export. BOTH ONLY ASK FOR A PATH — no fs permission is granted, so the webview cannot read or write a single file. Save report hands its path to a Rust command that writes the two files, because a general fs:allow-write-text-file would be a write-anywhere primitive in the webview of a tool that already runs subprocesses against the user's interpreters.",
"windows": ["main"],
"permissions": [
"core:default",
"core:event:allow-listen",
"core:event:allow-unlisten",
"core:window:allow-close",
"dialog:allow-open",
"dialog:allow-save"
]
+100 -5
View File
@@ -8,12 +8,8 @@
pub mod commands;
pub mod state;
pub mod window;
/// Run the application.
///
/// # Panics
/// Panics if Tauri cannot build the app context. That means a malformed `tauri.conf.json`, which
/// is a build-time mistake rather than a runtime condition, so there is nothing to recover to.
/// Commands that are **declared** in ARCHITECTURE §7 and `COMMANDS` but not yet implemented, each
/// with the slice that owes it.
///
@@ -78,6 +74,11 @@ fn startup_failed(e: &pipdock_core::PdError, log: &std::path::Path) {
.show();
}
/// Run the application.
///
/// # Panics
/// Panics if Tauri cannot build the app context. That means a malformed `tauri.conf.json`, which
/// is a build-time mistake rather than a runtime condition, so there is nothing to recover to.
#[cfg_attr(mobile, tauri::mobile_entry_point)]
#[allow(
clippy::expect_used,
@@ -120,6 +121,19 @@ pub fn run() {
// Already open: the one startup step that can fail for a reason the user can act on
// ran before Tauri, where its failure can reach the user.
app.manage(state);
// Created hidden (`visible: false`) so the first frame is drawn at a size that fits
// the monitor, not at one that hangs below a laptop's taskbar (U21, UI-SPEC §5).
if let Some(window) = app.get_webview_window("main") {
let config = app.config().app.windows.iter().find(|w| w.label == "main");
if let Some(config) = config
&& let Err(e) = window::place(&window, config)
{
tracing::warn!(target: "pipdock::app", error = %e, "could not fit the window");
}
if let Err(e) = window.show() {
tracing::error!(target: "pipdock::app", error = %e, "could not show the window");
}
}
Ok(())
})
.invoke_handler(tauri::generate_handler![
@@ -173,6 +187,87 @@ pub fn run() {
#[cfg(test)]
mod tests {
/// Every permission the webview holds, across every file in `capabilities/`.
fn granted() -> Vec<(String, serde_json::Value)> {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("capabilities");
let mut out = Vec::new();
for entry in std::fs::read_dir(&dir).expect("capabilities/ exists") {
let path = entry.expect("a readable entry").path();
let doc: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&path).expect("readable"))
.expect("a capability is JSON");
assert_eq!(
doc["windows"],
serde_json::json!(["main"]),
"{} must apply to the main window only",
path.display()
);
for p in doc["permissions"].as_array().expect("a permissions array") {
let id = p
.as_str()
.or_else(|| p["identifier"].as_str())
.expect("a permission names itself");
out.push((id.to_owned(), p.clone()));
}
}
out
}
#[test]
fn the_webview_is_granted_exactly_what_it_calls() {
// `core:default` granted some sixty core commands nothing called, and not the one the
// legal gate's Decline does — `core:window:allow-close` — so Decline did nothing in the
// installed app while its component test, which mocks `getCurrentWindow().close()`,
// passed. A grant is a contract no frontend test can see, so the set is pinned here:
// widening it is a decision this test makes visible, and losing one a regression it
// catches before a user does.
let mut ids: Vec<String> = granted().into_iter().map(|(id, _)| id).collect();
ids.sort();
assert_eq!(
ids,
[
// Copy full log, Copy recent log, About's addresses — write, never read.
"clipboard-manager:allow-write-text",
// plan-, scan-, health- and audit-progress.
"core:event:allow-listen",
"core:event:allow-unlisten",
// Decline on the legal gate.
"core:window:allow-close",
// Code Health's folder, Import requirements; Save report, Export.
"dialog:allow-open",
"dialog:allow-save",
// Scoped; see the next test.
"opener:allow-open-url",
]
);
}
#[test]
fn the_opener_reaches_four_hosts_and_no_more() {
// SECURITY §4: an unscoped opener is a launch-anything primitive.
let opener = granted()
.into_iter()
.find(|(id, _)| id == "opener:allow-open-url")
.map(|(_, p)| p)
.expect("the opener is granted");
let mut urls: Vec<&str> = opener["allow"]
.as_array()
.expect("the opener is scoped")
.iter()
.map(|a| a["url"].as_str().expect("each scope is a URL"))
.collect();
urls.sort_unstable();
assert_eq!(
urls,
[
"https://docs.astral.sh/*",
"https://github.com/*",
"https://osv.dev/*",
"https://poli0981.dev/*",
]
);
}
/// The handler list, read out of this file's own source.
///
/// `generate_handler!` is a macro, so there is no runtime list to inspect and no way to ask
+197
View File
@@ -0,0 +1,197 @@
//! Where the main window opens — UI-SPEC §5.
//!
//! Until 1.4.0 the window was capped at 1600×1100 and refused to maximize. That answered the wrong
//! problem: the layout reads badly stretched across a 4K panel, and the answer to that is a content
//! column with a maximum width (`max-w-content` in `App.tsx`), not a window the user cannot fill or
//! snap. And the cap never touched the opposite case, which is the one that hid controls:
//! `tauri.conf.json` asks for 1180×760 logical pixels, taller than the work area of a 1920×1080
//! panel at 150 % (about 688 under the taskbar) and of a 1366×768 laptop at 100 % — so the status
//! line and the plan panel's Confirm opened below the taskbar.
//!
//! So the window is created hidden (`visible: false`), fitted here to the work area of the monitor
//! it opened on, centred in it, and only then shown.
/// Logical pixels kept clear between the window and each edge of the work area.
const MARGIN: f64 = 16.0;
/// A rectangle in physical pixels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rect {
pub x: i32,
pub y: i32,
pub width: u32,
pub height: u32,
}
/// Where the window goes: its outer position, and the inner size to ask for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Placement {
pub x: i32,
pub y: i32,
pub inner_width: u32,
pub inner_height: u32,
}
/// Logical to physical, rounded. The inputs are window sizes from a config file and a monitor's
/// scale factor, so the result is small and positive; anything else saturates.
#[allow(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "a window dimension times a scale factor; `as` saturates, which is the wanted clamp"
)]
fn physical(logical: f64, scale: f64) -> u32 {
(logical * scale).round() as u32
}
/// The configured inner size, shrunk to fit `work` but never below the configured minimum, with
/// the outer rectangle centred in `work`.
///
/// `frame` is what the decorations add to the inner size — title bar and borders — in physical
/// pixels; `wanted` and `min` are logical, as `tauri.conf.json` states them. A work area smaller
/// than the minimum gets the minimum, pinned to the work area's top-left rather than centred off
/// its edge, because a title bar above the screen cannot be dragged back.
#[must_use]
pub fn fit(
work: Rect,
scale: f64,
frame: (u32, u32),
wanted: (f64, f64),
min: (f64, f64),
) -> Placement {
let margin = physical(MARGIN, scale);
let room_w = work.width.saturating_sub(frame.0 + 2 * margin);
let room_h = work.height.saturating_sub(frame.1 + 2 * margin);
let inner_width = physical(wanted.0, scale)
.min(room_w)
.max(physical(min.0, scale));
let inner_height = physical(wanted.1, scale)
.min(room_h)
.max(physical(min.1, scale));
let centre = |start: i32, room: u32, outer: u32| {
start.saturating_add(i32::try_from(room.saturating_sub(outer) / 2).unwrap_or(0))
};
Placement {
x: centre(work.x, work.width, inner_width + frame.0),
y: centre(work.y, work.height, inner_height + frame.1),
inner_width,
inner_height,
}
}
/// Fit `window` to its monitor's work area, per `config`.
///
/// # Errors
/// Whatever Tauri reports for a window it cannot query or move. The caller shows the window
/// regardless: at the configured size is better than not at all.
pub fn place(
window: &tauri::WebviewWindow,
config: &tauri::utils::config::WindowConfig,
) -> tauri::Result<()> {
let monitor = match window.current_monitor()? {
Some(monitor) => monitor,
None => match window.primary_monitor()? {
Some(monitor) => monitor,
None => return Ok(()),
},
};
let area = monitor.work_area();
let outer = window.outer_size()?;
let inner = window.inner_size()?;
let placement = fit(
Rect {
x: area.position.x,
y: area.position.y,
width: area.size.width,
height: area.size.height,
},
monitor.scale_factor(),
(
outer.width.saturating_sub(inner.width),
outer.height.saturating_sub(inner.height),
),
(config.width, config.height),
(
config.min_width.unwrap_or(0.0),
config.min_height.unwrap_or(0.0),
),
);
window.set_size(tauri::PhysicalSize::new(
placement.inner_width,
placement.inner_height,
))?;
window.set_position(tauri::PhysicalPosition::new(placement.x, placement.y))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
const WANTED: (f64, f64) = (1180.0, 760.0);
const MIN: (f64, f64) = (900.0, 560.0);
/// A Windows 11 title bar and resize borders at 100 %.
const FRAME: (u32, u32) = (16, 39);
fn work(width: u32, height: u32) -> Rect {
Rect {
x: 0,
y: 0,
width,
height,
}
}
#[test]
fn a_large_monitor_gets_the_configured_size_centred() {
let p = fit(work(1920, 1032), 1.0, FRAME, WANTED, MIN);
assert_eq!((p.inner_width, p.inner_height), (1180, 760));
assert_eq!((p.x, p.y), ((1920 - 1196) / 2, (1032 - 799) / 2));
}
#[test]
fn a_scaled_laptop_panel_gets_a_window_that_fits_under_its_taskbar() {
// 1920×1080 at 150 %: the work area is 1032 physical pixels tall, and 760 logical is 1140.
let frame = (24, 59);
let p = fit(work(1920, 1032), 1.5, frame, WANTED, MIN);
assert_eq!(p.inner_width, 1770, "the width fits, so it is untouched");
assert!(p.inner_height + frame.1 <= 1032, "{p:?}");
assert!(p.y >= 0, "{p:?}");
}
#[test]
fn a_small_laptop_keeps_the_whole_window_on_screen() {
let p = fit(work(1366, 728), 1.0, FRAME, WANTED, MIN);
assert!(p.inner_height + FRAME.1 <= 728, "{p:?}");
assert!(p.inner_height >= 560, "never below the minimum");
assert!(p.y >= 0);
}
#[test]
fn a_work_area_below_the_minimum_gets_the_minimum_at_its_corner() {
let p = fit(work(800, 600), 1.0, FRAME, WANTED, MIN);
assert_eq!((p.inner_width, p.inner_height), (900, 560));
assert_eq!(
(p.x, p.y),
(0, 0),
"never centred off the top of the screen"
);
}
#[test]
fn a_second_monitor_is_measured_from_its_own_origin() {
let p = fit(
Rect {
x: -1920,
y: 120,
width: 1920,
height: 1040,
},
1.0,
FRAME,
WANTED,
MIN,
);
assert!(p.x >= -1920 && p.x + 1196 <= 0, "{p:?}");
assert!(p.y >= 120, "{p:?}");
}
}
+4 -4
View File
@@ -17,16 +17,16 @@
"height": 760,
"minWidth": 900,
"minHeight": 560,
"maxWidth": 1600,
"maxHeight": 1100,
"resizable": true,
"maximizable": false,
"center": true,
"visible": false,
"fullscreen": false,
"theme": "Dark"
}
],
"security": {
"csp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'; connect-src 'self' ipc: http://ipc.localhost"
"csp": "default-src 'self'; img-src 'self' data:; style-src 'self'; font-src 'self'; connect-src 'self' ipc: http://ipc.localhost; object-src 'none'; base-uri 'none'; form-action 'none'",
"devCsp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'; connect-src 'self' ipc: http://ipc.localhost; object-src 'none'; base-uri 'none'; form-action 'none'"
}
},
"bundle": {
+7 -1
View File
@@ -3,9 +3,15 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--
The development policy. `npm run dev` serves this file as-is, and Vite injects its CSS as
<style> elements, so style-src needs 'unsafe-inline' here. A release build gets Tauri's
policy from tauri.conf.json as well, which drops it - and two policies are both enforced,
so the stricter one decides. Keep the other directives in step with tauri.conf.json.
-->
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'; connect-src 'self' ipc: http://ipc.localhost"
content="default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'; connect-src 'self' ipc: http://ipc.localhost; object-src 'none'; base-uri 'none'; form-action 'none'"
/>
<title>PipDock</title>
</head>
+37 -15
View File
@@ -14,11 +14,13 @@
* user can get there at all, and in how many clicks.
*/
import { fireEvent, render, screen, within } from '@testing-library/react'
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { App } from '@/App'
import type { DepsGraph, Dist } from '@/ipc'
import { NAV_KEYS } from '@/components/nav'
import type { DepsGraph, Dist, EnvRow } from '@/ipc'
import { joinRows } from '@/screens/rows'
import { useDepsStore, useEnvStore, useLegalStore, useUiStore } from '@/stores'
import graphFixture from '@/test/fixtures/deps_graph.json'
import listFixture from '@/test/fixtures/pkg_list.json'
@@ -57,16 +59,19 @@ const DISTS = listFixture as Dist[]
const ENV_HASH = 'abc123'
const INTERPRETER = String.raw`C:\proj\.venv\Scripts\python.exe`
const ROW = {
// Typed, so a seed the app could never produce fails to compile. This one said `source: 'venv'`,
// which is not an `EnvSource`, and lacked `hiddenUserSite`; `as never` below hid both (U10).
const ROW: EnvRow = {
interpreter: INTERPRETER,
source: 'venv' as const,
source: 'venv-scan',
envHash: ENV_HASH,
env: {
interpreter: INTERPRETER,
prefix: String.raw`C:\proj\.venv`,
pythonVersion: '3.12.10',
externallyManaged: false,
source: 'venv' as const,
hiddenUserSite: null,
source: 'venv-scan',
},
}
@@ -86,7 +91,7 @@ beforeEach(() => {
// Past the gate, and it takes both halves. The store field is what the first render reads; the
// command is what the mount effect overwrites it with.
legalConsentGet.mockReset().mockResolvedValue({ current: true, recorded: true })
legalConsentGet.mockReset().mockResolvedValue({ current: true, docsHash: 'a1b2c3d4e5f60718' })
useLegalStore.setState({ accepted: true, review: false })
useUiStore.setState({ nav: 'installed' })
useDepsStore.setState({
@@ -96,21 +101,17 @@ beforeEach(() => {
focus: null,
error: null,
})
// The rows `joinRows` builds, not a hand-made shape: the old seed had `pinned`, `state` and a
// `null` latest, none of which a `PackageRow` has.
useEnvStore.setState({
rows: [ROW],
selected: INTERPRETER,
packages: DISTS.map((d) => ({
name: d.name,
version: d.version,
latest: null,
sizeBytes: d.sizeBytes ?? null,
pinned: null,
state: 'unknown' as const,
})),
dists: DISTS,
packages: joinRows(DISTS, [], []).rows,
listing: 'ready',
outdatedStatus: 'ready',
selection: new Set<string>(),
} as never)
})
})
/** A package row by name, in the virtualized table. */
@@ -180,3 +181,24 @@ describe('the dependency view, reached the way a user reaches it', () => {
}
})
})
describe('the keyboard', () => {
it('selects a tab by the physical digit, whatever the layout types', () => {
// U49: on AZERTY, Ctrl+3 reports `"`. Parsing `e.key` made every tab shortcut a no-op there.
render(<App />)
expect(NAV_KEYS[2]).not.toBe(useUiStore.getState().nav)
fireEvent.keyDown(window, { key: '"', code: 'Digit3', ctrlKey: true })
expect(useUiStore.getState().nav).toBe(NAV_KEYS[2])
})
it('puts the cursor in the search field when `/` opens Search', async () => {
// U12: PdSearch focused its field, then the shell's own effect — parents run after children
// — moved focus to the heading, so the first keystroke after `/` went nowhere.
render(<App />)
fireEvent.keyDown(window, { key: '/', code: 'Slash' })
expect(useUiStore.getState().nav).toBe('search')
await waitFor(() => {
expect(screen.getByRole('searchbox')).toHaveFocus()
})
})
})
+49 -11
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { isBrowserShortcut } from '@/components/browserKeys'
import { NAV_KEYS } from '@/components/nav'
import { PdLegalGate } from '@/components/PdLegalGate'
import { PdOfflineBanner } from '@/components/PdOfflineBanner'
@@ -83,21 +84,45 @@ export function App() {
void checkConsent()
}, [checkConsent])
// Settings are the app's, not the Settings screen's: the status line names the engine and the
// PEP 668 chip reads the override. Loaded only when Settings mounted, so both showed the
// defaults — "pip", and no chip — until someone happened to open Settings (U13).
// Settings are the app's, not the Settings screen's: the status line names the engine, the
// PEP 668 chip reads the override, and the language is the user's. Loaded only when Settings
// mounted, so all three showed the defaults until someone opened Settings (U13) — and loaded
// before the legal gate rather than after it, so the gate is in the language they chose (U3).
const loadSettings = useSettingsStore((s) => s.load)
useEffect(() => {
if (accepted === true) void loadSettings()
}, [accepted, loadSettings])
void loadSettings()
}, [loadSettings])
// U20: a release build has no reload, print or find to offer — see `browserKeys`. Capture phase
// and above the gate's early return, so no screen and no modal can let one through.
useEffect(() => {
if (!import.meta.env.PROD) return undefined
const swallow = (e: KeyboardEvent) => {
if (isBrowserShortcut(e)) e.preventDefault()
}
window.addEventListener('keydown', swallow, { capture: true })
return () => {
window.removeEventListener('keydown', swallow, { capture: true })
}
}, [])
// UI-SPEC §8's "full keyboard traversal": after Ctrl+3 the focus was still on whatever the user
// last clicked, so the next Tab resumed in the old screen and a screen reader announced nothing.
// Moving it to the new screen's heading is the smallest thing that makes the shortcut complete.
// `key={nav}` on <main> forces a remount, so this fires on every change rather than only the
// first — and the heading takes `tabIndex={-1}` from the CSS-free `[tabindex]` below.
//
// A screen that names its own first stop with `data-autofocus` gets that instead. Search's field
// is UI-SPEC §5's first click, and PdSearch focused it — then this effect, which runs after its
// children's, moved focus to the heading on every arrival (U12).
useEffect(() => {
const heading = mainRef.current?.querySelector('h1')
const main = mainRef.current
const own = main?.querySelector<HTMLElement>('[data-autofocus]')
if (own !== null && own !== undefined) {
own.focus()
return
}
const heading = main?.querySelector('h1')
if (heading === null || heading === undefined) return
heading.setAttribute('tabindex', '-1')
heading.focus()
@@ -141,13 +166,21 @@ export function App() {
target?.tagName === 'INPUT' || target?.tagName === 'TEXTAREA' || target?.isContentEditable
if (e.key === '/' && !e.ctrlKey && !e.altKey && !e.metaKey && typing !== true) {
e.preventDefault()
setNav('search')
// Already on Search, `nav` does not change and the focus effect above does not run, so
// `/` did nothing at all from the very screen it names.
if (nav === 'search') {
mainRef.current?.querySelector<HTMLElement>('[data-autofocus]')?.focus()
} else {
setNav('search')
}
return
}
if (!e.ctrlKey || e.altKey || e.metaKey) return
const index = Number.parseInt(e.key, 10) - 1
const key = NAV_KEYS[index]
// By physical key (U49): `e.key` is what the layout types, and on AZERTY Ctrl+1 reports `&`,
// so the tab shortcuts did nothing for every French keyboard.
const digit = /^(?:Digit|Numpad)([1-9])$/.exec(e.code)?.[1]
const key = digit === undefined ? undefined : NAV_KEYS[Number(digit) - 1]
if (key !== undefined) {
e.preventDefault()
setNav(key)
@@ -157,7 +190,7 @@ export function App() {
return () => {
window.removeEventListener('keydown', onKey)
}
}, [setNav, guardOpen, planPhase, accepted, review])
}, [nav, setNav, guardOpen, planPhase, accepted, review])
// Nothing is usable before the documents are accepted, so the gate replaces the shell rather
// than overlaying a working app (UI-SPEC §4).
@@ -184,7 +217,12 @@ export function App() {
{/* Each screen owns its own scroll container. A virtualizer needs a scroll element it
can observe, and nesting one inside an already-scrolling <main> gives two scrollbars
and an outer one whose content is already the virtualizer's full height. */}
<main key={nav} ref={mainRef} className="flex min-w-0 flex-1 flex-col overflow-hidden">
{/* `mx-auto max-w-content`: the window maximizes, the column does not (UI-SPEC §5). */}
<main
key={nav}
ref={mainRef}
className="mx-auto flex min-w-0 max-w-content flex-1 flex-col overflow-hidden"
>
{PANEL_PHASES.has(planPhase) ? (
<PdPlanPanel
onFinished={(changed) => {
+2 -8
View File
@@ -9,15 +9,9 @@
* (`pipdock/no-jsx-literals`), which is the rule that keeps I18N §1 honest.
*/
export type BadgeTone = 'warn' | 'info' | 'danger' | 'accent' | 'dim'
import { BADGE_TONES as TONES, type BadgeTone } from '@/components/badgeTones'
const TONES: Record<BadgeTone, string> = {
warn: 'bg-warn/20 text-warn',
info: 'bg-info/20 text-info',
danger: 'bg-danger/20 text-danger',
accent: 'bg-accent/20 text-accent',
dim: 'border border-border text-text-dim',
}
export type { BadgeTone }
interface PdBadgeProps {
tone: BadgeTone
+2 -1
View File
@@ -146,7 +146,8 @@ export function PdConflictRow({
setConfirmingForce(false)
onChoose('force-latest')
}}
className="rounded-pd bg-danger/20 px-2 py-0.5 text-data text-danger"
// Outlined, not filled: a fill inside the confirm's own danger tint read at 4.03:1.
className="rounded-pd border border-danger px-2 py-0.5 text-data text-danger"
>
{t('plan.decision.force-latest')}
</button>
+70
View File
@@ -0,0 +1,70 @@
/**
* What *Report bug* puts in the issue — U31.
*
* The row asked `report_bug_url` for its link with no environment, so every prefilled issue said
* nothing about the Python or the engine version — the first two questions anyone answering it
* would ask. Passing the environment costs a subprocess (`pip --version`), so it is asked for when
* the user reports, not once per row mounted: a summary of a failed batch can mount dozens.
*/
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { PdErrorRow } from '@/components/PdErrorRow'
import * as ipc from '@/ipc'
import type { EnvRow, PyEnv } from '@/ipc'
import { useEnvStore } from '@/stores'
import { resetStore } from '@/test/stores'
vi.mock('@/ipc', async () => {
const { ipcMock } = await import('@/test/ipc')
return ipcMock()
})
vi.mock('@tauri-apps/plugin-opener', () => ({ openUrl: vi.fn().mockResolvedValue(undefined) }))
const { openUrl } = await import('@tauri-apps/plugin-opener')
const ENV: PyEnv = {
interpreter: 'C:/work/.venv/Scripts/python.exe',
prefix: 'C:/work/.venv',
pythonVersion: '3.12.4',
externallyManaged: false,
hiddenUserSite: null,
source: 'venv-scan',
}
const ROW: EnvRow = {
interpreter: ENV.interpreter,
source: 'venv-scan',
envHash: 'hash-work',
env: ENV,
}
describe('Report bug', () => {
beforeEach(() => {
vi.clearAllMocks()
resetStore(useEnvStore)
useEnvStore.setState({ rows: [ROW], selected: ENV.interpreter })
vi.mocked(ipc.reportBugUrl).mockResolvedValue({
url: 'https://github.com/poli0981/pipdock/issues/new',
log: '[log excerpt]',
})
})
it('does not spawn anything to render the row', async () => {
render(<PdErrorRow error={{ code: 'PD-NET-001', message: 'offline' }} />)
await screen.findByText('Report bug')
// One call, without the environment: deciding whether there is a log to offer is free.
expect(ipc.reportBugUrl).toHaveBeenCalledTimes(1)
expect(ipc.reportBugUrl).toHaveBeenCalledWith(undefined, 'PD-NET-001')
})
it('asks again with the environment when the user reports', async () => {
render(<PdErrorRow error={{ code: 'PD-NET-001', message: 'offline' }} />)
fireEvent.click(await screen.findByText('Report bug'))
await waitFor(() => {
expect(openUrl).toHaveBeenCalledTimes(1)
})
expect(ipc.reportBugUrl).toHaveBeenLastCalledWith(ENV, 'PD-NET-001')
})
})
+15 -2
View File
@@ -21,7 +21,7 @@ import { useTranslation } from 'react-i18next'
import { useOpenExternal } from '@/components/useOpenExternal'
import { reportBugUrl, type BugReportLink, type PdError } from '@/ipc'
import { useUiStore } from '@/stores'
import { useEnvStore, useUiStore } from '@/stores'
export function PdErrorRow({ error, counted = true }: { error: PdError; counted?: boolean }) {
const { t } = useTranslation()
@@ -31,6 +31,8 @@ export function PdErrorRow({ error, counted = true }: { error: PdError; counted?
const [copied, setCopied] = useState(false)
const addErrorRow = useUiStore((s) => s.addErrorRow)
const removeErrorRow = useUiStore((s) => s.removeErrorRow)
// The selected environment, for the Python and engine versions in the issue (U31).
const env = useEnvStore((s) => s.rows.find((r) => r.interpreter === s.selected)?.env)
// Registers while mounted, so `⚠ n` means "problems currently on screen" rather than a tally
// that only grows. `counted={false}` is for a sheet that renders one row per failed package —
@@ -108,7 +110,18 @@ export function PdErrorRow({ error, counted = true }: { error: PdError; counted?
<button
type="button"
onClick={() => {
openExternal(link.url)
// Asked again, with the environment, only when the user reports: the versions are
// what makes an issue answerable, and finding pip's costs a subprocess — one per
// click rather than one per row mounted, and a summary can mount dozens (U31). The
// link already in hand is the fallback, not a reason to send nothing.
void reportBugUrl(env ?? undefined, error.code).then(
(fresh) => {
openExternal(fresh.url)
},
() => {
openExternal(link.url)
},
)
}}
data-action="report-bug"
className="text-data text-text-dim underline underline-offset-2"
+8
View File
@@ -51,6 +51,14 @@ describe('PdLegalGate', () => {
expect(accept).toBeEnabled()
})
it('says so when consent cannot be recorded', () => {
// U29: the store kept the error and nothing rendered it, so Accept looked like a button
// that did nothing.
useLegalStore.setState({ error: { code: 'PD-PRM-003', message: 'read-only data folder' } })
render(<PdLegalGate />)
expect(screen.getByText('PD-PRM-003')).toBeInTheDocument()
})
it('closes the window on Decline', () => {
render(<PdLegalGate />)
fireEvent.click(screen.getByRole('button', { name: 'Decline and exit' }))
+11 -1
View File
@@ -5,7 +5,7 @@
* documents' hash, so a bump re-triggers this (`docs_hash`, computed at build time).
*
* The links are opened by Rust, not by the webview: `connect-src` in `tauri.conf.json` allows only
* `'self'` and the IPC origin, and the `opener` capability is scoped to three hosts (SECURITY §4).
* `'self'` and the IPC origin, and the `opener` capability is scoped to four hosts (SECURITY §4).
* A failure to open is shown rather than swallowed — the documents are the thing the user is being
* asked to agree to, so silently failing to show them is not acceptable. That rule is now the
* shared `useOpenExternal`, and the rest of the app follows it too.
@@ -21,6 +21,7 @@ import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { LEGAL_DOCUMENTS } from '@/components/legal'
import { PdErrorRow } from '@/components/PdErrorRow'
import { useOpenExternal } from '@/components/useOpenExternal'
import { useLegalStore } from '@/stores'
@@ -33,6 +34,9 @@ export function PdLegalGate({
} = {}) {
const { t } = useTranslation()
const accept = useLegalStore((s) => s.accept)
// U29: a consent that cannot be read or written was stored and never shown, so Accept looked
// like a button that did nothing.
const error = useLegalStore((s) => s.error)
const [checked, setChecked] = useState(false)
const { open, failed: openFailed } = useOpenExternal()
@@ -74,6 +78,12 @@ export function PdLegalGate({
<p className="mt-4 border-l-2 border-border pl-3 text-text-dim">{t('legal.summary')}</p>
{error === null ? null : (
<div className="mt-4">
<PdErrorRow error={error} />
</div>
)}
{review ? (
<div className="mt-5 flex gap-2">
<button
+48 -45
View File
@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next'
import { PdBadge } from '@/components/PdBadge'
import { PdPinChip } from '@/components/PdPinChip'
import { COLUMNS } from '@/components/packageColumns'
import { formatBytes, rowState, type LoadState, type PackageRow } from '@/screens/rows'
/** Fixed row height, in px. Mono data at one line, so the virtualizer never has to measure. */
@@ -106,7 +107,7 @@ function Row({
}
}}
style={style}
className={`absolute top-0 left-0 flex w-full items-center gap-3 border-b border-border px-3 ${
className={`absolute top-0 left-0 w-full ${COLUMNS.row} border-b border-border ${
// UI-SPEC §4: up-to-date rows are dimmed. `unknown` is deliberately not dimmed —
// see rowState.
state === 'current' ? 'text-text-dim' : 'text-text'
@@ -124,24 +125,24 @@ function Row({
aria-label={row.name}
// Not a tab stop: the row is (see onKeyDown above). Still clickable and still announced.
tabIndex={-1}
className="shrink-0 accent-accent disabled:opacity-40"
className={`${COLUMNS.checkbox} accent-accent disabled:opacity-40`}
/>
<code role="gridcell" className="min-w-0 flex-1 truncate font-mono text-data">
<code role="gridcell" className={`${COLUMNS.name} font-mono text-data`}>
{row.name}
</code>
<span role="gridcell" className="w-28 shrink-0 font-mono text-data">
<span role="gridcell" className={`${COLUMNS.version} font-mono text-data`}>
{row.version}
</span>
<span role="gridcell" className="w-28 shrink-0 font-mono text-data">
<span role="gridcell" className={`${COLUMNS.latest} font-mono text-data`}>
{/* An em dash, not "0" or a blank: latest is unknown until pkg_outdated resolves. */}
{row.latest ?? '—'}
</span>
<span role="gridcell" className="w-24 shrink-0 text-right font-mono text-data">
<span role="gridcell" className={`${COLUMNS.size} font-mono text-data`}>
{row.sizeBytes === undefined ? '—' : formatBytes(row.sizeBytes, i18n.language)}
</span>
<span role="gridcell" className="flex w-40 shrink-0 items-center gap-1">
<span role="gridcell" className={COLUMNS.status}>
{state === 'outdated' ? <PdBadge tone="warn" label={t('packages.badge.update')} /> : null}
{row.pin === undefined ? null : <PdPinChip mode={row.pin} />}
</span>
@@ -159,44 +160,46 @@ function Row({
A third inline button costs nothing instead. The row is the only tab stop (see
onKeyDown), so the controls are a roving sequence rather than tab stops — a third one
adds a left/right step, not 200 more stops. Ordered non-destructive first: details, pin,
remove. */}
<button
type="button"
tabIndex={-1}
onClick={() => {
onDetails(row.name)
}}
aria-label={t('packages.actions.details')}
title={t('packages.actions.details')}
className="shrink-0 rounded-pd border border-border px-2 py-0.5 text-data text-text-dim"
>
{'⇄'}
</button>
<button
type="button"
tabIndex={-1}
onClick={() => {
onPinToggle(row.name)
}}
aria-label={pinned ? t('packages.actions.unpin') : t('packages.actions.pin')}
title={pinned ? t('packages.actions.unpin') : t('packages.actions.pin')}
className="shrink-0 rounded-pd border border-border px-2 py-0.5 text-data text-text-dim"
>
{pinned ? '–' : '+'}
</button>
<button
type="button"
tabIndex={-1}
onClick={() => {
onUninstall(row.name)
}}
data-action="uninstall"
aria-label={t('packages.actions.uninstall')}
title={t('packages.actions.uninstall')}
className="shrink-0 rounded-pd border border-border px-2 py-0.5 text-data text-text-dim"
>
{'✕'}
</button>
remove. One cell holding all three, at the width the header reserves for them. */}
<span role="gridcell" className={COLUMNS.actions}>
<button
type="button"
tabIndex={-1}
onClick={() => {
onDetails(row.name)
}}
aria-label={t('packages.actions.details')}
title={t('packages.actions.details')}
className="shrink-0 rounded-pd border border-border px-2 py-0.5 text-data text-text-dim"
>
{'⇄'}
</button>
<button
type="button"
tabIndex={-1}
onClick={() => {
onPinToggle(row.name)
}}
aria-label={pinned ? t('packages.actions.unpin') : t('packages.actions.pin')}
title={pinned ? t('packages.actions.unpin') : t('packages.actions.pin')}
className="shrink-0 rounded-pd border border-border px-2 py-0.5 text-data text-text-dim"
>
{pinned ? '–' : '+'}
</button>
<button
type="button"
tabIndex={-1}
onClick={() => {
onUninstall(row.name)
}}
data-action="uninstall"
aria-label={t('packages.actions.uninstall')}
title={t('packages.actions.uninstall')}
className="shrink-0 rounded-pd border border-border px-2 py-0.5 text-data text-text-dim"
>
{'✕'}
</button>
</span>
</div>
)
}
+18 -10
View File
@@ -17,6 +17,7 @@ import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { PdPackageRow, ROW_HEIGHT } from '@/components/PdPackageRow'
import { COLUMNS } from '@/components/packageColumns'
import type { LoadState, PackageRow } from '@/screens/rows'
interface PdPackageTableProps {
@@ -77,7 +78,10 @@ export function PdPackageTable({
role="grid"
aria-label={t('packages.tableLabel')}
aria-rowcount={rows.length + 1}
className="flex min-h-0 flex-1 flex-col"
// Focusable but not a tab stop: the rows are (Sonar S6852, the ARIA grid pattern).
tabIndex={-1}
// `@container`: the columns size against the table's width, not the window's (U22).
className="@container flex min-h-0 flex-1 flex-col"
onKeyDown={(e) => {
// Ctrl+A selects all (UI-SPEC §8). Guarded against text inputs: none exist on these
// screens yet, but Search lands in S4 and this is the cheap moment to get it right.
@@ -89,32 +93,36 @@ export function PdPackageTable({
}
}}
>
{/* The same `COLUMNS` as every row, so the two cannot drift (U23). Outside the scroller, so
it stays put — and given the scroller's gutter, so a scrollbar appearing does not push
every cell left of its heading: `overflow-hidden` plus a stable gutter reserves the same
width a scrollbar would take. */}
<div
role="row"
aria-rowindex={1}
className="flex shrink-0 items-center gap-3 border-b border-border px-3 py-1 text-data text-text-dim"
className={`${COLUMNS.row} shrink-0 overflow-hidden border-b border-border py-1 text-data text-text-dim [scrollbar-gutter:stable]`}
>
{/* Aligns with the row checkbox, which has no header of its own. */}
<span aria-hidden="true" className="w-[13px] shrink-0" />
<span role="columnheader" className="min-w-0 flex-1">
<span aria-hidden="true" className={COLUMNS.checkbox} />
<span role="columnheader" className={COLUMNS.name}>
{t('packages.column.name')}
</span>
<span role="columnheader" className="w-28 shrink-0">
<span role="columnheader" className={COLUMNS.version}>
{t('packages.column.version')}
</span>
<span role="columnheader" className="w-28 shrink-0">
<span role="columnheader" className={COLUMNS.latest}>
{t('packages.column.latest')}
</span>
<span role="columnheader" className="w-24 shrink-0 text-right">
<span role="columnheader" className={COLUMNS.size}>
{t('packages.column.size')}
</span>
<span role="columnheader" className="w-40 shrink-0">
<span role="columnheader" className={COLUMNS.status}>
{t('packages.column.status')}
</span>
<span aria-hidden="true" className="w-8 shrink-0" />
<span aria-hidden="true" className={COLUMNS.actions} />
</div>
<div ref={scrollRef} className="min-h-0 flex-1 overflow-auto">
<div ref={scrollRef} className="min-h-0 flex-1 overflow-auto [scrollbar-gutter:stable]">
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
{virtualizer.getVirtualItems().map((item) => {
const row = rows[item.index]
+1 -1
View File
@@ -88,7 +88,7 @@ export function PdUninstallDialog({
onConfirm(true)
}}
data-action="force"
className="rounded-pd border border-danger bg-danger/20 px-3 py-1 text-data text-danger disabled:opacity-40"
className="rounded-pd border border-danger bg-danger/15 px-3 py-1 text-data text-danger disabled:opacity-40"
>
{t('uninstall.force', { count: report.removing.length })}
</button>
+21
View File
@@ -0,0 +1,21 @@
/**
* `PdBadge`'s tones, in a module of their own so `tokens.test.ts` can sweep them.
*
* A badge is text on a tint of its own colour, and the tint lowers the contrast the plain token
* has: danger on a 20 % danger tint over a selected row measured 3.92:1, under WCAG AA's 4.5, and
* no test looked at it because the token test checked tokens on plain surfaces only (U46). The
* test now composites each tint here over every surface. Danger takes a lighter tint for that
* reason, and the token itself moved from #F0574F to #F26A63.
*
* Tailwind finds these by scanning source text, so every class is written out whole.
*/
export type BadgeTone = 'warn' | 'info' | 'danger' | 'accent' | 'dim'
export const BADGE_TONES: Readonly<Record<BadgeTone, string>> = {
warn: 'bg-warn/20 text-warn',
info: 'bg-info/20 text-info',
danger: 'bg-danger/15 text-danger',
accent: 'bg-accent/20 text-accent',
dim: 'border border-border text-text-dim',
}
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest'
import { isBrowserShortcut } from '@/components/browserKeys'
const press = (key: string, code: string, mods: Partial<Record<'ctrl' | 'shift' | 'alt', boolean>> = {}) =>
isBrowserShortcut({
key,
code,
ctrlKey: mods.ctrl === true,
shiftKey: mods.shift === true,
altKey: mods.alt === true,
metaKey: false,
})
describe('the browser shortcuts a release build swallows', () => {
it.each([
['F5', 'F5', {}],
['r', 'KeyR', { ctrl: true }],
['R', 'KeyR', { ctrl: true, shift: true }],
['p', 'KeyP', { ctrl: true }],
['f', 'KeyF', { ctrl: true }],
['F3', 'F3', {}],
['ArrowLeft', 'ArrowLeft', { alt: true }],
['BrowserBack', 'BrowserBack', {}],
] as const)('%s (%s) is the browser’s', (key, code, mods) => {
expect(press(key, code, mods)).toBe(true)
})
it('finds Ctrl+R by its physical key, whatever the layout calls it', () => {
// A layout where KeyR types something else still reloads the page.
expect(press('к', 'KeyR', { ctrl: true })).toBe(true)
})
it.each([
['k', 'KeyK', { ctrl: true }],
['a', 'KeyA', { ctrl: true }],
['c', 'KeyC', { ctrl: true }],
['v', 'KeyV', { ctrl: true }],
['1', 'Digit1', { ctrl: true }],
['/', 'Slash', {}],
['r', 'KeyR', {}],
['ArrowLeft', 'ArrowLeft', {}],
['r', 'KeyR', { ctrl: true, alt: true }],
] as const)('%s (%s) is left to the app', (key, code, mods) => {
// Ctrl+K, Ctrl+A, Ctrl+1..9 and `/` are PipDock's own (UI-SPEC §8); copy and paste are the
// user's; a bare R is typing; Ctrl+Alt is AltGr on many layouts.
expect(press(key, code, mods)).toBe(false)
})
})
+35
View File
@@ -0,0 +1,35 @@
/**
* The browser's own shortcuts, which a release build has no use for — U20.
*
* WebView2 is a browser, and it kept a browser's keys: F5 and Ctrl+R reloaded the app — dropping a
* preview mid-decision along with everything the stores had not persisted — Ctrl+P printed the
* package table, Ctrl+F opened a find bar over a virtualized table whose off-screen rows do not
* exist in the DOM, and Alt+← navigated "back" from a single-page app. None of them is a PipDock
* feature, and each looked like one.
*
* Development keeps them: a reload is how a developer recovers from a bad hot update.
*/
type Keys = Pick<KeyboardEvent, 'key' | 'code' | 'ctrlKey' | 'shiftKey' | 'altKey' | 'metaKey'>
/** Physical keys whose Ctrl chord is the browser's: reload, print, find, find-next, source, save. */
const CTRL_CODES: ReadonlySet<string> = new Set(['KeyR', 'KeyP', 'KeyF', 'KeyG', 'KeyU', 'KeyS'])
/** Keys that are the browser's on their own. */
const BARE_KEYS: ReadonlySet<string> = new Set([
'F3',
'F5',
'BrowserBack',
'BrowserForward',
'BrowserRefresh',
])
export function isBrowserShortcut(e: Keys): boolean {
if (BARE_KEYS.has(e.key)) return true
if (e.altKey && !e.ctrlKey && !e.metaKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) {
return true
}
if (!e.ctrlKey || e.altKey || e.metaKey) return false
// By physical key, like the app's own shortcuts: on AZERTY, Ctrl+R is still `KeyR`.
return CTRL_CODES.has(e.code)
}
+23
View File
@@ -0,0 +1,23 @@
/**
* The package table's column widths — one definition for the header and for every row (U23).
*
* The header used to be a hand-written mirror of the row, and it had drifted: one 2rem slot stood
* above three action buttons, so every fixed column's heading sat about 76px to the right of its
* cells. And the fixed widths summed to more than the table has at the 900px minimum window, with
* the name column — `min-w-0 flex-1` — absorbing the whole deficit, so at that width it rendered
* no names at all (U22). Narrow tables therefore drop Size first and tighten the rest, by
* container query against the table's own width rather than the window's: the plan panel and a
* future split view change the one without the other.
*
* Tailwind finds these by scanning source text, so every class is written out whole.
*/
export const COLUMNS = {
row: 'flex items-center gap-2 px-3 @4xl:gap-3',
checkbox: 'w-[13px] shrink-0',
name: 'min-w-0 flex-1 truncate',
version: 'w-24 shrink-0 @4xl:w-28',
latest: 'w-24 shrink-0 @4xl:w-28',
size: 'hidden w-24 shrink-0 text-right @3xl:block',
status: 'flex w-36 min-w-0 shrink-0 items-center gap-1 overflow-hidden @4xl:w-40',
actions: 'flex w-[6.5rem] shrink-0 items-center justify-end gap-1',
} as const
+6
View File
@@ -81,6 +81,12 @@ void i18n.use(initReactI18next).init({
},
})
// The document's language follows the UI's, so a screen reader pronounces Vietnamese copy as
// Vietnamese: index.html ships `lang="en"`, and nothing changed it when the language did.
i18n.on('languageChanged', (lng) => {
if (typeof document !== 'undefined') document.documentElement.lang = resolveLocale(lng)
})
if (import.meta.env.DEV) {
i18n.addResourceBundle(
PSEUDO_LOCALE,
+19
View File
@@ -0,0 +1,19 @@
/**
* The one test for "is this a `PdError`", in a module with no Tauri import.
*
* Both stores route every rejection through it, so the `@/ipc` mock has to use the same predicate
* rather than a lookalike — it used one, which accepted `{ code: 1, message: null }`, and every
* error test agreed with itself (U10). Living here lets the mock import the real thing without
* importing `@tauri-apps/api`, which has no host to talk to under jsdom.
*/
import type { PdError } from '@/ipc'
export function isPdError(value: unknown): value is PdError {
return (
typeof value === 'object' &&
value !== null &&
typeof (value as PdError).code === 'string' &&
typeof (value as PdError).message === 'string'
)
}
+2 -8
View File
@@ -127,14 +127,8 @@ export interface PdError {
* *usually* a `PdError` — but a panic or a serialization failure arrives as something else.
* Narrowing here means no screen has to guess.
*/
export function isPdError(value: unknown): value is PdError {
return (
typeof value === 'object' &&
value !== null &&
typeof (value as PdError).code === 'string' &&
typeof (value as PdError).message === 'string'
)
}
// In a module of its own so the test mock can import the real predicate without Tauri.
export { isPdError } from '@/ipc/errors'
/** What the shell reports about itself. */
export interface AppInfo {
+1 -1
View File
@@ -55,7 +55,7 @@ function Row({ row }: { row: EnvRow }) {
<code className="font-mono text-data">{row.interpreter}</code>
<SourceChip row={row} />
{managed ? (
<span className="rounded-pd bg-danger/20 px-1.5 py-0.5 text-data text-danger">
<span className="rounded-pd bg-danger/15 px-1.5 py-0.5 text-data text-danger">
{t('env.managed')}
</span>
) : null}
+9 -2
View File
@@ -41,8 +41,15 @@ function withEnv(pins: Pin[] = PINS) {
interpreter: INTERPRETER,
envHash: 'envhash01',
source: 'manual',
env: { interpreter: INTERPRETER, pythonVersion: '3.12.4', externallyManaged: false },
} as never,
env: {
interpreter: INTERPRETER,
prefix: 'C:/proj/.venv',
pythonVersion: '3.12.4',
externallyManaged: false,
hiddenUserSite: null,
source: 'manual',
},
},
],
pins,
})
+4 -1
View File
@@ -54,7 +54,9 @@ export function PdSearch() {
const envRow = rows.find((r) => r.interpreter === envSelected)
// UI-SPEC §5: the Search flow's first click is spent arriving here, so the field must already
// have focus — "Search (autofocus) → result [Add] → Install → Confirm" is 4, not 5.
// have focus — "Search (autofocus) → result [Add] → Install → Confirm" is 4, not 5. In the app
// the shell does this, by `data-autofocus`, because its own focus effect runs after this one and
// used to move focus to the heading; this stays for the screen rendered on its own.
useEffect(() => {
field.current?.focus()
}, [])
@@ -85,6 +87,7 @@ export function PdSearch() {
<input
ref={field}
data-autofocus
type="search"
value={query}
onChange={(e) => {
+8
View File
@@ -53,6 +53,14 @@ beforeEach(() => {
})
describe('PdSecurity', () => {
it('scrolls, rather than clipping a report taller than the window', () => {
// U2: the shell's <main> clips, so a screen that does not scroll itself cannot be scrolled at
// all — and Security's root was a bare <div>.
render(<PdSecurity />)
const heading = screen.getByRole('heading', { name: 'Security' })
expect(heading.closest('.overflow-auto')).not.toBeNull()
})
it('says nothing has run when nothing has', () => {
render(<PdSecurity />)
+98 -92
View File
@@ -61,114 +61,120 @@ export function PdSecurity() {
const shown = row === undefined ? null : freshAudit({ report, reportFor }, row.envHash)
return (
<div>
<h1 tabIndex={-1} className="text-accent">
{t('nav.security')}
</h1>
// One scroll container for the report, with the console drawer pinned under it, as Health
// does. The root was a bare <div> inside a <main> that clips, so a report taller than the
// window could not be scrolled to at all (U2).
<section aria-labelledby="security-title" className="flex h-full min-h-0 flex-col">
<div className="min-h-0 flex-1 overflow-auto p-6">
<h1 id="security-title" tabIndex={-1} className="text-accent">
{t('nav.security')}
</h1>
<div className="mt-2 flex flex-wrap items-center gap-2">
<button
type="button"
data-action="run-audit"
disabled={running || env === undefined}
onClick={() => {
if (env !== undefined && row !== undefined) void run(env, row.envHash)
}}
className="rounded-pd bg-surface-2 px-3 py-1.5 text-accent disabled:opacity-40"
>
{t('security.run')}
</button>
{/* Only while a run is going. An audit is 18-68 s — long enough that a user needs a way
out, which is the measurement that changed P4's answer for Code Health. */}
{running ? (
<div className="mt-2 flex flex-wrap items-center gap-2">
<button
type="button"
data-action="cancel-audit"
data-action="run-audit"
disabled={running || env === undefined}
onClick={() => {
void cancel()
if (env !== undefined && row !== undefined) void run(env, row.envHash)
}}
className="rounded-pd bg-surface-2 px-3 py-1.5 text-text-dim"
className="rounded-pd bg-surface-2 px-3 py-1.5 text-accent disabled:opacity-40"
>
{t('actions.cancel')}
{t('security.run')}
</button>
) : null}
{shown === null ? null : (
{/* Only while a run is going. An audit is 18-68 s — long enough that a user needs a way
out, which is the measurement that changed P4's answer for Code Health. */}
{running ? (
<button
type="button"
data-action="cancel-audit"
onClick={() => {
void cancel()
}}
className="rounded-pd bg-surface-2 px-3 py-1.5 text-text-dim"
>
{t('actions.cancel')}
</button>
) : null}
{shown === null ? null : (
<button
type="button"
onClick={() => {
void pickSavePath(t('security.saveTitle'), 'security-audit.md').then((target) => {
if (target !== null) void auditSaveReport(shown, target).then(setSaved)
})
}}
className="rounded-pd bg-surface-2 px-3 py-1.5 text-text"
>
{t('security.save')}
</button>
)}
<button
type="button"
onClick={() => {
void pickSavePath(t('security.saveTitle'), 'security-audit.md').then((target) => {
if (target !== null) void auditSaveReport(shown, target).then(setSaved)
})
setConsoleOpen(!consoleOpen)
}}
className="rounded-pd bg-surface-2 px-3 py-1.5 text-text"
className="ml-auto rounded-pd px-2 py-1 text-data text-text-dim"
>
{t('security.save')}
{t('status.log')}
</button>
</div>
{/* One live region for the whole screen. Two would serialize against each other
unpredictably — the pair P6 folded for exactly this reason. */}
<p aria-live="polite" className="mt-2 text-data text-text-dim">
{running ? t('security.running') : saved === null ? '' : t('security.saved', { files: saved.join(', ') })}
</p>
{/* A run that failed outright — as opposed to a tool problem inside a report, below. */}
{error === null ? null : (
<div className="mt-2">
<PdErrorRow error={error} />
</div>
)}
<button
type="button"
onClick={() => {
setConsoleOpen(!consoleOpen)
}}
className="ml-auto rounded-pd px-2 py-1 text-data text-text-dim"
>
{t('status.log')}
</button>
</div>
{/* One live region for the whole screen. Two would serialize against each other
unpredictably — the pair P6 folded for exactly this reason. */}
<p aria-live="polite" className="mt-2 text-data text-text-dim">
{running ? t('security.running') : saved === null ? '' : t('security.saved', { files: saved.join(', ') })}
</p>
{/* A run that failed outright — as opposed to a tool problem inside a report, below. */}
{error === null ? null : (
<div className="mt-2">
<PdErrorRow error={error} />
</div>
)}
{/* pip-audit failed but the report still came back, so the advisories (if any) stay on
screen beneath this. `⚠ n` counts these rows, per UI-SPEC §3. */}
{(shown?.problems ?? []).map((problem) => (
<div key={problem.tool} className="mt-2">
<PdErrorRow error={asError(problem)} />
</div>
))}
{/* **Nothing here while a run is going.** `shown` is null then — the report is cleared before
the command so a second run cannot paint the last one's findings under a new timestamp —
and rendering the un-run empty state on that basis said *No audit has run for this
environment* while one was running. That is P4's "no issues found before anything had
run", inverted: a true-looking sentence derived from a state the screen had not loaded.
The live region above, the disabled Run and the Cancel beside it already say what is
happening, so the body says nothing rather than something false. Found by clicking Run
against a deliberately slow bridge; no test asserted on it, because every test that
renders this screen renders it settled. */}
{shown !== null ? (
<div className="mt-4">
{shown.cancelled ? (
// A cancel is a state, not an error, so it is said plainly and the partial result is
// kept rather than thrown away.
<p className="text-data text-warn">{t('security.cancelled')}</p>
) : null}
<p className="text-data text-text-dim">
{t('security.checkedAt', { at: shown.ranAt, version: shown.toolVersion })}
</p>
<div className="mt-2">
<PdAuditReport report={shown} />
{/* pip-audit failed but the report still came back, so the advisories (if any) stay on
screen beneath this. `⚠ n` counts these rows, per UI-SPEC §3. */}
{(shown?.problems ?? []).map((problem) => (
<div key={problem.tool} className="mt-2">
<PdErrorRow error={asError(problem)} />
</div>
</div>
) : running ? null : (
<PdEmptyState
message={env === undefined ? t('security.noEnv') : t('security.notRunYet')}
{...(env === undefined ? {} : { hint: t('security.notRunYetHint') })}
/>
)}
))}
{/* **Nothing here while a run is going.** `shown` is null then — the report is cleared before
the command so a second run cannot paint the last one's findings under a new timestamp —
and rendering the un-run empty state on that basis said *No audit has run for this
environment* while one was running. That is P4's "no issues found before anything had
run", inverted: a true-looking sentence derived from a state the screen had not loaded.
The live region above, the disabled Run and the Cancel beside it already say what is
happening, so the body says nothing rather than something false. Found by clicking Run
against a deliberately slow bridge; no test asserted on it, because every test that
renders this screen renders it settled. */}
{shown !== null ? (
<div className="mt-4">
{shown.cancelled ? (
// A cancel is a state, not an error, so it is said plainly and the partial result is
// kept rather than thrown away.
<p className="text-data text-warn">{t('security.cancelled')}</p>
) : null}
<p className="text-data text-text-dim">
{t('security.checkedAt', { at: shown.ranAt, version: shown.toolVersion })}
</p>
<div className="mt-2">
<PdAuditReport report={shown} />
</div>
</div>
) : running ? null : (
<PdEmptyState
message={env === undefined ? t('security.noEnv') : t('security.notRunYet')}
{...(env === undefined ? {} : { hint: t('security.notRunYetHint') })}
/>
)}
</div>
<PdConsoleDrawer
lines={lines}
@@ -179,6 +185,6 @@ export function PdSecurity() {
done={done}
total={total}
/>
</div>
</section>
)
}
+3 -4
View File
@@ -22,7 +22,7 @@ import { useSettingsStore } from '@/stores'
const ENGINES = ['pip', 'uv'] as const
export function PdSettings() {
const { t, i18n } = useTranslation()
const { t } = useTranslation()
const {
engine,
allowExternallyManaged,
@@ -87,9 +87,8 @@ export function PdSettings() {
name="locale"
checked={locale === code}
onChange={() => {
setLocale(code)
// I18N §2: applied live, not on restart.
void i18n.changeLanguage(code)
// I18N §2: applied live — and stored, so it is still the language tomorrow.
void setLocale(code)
}}
className="accent-[var(--color-accent)]"
/>
+33 -8
View File
@@ -16,7 +16,12 @@
import { create } from 'zustand'
import type { NavKey } from '@/components/nav'
import { FALLBACK_LOCALE, type Locale } from '@/i18n'
import i18n, {
FALLBACK_LOCALE,
resolveLocale,
SUPPORTED_LOCALES,
type Locale,
} from '@/i18n'
import {
envProbe,
envScan,
@@ -61,8 +66,14 @@ export function asPdError(e: unknown): PdError {
}
interface SettingsState {
/** Active UI language. */
/** Active UI language — the choice when there is one, else what the OS resolved to. */
locale: Locale
/**
* The user's explicit choice, as stored. `null` is "follow the OS", which is what a fresh
* install has, and it is kept distinct from `locale` so that saving another setting cannot pin
* the language the OS happened to resolve to (U3).
*/
localeChoice: Locale | null
/** Configured engine. First run pre-selects uv when it is on PATH (ARCHITECTURE §3). */
engine: EngineId
/**
@@ -77,11 +88,16 @@ interface SettingsState {
error: PdError | null
load: () => Promise<void>
save: (patch: Partial<Settings>) => Promise<void>
setLocale: (locale: Locale) => void
/** Choose a language: applied live (I18N §2) and stored, so it survives a restart. */
setLocale: (locale: Locale) => Promise<void>
}
const isLocale = (value: string | null | undefined): value is Locale =>
value != null && (SUPPORTED_LOCALES as readonly string[]).includes(value)
export const useSettingsStore = create<SettingsState>((set, get) => ({
locale: FALLBACK_LOCALE,
localeChoice: null,
engine: 'pip',
allowExternallyManaged: false,
// Mirrors `graph::PIN_SUGGEST_THRESHOLD`. Only on screen until `load` resolves, which is what
@@ -93,27 +109,31 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
load: async () => {
try {
const s = await settingsGet()
const choice = isLocale(s.locale) ? s.locale : null
set({
engine: s.engine,
allowExternallyManaged: s.allowExternallyManaged,
pinSuggestThreshold: s.pinSuggestThreshold,
localeChoice: choice,
locale: choice ?? resolveLocale(i18n.language),
loading: false,
error: null,
})
if (choice !== null && i18n.language !== choice) await i18n.changeLanguage(choice)
} catch (e) {
set({ loading: false, error: asPdError(e) })
}
},
save: async (patch) => {
const { engine, allowExternallyManaged, pinSuggestThreshold } = get()
const { engine, allowExternallyManaged, pinSuggestThreshold, localeChoice } = get()
const next: Settings = {
engine,
allowExternallyManaged,
pinSuggestThreshold,
// The store holds the *resolved* locale; `null` on the wire means "follow the OS", and only
// an explicit choice in Settings should overwrite that.
locale: null,
// The choice, never the resolved language: `null` on the wire means "follow the OS". This
// was a literal `null`, so every save erased a choice that nothing had stored anyway.
locale: localeChoice,
...patch,
}
try {
@@ -122,6 +142,7 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
engine: saved.engine,
allowExternallyManaged: saved.allowExternallyManaged,
pinSuggestThreshold: saved.pinSuggestThreshold,
localeChoice: isLocale(saved.locale) ? saved.locale : null,
error: null,
})
} catch (e) {
@@ -129,7 +150,11 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
}
},
setLocale: (locale) => set({ locale }),
setLocale: async (locale) => {
set({ locale, localeChoice: locale })
await i18n.changeLanguage(locale)
await get().save({ locale })
},
}))
interface EnvState {
+83
View File
@@ -0,0 +1,83 @@
/**
* The language a user chose is still their language after a restart — U3.
*
* The locale radio applied a language live and stored nothing: `save` sent `locale: null` every
* time, so choosing Vietnamese lasted until the window closed, and saving any other setting
* afterwards would have erased a choice even if one had been written. `load` ignored the stored
* value as well, and the radio started on English whatever the OS was.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import i18n from '@/i18n'
import * as ipc from '@/ipc'
import type { Settings } from '@/ipc'
import { useSettingsStore } from '@/stores'
import { resetStore } from '@/test/stores'
vi.mock('@/ipc', async () => {
const { ipcMock } = await import('@/test/ipc')
return ipcMock()
})
const STORED: Settings = {
engine: 'pip',
locale: null,
allowExternallyManaged: false,
pinSuggestThreshold: 5,
}
describe('the locale', () => {
beforeEach(async () => {
vi.clearAllMocks()
resetStore(useSettingsStore)
vi.mocked(ipc.settingsSet).mockImplementation((s: Settings) => Promise.resolve(s))
await i18n.changeLanguage('en')
})
afterEach(async () => {
await i18n.changeLanguage('en')
})
it('applies the stored choice when settings load', async () => {
vi.mocked(ipc.settingsGet).mockResolvedValue({ ...STORED, locale: 'vi' })
await useSettingsStore.getState().load()
expect(useSettingsStore.getState().locale).toBe('vi')
expect(i18n.language).toBe('vi')
})
it('follows the language already in use when nothing was chosen', async () => {
vi.mocked(ipc.settingsGet).mockResolvedValue(STORED)
await useSettingsStore.getState().load()
expect(useSettingsStore.getState().locale).toBe('en')
expect(useSettingsStore.getState().localeChoice).toBeNull()
})
it('stores a choice when one is made', async () => {
vi.mocked(ipc.settingsGet).mockResolvedValue(STORED)
await useSettingsStore.getState().load()
await useSettingsStore.getState().setLocale('vi')
expect(i18n.language).toBe('vi')
expect(ipc.settingsSet).toHaveBeenLastCalledWith(expect.objectContaining({ locale: 'vi' }))
})
it('keeps the choice when another setting is saved', async () => {
// The second half of the bug: `save` wrote `locale: null` with every other change.
vi.mocked(ipc.settingsGet).mockResolvedValue({ ...STORED, locale: 'vi' })
await useSettingsStore.getState().load()
await useSettingsStore.getState().save({ engine: 'uv' })
expect(ipc.settingsSet).toHaveBeenLastCalledWith(
expect.objectContaining({ engine: 'uv', locale: 'vi' }),
)
})
it('does not invent a choice for someone who never made one', async () => {
// `null` means "follow the OS". Writing the resolved language back would pin it.
vi.mocked(ipc.settingsGet).mockResolvedValue(STORED)
await useSettingsStore.getState().load()
await useSettingsStore.getState().save({ engine: 'uv' })
expect(ipc.settingsSet).toHaveBeenLastCalledWith(expect.objectContaining({ locale: null }))
})
})
+5 -1
View File
@@ -52,7 +52,7 @@
--color-text: #e7f0ea;
--color-text-dim: #8aa394;
--color-warn: #f5b94a;
--color-danger: #f0574f;
--color-danger: #f26a63;
--color-info: #5bc0de;
--font-sans: 'Inter', system-ui, sans-serif;
@@ -63,6 +63,10 @@
--radius-pd: 6px;
/* The content column's widest. The window may be maximized (UI-SPEC §5); the column is what
stops a table from stretching across a 4K panel. */
--container-content: 87.5rem;
/* UI-SPEC §2: motion is 120–160 ms ease-out. */
--ease-pd: cubic-bezier(0.16, 1, 0.3, 1);
}
+8 -3
View File
@@ -24,6 +24,8 @@
import { vi } from 'vitest'
import { isPdError } from '@/ipc/errors'
/** The wrappers a test can drive. Add one when a test needs it, not before. */
export interface IpcMock {
pkgList: ReturnType<typeof vi.fn>
@@ -92,6 +94,9 @@ export function ipcMock(): IpcMock {
database: { bytes: 0, path: 'C:/data/index.db', exists: false },
snapshots: { bytes: 0, path: 'C:/data/snapshots', exists: false },
tools: { bytes: 0, path: 'C:/data/tools', exists: false },
// The fourth target since the Security tab. Missing here, so any test reading it got
// `undefined` from a shape the app never sends.
audit: { bytes: 0, path: 'C:/data/audit', exists: false },
snapshotCount: 0,
}),
cacheClear: vi.fn().mockResolvedValue(0),
@@ -149,8 +154,8 @@ export function ipcMock(): IpcMock {
}),
settingsSet: vi.fn(),
// Real, not a spy: the stores decide whether a rejection carries a catalog code by asking it,
// and a stub that always answered one way would make every error test agree with itself.
isPdError: (value: unknown): boolean =>
typeof value === 'object' && value !== null && 'code' in value && 'message' in value,
// and a stub that always answered one way would make every error test agree with itself. And
// the real one, not a lookalike — the lookalike accepted `{ code: 1, message: null }`.
isPdError,
}
}
+41
View File
@@ -8,6 +8,29 @@ import {
surfaceTokens,
} from './tokens'
import { BADGE_TONES } from '@/components/badgeTones'
/** Tailwind colour names, as `BADGE_TONES` spells them, to the tokens they compile to. */
const TOKEN_OF: Record<string, keyof typeof colors> = {
warn: 'warn',
info: 'info',
danger: 'danger',
accent: 'accent',
'text-dim': 'textDim',
}
/** `fg` laid at `alpha` over `bg` — what `bg-danger/15` composites to on a surface. */
function tint(fg: string, bg: string, alpha: number): string {
const channel = (i: number) =>
Math.round(
Number.parseInt(fg.slice(1 + 2 * i, 3 + 2 * i), 16) * alpha +
Number.parseInt(bg.slice(1 + 2 * i, 3 + 2 * i), 16) * (1 - alpha),
)
.toString(16)
.padStart(2, '0')
return `#${channel(0)}${channel(1)}${channel(2)}`
}
/**
* UI-SPEC §8: "all text tokens meet WCAG AA on their surfaces (verified in the design-token
* test)". This is that test — TESTING L3 lists it as a build-time gate, so a token tweak that
@@ -37,6 +60,24 @@ describe('design tokens', () => {
expect(contrastRatio(colors.accentDim, colors.bg)).toBeGreaterThanOrEqual(AA_NORMAL)
})
it.each(Object.entries(BADGE_TONES))('the %s badge reads at AA on every surface', (tone, classes) => {
// U46: the token test checked tokens on plain surfaces, and a badge is its text on a tint of
// its own colour — danger read 3.92:1 on a selected row with nothing to say so.
const text = TOKEN_OF[/text-([a-z-]+)/.exec(classes)?.[1] ?? '']
expect(text, `${tone} names a text token`).toBeDefined()
const fill = /bg-([a-z-]+)\/(\d+)/.exec(classes)
for (const surface of surfaceTokens) {
const under =
fill === null
? colors[surface]
: tint(colors[TOKEN_OF[fill[1] ?? ''] ?? 'bg'], colors[surface], Number(fill[2]) / 100)
expect(
contrastRatio(colors[text ?? 'text'], under),
`${tone} on ${surface}`,
).toBeGreaterThanOrEqual(AA_NORMAL)
}
})
it('every foreground token clears AA large on every surface', () => {
for (const fg of foregroundTokens) {
for (const surface of surfaceTokens) {
+1 -1
View File
@@ -16,7 +16,7 @@ export const colors = {
text: '#E7F0EA',
textDim: '#8AA394',
warn: '#F5B94A',
danger: '#F0574F',
danger: '#F26A63',
info: '#5BC0DE',
} as const