Compare commits

..
2 Commits
Author SHA1 Message Date
proxyctl coordinator 30f7206b14 fix: simplify dashboard and disable unauthorized actions
hermetic-ci / test (push) Canceled after 0s
2026-08-30 15:49:04 +08:00
proxyctl coordinator 416425a9bf docs: streamline README and split detailed guides
hermetic-ci / test (push) Canceled after 0s
2026-08-30 11:35:52 +08:00
25 changed files with 430 additions and 326 deletions
+51 -88
View File
@@ -1,145 +1,108 @@
# proxyctl
`proxyctl` is a keyboard-driven Linux TUI for coordinating one **Active Profile** across independently switchable proxy **Targets**. It manages proxy configuration surfaces; it does not run a proxy server.
`proxyctl` is a keyboard-driven Linux TUI that applies one **Active Profile** to independently switchable proxy **Targets**. It configures existing system components; it does not run a proxy server.
## Supported systems
The v1 binaries target Linux on amd64 and arm64. General TUI behavior and the Shell Target are distribution-independent. The supported Target boundaries are:
Linux amd64 and arm64 are supported.
- **Shell:** Bash and Zsh only.
- **APT:** Debian-family systems with `apt-config` and `apt.conf.d`.
- **Docker daemon:** Docker installations managed by systemd.
- **Docker containers/builds:** the standard per-user Docker client `config.json` model.
- **GNOME:** sessions exposing the expected `org.gnome.system.proxy` settings schemas.
| Target | Scope |
|---|---|
| Shell | Bash and Zsh sessions |
| APT | Debian-family `apt` configuration |
| Docker daemon | systemd-managed Docker service |
| Docker containers/builds | Per-user Docker client defaults |
| GNOME | `org.gnome.system.proxy` settings |
Unavailable Targets are hidden from the main panel; `?` opens contextual, scrollable Help over the current page and includes every built-in Target and its detection evidence.
Unavailable Targets are hidden by default. Press `u` to show them and `?` for contextual help.
## Install
### Verified release binary
### Release binary
Download the binary for your architecture together with `SHA256SUMS`, then verify it before installing:
Download the binary for your architecture together with `SHA256SUMS`, then verify and install it:
```sh
grep 'proxyctl-linux-amd64$' SHA256SUMS | sha256sum -c - # substitute arm64 when needed
chmod +x proxyctl-linux-amd64 # use proxyctl-linux-arm64 on arm64
grep 'proxyctl-linux-amd64$' SHA256SUMS | sha256sum -c - # use arm64 when needed
chmod +x proxyctl-linux-amd64
install -m 0755 proxyctl-linux-amd64 "$HOME/.local/bin/proxyctl"
proxyctl version
proxyctl version --short # exact value only, for scripts
```
Release output is two single binaries, not packages or archives. The project does not publish deb, rpm, AUR, Snap, Flatpak, or similar packages.
### From source
### Install from source with Go
Go 1.24 or newer is required. From a source checkout:
Go 1.24 or newer is required:
```sh
go install ./cmd/proxyctl
```
The executable is placed in `GOBIN`, or in `$(go env GOPATH)/bin` when `GOBIN` is unset. Ensure that directory is on `PATH`. Source builds report `dev` unless a release version is injected by release automation.
## First use and Profiles
Start the Target panel with no arguments:
## Quick start
```sh
proxyctl
```
Press `m` for Proxy Profile management, then `n` to create a Profile, enter a name and proxy URL, and press Ctrl+S to save. The editor supports cursor movement, Home, End, Delete, Backspace, insertion, paste, and horizontal scrolling; Tab or the arrow keys move between fields, and Escape cancels without saving. Validation stays beside each field. The management page supports reviewing obscured connection details, editing, and safe deletion; Active Profile switching remains a separate dashboard picker workflow rather than a management action. Single mode applies one URL to HTTP, HTTPS, and ALL/SOCKS. Ctrl+T selects advanced mode for separate values without discarding values entered in either mode. A bare `host:port` is accepted and normalized to `http://`. The Single proxy URL field visibly offers Protocol Probe with Ctrl+D; it runs only on that explicit keypress, and its credential-safe progress and HTTP/SOCKS5 result stay with the initiating URL context rather than global status. When one endpoint supports both protocols, the probe switches the form to advanced mode, retains a read-only Single URL probe source row, and fills HTTP/HTTPS with `http://` and ALL/SOCKS with `socks5://`. Bypass accepts comma- or newline-delimited hostnames, domain suffixes, IPv4, IPv6, and CIDR entries; the editor previews normalized, deduplicated values and identifies invalid items before save.
1. Press `m`, then `n`, to create a Proxy Profile.
2. Enter a name and proxy URL; press Ctrl+S to save.
3. Press `p` on the dashboard to select the Active Profile.
4. Select a Target with `↑`/`↓` or `j`/`k`.
5. Press Space to enable, disable, apply, or resolve that Target.
The dashboard shows the Active Profile. Press `p` to open the searchable Active Profile picker, type to filter, use arrows to select, and press Enter to activate; Escape cancels without changing the Active Profile. Use arrows or `j`/`k` to select an Available Target and Space to run its contextual action: Enable, Disable, Apply Profile, or Resolve. Drift Resolution explicitly offers Reapply Active Profile and Restore Original; restoration refuses safely if proxyctl no longer has sufficient ownership evidence. Press `r` to refresh detection, `u` to show unavailable Targets, and `?` on any page or dialog for contextual Help. Help scrolls with arrows, `j`/`k`, Page Up/Page Down, Home, and End; `q` or Escape closes it without changing the page, focus, selection, or viewport beneath it. Applying or reapplying requires an Active Profile, while Restore Original remains available without one.
Common keys:
Escape closes the top dialog or returns one page level. `q` returns from child pages and exits only from the unobscured dashboard (in the searchable Profile picker it remains search input). Ctrl+C requests exit everywhere. If a system mutation is running, either dashboard `q` or Ctrl+C visibly defers exit until the mutation completes safely; Target browsing and Help remain available while conflicting changes are disabled.
| Key | Action |
|---|---|
| `p` | Switch Active Profile |
| `m` | Manage Profiles |
| Space | Run the selected Target action |
| `r` | Refresh Target detection |
| `u` | Show unavailable Targets |
| `?` | Contextual help |
| `q` / Esc | Back or exit |
## TUI keyboard, responsive, and accessibility behavior
The dashboard is keyboard-only. Up/Down or `j`/`k` moves within the focused region, Tab moves between the Target list and details, Page Up/Page Down scrolls long details, and the fixed footer lists the actions currently accepted. Focus always has a text marker such as `[focused]`, not color alone. Confirmation dialogs start on Cancel; Left/Right or Tab changes the choice and Enter activates it. Errors remain visible until acknowledged or directly resolved and can be expanded with `e`; progress appears both on the affected Target row and in the status area.
At 100×28 and larger, Targets and details are side by side. From 60–99 columns, the same workflow uses a single-column layout. Below 60×16, proxyctl shows only a minimum-size warning; resizing back restores the current page, selection, focus, scroll position, dialog, and in-flight operation. The TUI uses the terminal alternate screen and restores the prior shell screen after normal or safely deferred exit.
State is always communicated by a standard Unicode/ASCII-safe symbol and an explicit word (`● Enabled`, `○ Disabled`, `◇ External`, `! Drifted`, `… Checking`); no Nerd Font is required. Styling adapts to light and dark terminal backgrounds. Set `NO_COLOR` to disable color without losing state, focus, progress, warning, disabled-action, or error meaning.
Profiles are human-readable under the user's XDG configuration directory (normally `~/.config/proxyctl/profiles.json`) and are stored owner-only because proxy URLs may contain credentials.
For Profile modes, Protocol Probe, Target states, complete keyboard behavior, and accessibility details, see [docs/user-guide.md](docs/user-guide.md).
## Shell integration
A child TUI cannot change its parent Shell. Install the one-time Bash/Zsh startup hook:
A child TUI cannot modify its parent Shell. Install the Bash/Zsh startup hook once:
```sh
proxyctl shell install
```
Restart or source the startup file once. Thereafter the wrapper reloads proxy exports and unsets after `proxyctl` exits. The Shell Target emits conventional upper- and lower-case `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, and `NO_PROXY` forms. Remove the hook with:
Restart or source the startup file. Remove the hook with:
```sh
proxyctl shell uninstall
```
Fish and other Shells are intentionally unsupported in v1.
## System Targets and permissions
## What each Target affects
APT and Docker daemon changes normally require root authority. `proxyctl` never invokes `sudo`, `pkexec`, or another elevation mechanism itself. Start it explicitly with `sudo proxyctl` when system Targets are required.
1. **Shell** — commands started by integrated Bash/Zsh sessions. It does not change existing processes, system services, Docker, or desktop settings.
2. **APT** — persistent APT package operations across Shell and privilege boundaries through a tool-owned `apt.conf.d` overlay. It does not configure other package managers and requires no service restart.
3. **Docker daemon** — daemon operations such as registry access. It does not set container networking or container/build defaults. Every change reloads systemd and immediately restarts Docker; confirm only when disruption to running work is acceptable.
4. **Docker containers/builds** — proxy variables and build arguments for future containers and builds via the owning user's Docker client configuration. It does not affect existing containers, the Docker CLI connection, or the daemon.
5. **GNOME** — GNOME system proxy settings used by compatible desktop applications. It does not rewrite browser-specific profiles or configure non-GNOME desktops. GNOME settings cannot express `socks5h` remote-DNS semantics, and the Protocol Probe fills `socks5h` for SOCKS-only endpoints; switch to advanced mode and enter `socks5` when a SOCKS endpoint must work through the GNOME Target.
Docker daemon changes reload systemd and restart Docker. Review the confirmation before proceeding.
proxyctl prefers isolated, tool-owned overlays. Where that is impossible it records original values and a last-applied fingerprint so disable/reset can restore prior state safely.
## Target states
- **Enabled:** actual managed configuration matches the Active Profile.
- **Disabled:** no managed or positively recognized external proxy configuration was detected.
- **External:** a recognized proxy configuration exists but is not owned by proxyctl.
- **Drifted:** managed configuration exists but no longer matches the Active Profile, including partial failures or configuration left when the final Profile is deleted.
External detection is best-effort; Disabled does not claim that every possible configuration source was exhaustively searched.
## Permissions, sudo, and restarts
User Targets normally need only user-file permissions. APT and Docker daemon files generally require authority to write system locations, and Docker daemon operations require authority to reload/restart its systemd service.
proxyctl **never** runs `sudo`, `pkexec`, or another elevation mechanism. Permission failures are reported normally. If system Targets are wanted, the user must explicitly start `sudo proxyctl`; under sudo, the invoking user remains the owner of Profiles, Shell, Docker client, and GNOME configuration while current root authority is available to system Targets. In a direct root login, root is the owner. Review the Docker restart warning before confirming any daemon change.
See [docs/security.md](docs/security.md) for privilege boundaries, credential handling, restoration guarantees, and project scope.
## Diagnose, reset, and remove
Run read-only diagnostics for Profile validity, storage permissions, required commands, Target availability/state, and Target-specific authority:
```sh
proxyctl doctor
proxyctl doctor # read-only diagnostics
proxyctl reset # restore managed Targets
proxyctl shell uninstall # remove Shell startup integration
```
Before removal, restore every managed Target. The command asks for confirmation and does nothing when declined:
Complete a successful reset before deleting recovery state or uninstalling the executable.
```sh
proxyctl reset
proxyctl shell uninstall
```
## Privacy
Inspect failures and rerun until reset reports no failed managed Target. Then remove the installed executable and, after retaining any desired logs, remove empty proxyctl configuration/state directories. Do not delete recovery state before a successful reset because it may be needed to restore original settings.
proxyctl has no telemetry, automatic update checks, or automatic proxy-connectivity tests. Network traffic is generated only by the user-initiated Protocol Probe. Diagnostic output and logs redact credentials; stored Profile and Target configuration can still contain credentials and is protected with restrictive file permissions.
## Privacy and safety boundaries
## Documentation
proxyctl has no telemetry, automatic update checks, or automatic proxy-connectivity tests. It does not contact the network on its own; the only network traffic it generates is the user-initiated Protocol Probe (Ctrl+D in the Profile form), a handshake check that never forwards traffic through the proxy and never contacts anything beyond the endpoint itself. Local diagnostic logs are credential-redacted and bounded in size. Every TUI frame defensively redacts credentials from Profile values, Target evidence, progress, notices, errors and command output, and confirmation copy immediately before rendering, including malformed credential-bearing URLs. Profile form frames mask the entire URL userinfo while retaining the underlying value for saving. Proxy credentials remain present where a selected Target requires them, so normal local file security still matters.
proxyctl does **not** manage or supervise proxy processes such as Clash, sing-box, or Xray. It does not manage subscriptions, nodes, latency, routing rules, transparent proxying, TUN/iptables/nftables, arbitrary services or commands, plugins, or a complete headless Profile/Target CLI.
Deferred integrations include DNF, Git-specific settings, npm/pip, arbitrary systemd services, Firefox policies, Chromium launch flags, KDE and other desktops, Snap/Ubuntu Core, Fish, Windows, macOS, distribution packages, mouse interaction, and cross-Target rollback. Conventional Shell variables may already cover some deferred command-line tools.
Support is limited to the Linux architectures and Target boundaries above. When reporting an issue, include `proxyctl version`, redacted `proxyctl doctor` output, distribution/desktop/Shell details, and the affected Target/state. Never include unredacted proxy credentials.
## Build and verification
Create reproducible Linux binaries and checksums without packages or archives:
```sh
VERSION=v1.0.0 ./scripts/build-release.sh
sha256sum -c dist/SHA256SUMS
file dist/proxyctl-linux-amd64 dist/proxyctl-linux-arm64
```
`./scripts/test-release.sh` builds twice, compares binaries and checksum manifests, verifies both checksums, and checks ELF architectures. `./scripts/verify-clean-machine.sh` uses an isolated identity and XDG roots to exercise `go install`, Profile and hermetic Target workflows, doctor, reset cancellation, Shell install/uninstall, removal, and unchanged host-state snapshots.
- [User guide](docs/user-guide.md)
- [Security and operational boundaries](docs/security.md)
- [Development and release verification](docs/development.md)
- [Product specifications](docs/specs/)
- [Linux Target research](docs/research/linux-proxy-targets.md)
+2 -2
View File
@@ -97,8 +97,8 @@ func TestDefaultInvocationLoadsPersistedActiveProfile(t *testing.T) {
if err := runWithSystemTargets(nil, strings.NewReader("q"), &output, []target.Target{}); err != nil {
t.Fatalf("run proxyctl: %v", err)
}
if !strings.Contains(output.String(), "Active Profile: office") {
t.Fatalf("default TUI output missing Active Profile: %q", output.String())
if !strings.Contains(output.String(), "Profile: office") {
t.Fatalf("default TUI output missing Profile: %q", output.String())
}
}
+5 -7
View File
@@ -247,19 +247,17 @@ func TestCommandsRunAsRealProcessesInsideIsolatedUserState(t *testing.T) {
}
defaultView := string(defaultOutput)
for _, expected := range []string{
"proxyctl Operations Console",
"Active Profile: No Active Profile",
"Targets: ● Enabled 0 ○ Disabled 1 ◇ External 0 ! Drifted 1",
"proxyctl Profile: No Active Profile",
"▶ Targets [focused]",
"> ○ Disabled Shell",
"! Drifted Docker daemon",
"Target details",
"State: ○ Disabled",
"Evidence: no recognized Shell proxy configuration detected",
"Tab: focus details",
"○ Disabled",
"no recognized Shell proxy configuration detected",
"Tab: Details",
} {
if !strings.Contains(defaultView, expected) {
t.Errorf("default Operations Console missing %q; output=%q", expected, defaultOutput)
t.Errorf("default dashboard missing %q; output=%q", expected, defaultOutput)
}
}
versionOutput, err := invoke("", "version", "--short")
+36
View File
@@ -0,0 +1,36 @@
# Development and release verification
## Requirements
- Go 1.24 or newer
- Linux
- GNU `sha256sum`, `stat`, and `find`
- `file`
## Local verification
```sh
gofmt -w .
go test ./...
go vet ./...
./scripts/check-docs.sh
./scripts/test-hermetic.sh
./scripts/test-release.sh
./scripts/verify-clean-machine.sh
```
`test-hermetic.sh` runs the complete uncached Go suite as an unprivileged user and verifies that readable host configuration content and metadata remain unchanged.
`verify-clean-machine.sh` uses isolated identity and XDG roots to exercise installation, Profile workflows, hermetic Target workflows, diagnostics, reset confirmation, Shell integration, and removal.
## Release build
```sh
VERSION=v1.0.0 ./scripts/build-release.sh
sha256sum -c dist/SHA256SUMS
file dist/proxyctl-linux-amd64 dist/proxyctl-linux-arm64
```
The release consists of Linux amd64 and arm64 single binaries plus `SHA256SUMS`; it does not produce distribution packages or archives.
`test-release.sh` builds twice, compares binaries and checksum manifests, validates both architectures and checksums, and verifies that process-test seams cannot enter a release artifact.
+54
View File
@@ -0,0 +1,54 @@
# Security and operational boundaries
## Privileges
User Targets normally require only access to user-owned files. APT and Docker daemon configuration generally require root authority.
proxyctl never starts `sudo`, `pkexec`, or another elevation mechanism. Run `sudo proxyctl` explicitly when system Targets are needed. Under sudo, the invoking user remains the owner of Profiles, Shell integration, Docker client configuration, and GNOME settings; root authority is used for system Targets. A direct root login uses root as the owner.
Docker daemon changes reload systemd and restart Docker immediately after confirmation.
## Configuration recovery
proxyctl prefers isolated, tool-owned overlays. Where shared configuration must be edited, it records the original value and a fingerprint of the last applied state.
Restore and reset operations refuse to overwrite configuration that changed after proxyctl applied it. Recovery metadata must not be deleted before a successful reset.
Use:
```sh
proxyctl doctor
proxyctl reset
proxyctl shell uninstall
```
Inspect and resolve all failures before removing the executable or state directory.
## Credentials and privacy
Proxy URLs may contain credentials. Profile, recovery, and managed credential-bearing files use restrictive permissions. Docker daemon configuration is owner-only while proxyctl manages credential-bearing proxy values.
The TUI, diagnostics, errors, command output, and bounded local operation logs defensively redact credentials. Profile editor frames obscure URL user information. Credentials remain present in underlying configuration where a selected Target requires them, so host file security still matters.
proxyctl has:
- no telemetry
- no automatic update checks
- no automatic proxy-connectivity tests
The user-initiated Protocol Probe contacts only the entered endpoint, performs protocol handshakes, and never forwards traffic through the proxy.
## Scope
proxyctl configures proxy settings; it does **not** manage or supervise proxy processes such as Clash, sing-box, or Xray. It does not manage subscriptions, nodes, latency, routing rules, transparent proxying, TUN/iptables/nftables, arbitrary services, or plugins.
It currently excludes DNF, Git-specific settings, npm/pip settings, arbitrary systemd services, browser policies, KDE, Fish, Windows, macOS, distribution packages, mouse interaction, and cross-Target rollback.
Support is limited to the Linux architectures and Targets documented in the README. When reporting an issue, include:
- `proxyctl version`
- redacted `proxyctl doctor` output
- distribution and desktop/Shell details
- affected Target and state
Never include unredacted proxy credentials.
+75
View File
@@ -0,0 +1,75 @@
# User guide
## Profiles
A Proxy Profile contains proxy URLs and bypass rules. The Active Profile is the source applied to every Enabled Target.
Open Profile management with `m`:
- `n`: create a Profile
- `e` or Enter: edit the selected Profile
- `d`: safely delete the selected Profile
- Ctrl+S: save the editor
- Ctrl+T: switch between Single and Advanced modes
Single mode applies one URL to HTTP, HTTPS, and ALL/SOCKS. Advanced mode accepts separate values. A bare `host:port` is normalized to `http://`.
Bypass entries may be comma- or newline-delimited hostnames, domain suffixes, IPv4/IPv6 addresses, or CIDR ranges. The editor normalizes and deduplicates valid entries.
### Protocol Probe
Press Ctrl+D while editing the Single proxy URL to run an explicit handshake probe. It reports HTTP and SOCKS5 support without forwarding traffic or contacting another endpoint.
If both protocols are detected, the editor changes to Advanced mode and fills HTTP/HTTPS with `http://` and ALL/SOCKS with `socks5://`. GNOME cannot represent `socks5h` remote-DNS semantics; use Advanced mode with `socks5` when GNOME must use that endpoint.
## Dashboard
Press `p` to search and select the Active Profile. Select Targets with arrows or `j`/`k`; Space runs the contextual action:
- **Enable** a Disabled Target
- **Disable** an Enabled Target
- **Apply Profile** to an External Target
- **Resolve** a Drifted Target by reapplying the Active Profile or restoring the original configuration
Restoration refuses to overwrite configuration that changed after proxyctl applied it.
Other controls:
- `r`: refresh detection
- `u`: show unavailable Targets
- Tab: switch between Target list and details
- Page Up/Page Down: scroll details
- `e`: expand or collapse the current error
- `x`: acknowledge the current error
- `?`: contextual Help
- `q` or Esc: close the current page/dialog; `q` exits from the unobscured dashboard
- Ctrl+C: request exit
Conflicting actions are disabled while a mutation runs. Exit requests cancel cancellable work and wait for the operation to settle safely.
## Target states
- **Enabled:** managed configuration matches the Active Profile.
- **Disabled:** no managed or positively recognized external proxy configuration was detected.
- **External:** recognized proxy configuration exists outside proxyctl ownership.
- **Drifted:** managed configuration no longer matches the Active Profile, including partial failures.
External detection is best-effort. Disabled does not claim that every possible configuration source was exhaustively searched.
## What each Target affects
1. **Shell** — future commands in integrated Bash/Zsh sessions. It does not change existing processes or services.
2. **APT** — persistent Debian-family package operations through a tool-owned `apt.conf.d` overlay.
3. **Docker daemon** — registry and daemon traffic. Every change reloads systemd and restarts Docker.
4. **Docker containers/builds** — proxy defaults for future containers and builds in the owning user's Docker client configuration. It does not configure the daemon.
5. **GNOME** — compatible desktop applications using GNOME system proxy settings. It does not rewrite browser-specific profiles.
## Responsive and accessible TUI
At 100×28 and larger, Targets and details are side by side. At 60–99 columns they use one column. Below 60×16, proxyctl displays a minimum-size warning and restores interaction state after resize.
Focus and state never rely on color alone. States include symbols and words such as `● Enabled`, `○ Disabled`, `◇ External`, `! Drifted`, and `… Checking`. No Nerd Font is required. Set `NO_COLOR` to disable color.
Confirmation dialogs start on Cancel. The TUI uses the terminal alternate screen and restores the previous screen after exit.
Profiles are normally stored at `~/.config/proxyctl/profiles.json` with owner-only permissions.
+47 -16
View File
@@ -164,6 +164,7 @@ type Application struct {
targetDescriptions []target.Description
availabilities map[string]target.Availability
inspections map[string]target.Inspection
mutationBlockReasons map[string]string
detectionPhase map[string]TargetDetectionPhase
detectionErr map[string]error
detectionGeneration uint64
@@ -197,15 +198,16 @@ func NewWithTargetsAndRuntime(store profile.Store, targets []target.Target, muta
return nil, err
}
a := &Application{
store: store,
state: state,
targets: append([]target.Target(nil), targets...),
availabilities: make(map[string]target.Availability),
inspections: make(map[string]target.Inspection),
detectionPhase: make(map[string]TargetDetectionPhase),
detectionErr: make(map[string]error),
mutationLock: mutationLock,
logger: logger,
store: store,
state: state,
targets: append([]target.Target(nil), targets...),
availabilities: make(map[string]target.Availability),
inspections: make(map[string]target.Inspection),
mutationBlockReasons: make(map[string]string),
detectionPhase: make(map[string]TargetDetectionPhase),
detectionErr: make(map[string]error),
mutationLock: mutationLock,
logger: logger,
}
for _, adapter := range a.targets {
id := adapter.ID()
@@ -229,7 +231,7 @@ func (a *Application) snapshotLocked() Snapshot {
availability := a.availabilities[id]
inspection := a.inspections[id]
phase := a.detectionPhase[id]
primary, resolution := contextualTargetActions(phase, availability.Available, inspection.State, state.ActiveProfile != "")
primary, resolution := contextualTargetActions(phase, availability.Available, inspection.State, state.ActiveProfile != "", a.mutationBlockReasons[id])
snapshot.Targets = append(snapshot.Targets, TargetSnapshot{
ID: id, Description: a.targetDescriptions[i], DetectionPhase: phase, DetectionErr: a.detectionErr[id],
Available: availability.Available, AvailabilityEvidence: availability.Evidence, State: inspection.State, Evidence: inspection.Evidence,
@@ -239,7 +241,7 @@ func (a *Application) snapshotLocked() Snapshot {
return snapshot
}
func contextualTargetActions(phase TargetDetectionPhase, available bool, state target.State, hasActiveProfile bool) (TargetAction, []TargetAction) {
func contextualTargetActions(phase TargetDetectionPhase, available bool, state target.State, hasActiveProfile bool, mutationBlockReason string) (TargetAction, []TargetAction) {
primaryKind := primaryTargetActionKind(state)
primary := TargetAction{Kind: primaryKind, Available: primaryKind != 0}
if primaryKind == 0 {
@@ -253,6 +255,10 @@ func contextualTargetActions(phase TargetDetectionPhase, available bool, state t
primary.Available = false
primary.DisabledReason = "This action is unavailable because there is no Active Profile; open Profile management first"
}
if primary.Available && mutationBlockReason != "" {
primary.Available = false
primary.DisabledReason = mutationBlockReason
}
if state != target.Drifted {
return primary, nil
}
@@ -271,6 +277,10 @@ func contextualTargetActions(phase TargetDetectionPhase, available bool, state t
action.Available = false
action.DisabledReason = reason
}
if action.Available && mutationBlockReason != "" {
action.Available = false
action.DisabledReason = mutationBlockReason
}
resolution = append(resolution, action)
}
return primary, resolution
@@ -300,8 +310,9 @@ func targetActionDisabledReason(phase TargetDetectionPhase, available bool) stri
}
type targetDetectionOutcome struct {
targetID string
detection target.Detection
targetID string
detection target.Detection
mutationBlockReason string
}
type targetDetectionUpdate struct {
@@ -327,7 +338,10 @@ func (a *Application) beginTargetDetection(ctx context.Context) (Snapshot, <-cha
for i, adapter := range a.targets {
adapter, id := adapter, a.targetIDs[i]
go func() {
outcomes <- targetDetectionOutcome{targetID: id, detection: detectTarget(ctx, adapter, active)}
outcomes <- targetDetectionOutcome{
targetID: id, detection: detectTarget(ctx, adapter, active),
mutationBlockReason: mutationBlockReason(ctx, adapter),
}
}()
}
go func() {
@@ -345,6 +359,7 @@ func (a *Application) beginTargetDetection(ctx context.Context) (Snapshot, <-cha
}
a.availabilities[outcome.targetID] = outcome.detection.Availability
a.inspections[outcome.targetID] = outcome.detection.Inspection
a.mutationBlockReasons[outcome.targetID] = outcome.mutationBlockReason
a.detectionPhase[outcome.targetID] = phase
a.detectionErr[outcome.targetID] = outcome.detection.Err
update := targetDetectionUpdate{snapshot: a.snapshotLocked(), targetID: outcome.targetID}
@@ -372,6 +387,21 @@ func detectTarget(ctx context.Context, adapter target.Target, active *profile.Pr
}
}
func mutationBlockReason(ctx context.Context, adapter target.Target) string {
authorizer, ok := adapter.(target.MutationAuthorizer)
if !ok {
return ""
}
check := authorizer.MutationAuthority(ctx)
if check.OK {
return ""
}
if check.Evidence == "" {
return "The current process does not have authority to change this Target"
}
return check.Evidence
}
func (a *Application) Dispatch(intent Intent) Result {
ctx, cancel := context.WithTimeout(context.Background(), operationTimeout)
defer cancel()
@@ -642,12 +672,13 @@ func (a *Application) replaceInspection(id string, inspection target.Inspection)
// publishTargetDetection atomically replaces all availability, inspection, and
// failure fields from one targeted check. Detect runs before this method, so no
// Application state mutex is held while adapter code executes.
func (a *Application) publishTargetDetection(id string, detection target.Detection) Snapshot {
func (a *Application) publishTargetDetection(id string, detection target.Detection, mutationBlockReason string) Snapshot {
a.stateMu.Lock()
defer a.stateMu.Unlock()
a.detectionGeneration++
a.availabilities[id] = detection.Availability
a.inspections[id] = detection.Inspection
a.mutationBlockReasons[id] = mutationBlockReason
a.detectionErr[id] = detection.Err
a.detectionPhase[id] = TargetReady
if detection.Err != nil {
@@ -806,7 +837,7 @@ func (a *Application) setTargetDesired(ctx context.Context, intent Intent, publi
// before action validation. Adapter calls happen without stateMu; the full
// outcome is then published under one lock before policy is derived.
detection := detectTarget(ctx, selected, active)
snapshot := a.publishTargetDetection(intent.TargetID, detection)
snapshot := a.publishTargetDetection(intent.TargetID, detection, mutationBlockReason(ctx, selected))
selectedSnapshot := snapshot.Targets[selectedIndex]
policy, err := validateTargetAction(intent, selectedSnapshot)
if err != nil {
+29
View File
@@ -103,6 +103,35 @@ func TestApplicationRequiresTargetConfirmationBeforeMutation(t *testing.T) {
}
}
type authorityTarget struct {
*fakeTarget
allowed bool
reason string
}
func (t *authorityTarget) MutationAuthority(context.Context) target.Check {
return target.Check{Name: "mutation authority", OK: t.allowed, Evidence: t.reason}
}
func TestApplicationDisablesMutationWhenCurrentProcessLacksAuthority(t *testing.T) {
adapter := &authorityTarget{fakeTarget: &fakeTarget{available: true, state: target.Disabled}, reason: "requires elevated authority"}
application, err := app.NewWithTargets(profile.NewFileStore(filepath.Join(t.TempDir(), "profiles.json")), []target.Target{adapter})
if err != nil {
t.Fatal(err)
}
createAndActivate(t, application)
refreshApplicationTargets(t, application)
snapshot := application.Snapshot()
if snapshot.Targets[0].PrimaryAction.Available || snapshot.Targets[0].PrimaryAction.DisabledReason != adapter.reason {
t.Fatalf("authority policy = %#v", snapshot.Targets[0].PrimaryAction)
}
result := application.Dispatch(app.Intent{Kind: app.EnableTarget, TargetID: adapter.ID()})
if result.Err == nil || !strings.Contains(result.Err.Error(), adapter.reason) || len(adapter.calls) != 0 {
t.Fatalf("blocked mutation result = %#v calls=%v", result, adapter.calls)
}
}
type targetWithID struct {
*fakeTarget
id string
+8
View File
@@ -130,6 +130,14 @@ func (a *Adapter) Confirmation(bool) string { return "" }
// DiagnosticChecks observes the APT command, configuration schema, and current
// filesystem authority without changing the overlay or effective settings.
func (a *Adapter) MutationAuthority(context.Context) target.Check {
check := target.ReadOnlyWriteAuthority(a.configuration.OverlayFile)
if !check.OK {
check.Evidence += "; run proxyctl with sufficient authority (normally sudo proxyctl)"
}
return check
}
func (a *Adapter) DiagnosticChecks(ctx context.Context, _ *profile.Profile) []target.Check {
commandCheck := target.Check{Name: "required command", OK: true, Evidence: "apt-config is available"}
command, err := a.runner.LookPath("apt-config")
+9
View File
@@ -132,6 +132,15 @@ func (a *Adapter) Confirmation(bool) string {
// DiagnosticChecks performs only systemctl show and filesystem reads/metadata
// probes; service reload/restart and all configuration mutations are excluded.
func (a *Adapter) MutationAuthority(context.Context) target.Check {
if a.authority.EffectiveUID() != 0 {
return target.Check{Name: "mutation authority", Evidence: "Docker daemon changes require root authority; restart with sudo proxyctl"}
}
check := target.ReadOnlyWriteAuthority(a.configuration.DaemonConfigPath, a.configuration.RecoveryPath)
check.Name = "mutation authority"
return check
}
func (a *Adapter) DiagnosticChecks(ctx context.Context, _ *profile.Profile) []target.Check {
commandCheck := target.Check{Name: "required command and service", OK: true, Evidence: "systemctl can inspect the loaded docker.service"}
if availability, err := a.detect(ctx); err != nil || !availability.Available {
+6
View File
@@ -78,6 +78,12 @@ type Diagnosable interface {
DiagnosticChecks(context.Context, *profile.Profile) []Check
}
// MutationAuthorizer optionally explains why a detected Target cannot be
// changed by the current process. It is read-only and presentation-independent.
type MutationAuthorizer interface {
MutationAuthority(context.Context) Check
}
// Target hides platform paths and commands from the application and TUI.
type Target interface {
ID() string
+2 -2
View File
@@ -180,7 +180,7 @@ func TestCompleteModelPickerConfirmedActivationContinuesThroughUnifiedOperation(
completion <- app.SucceededOperationUpdate(completed, app.OperationStatus{Summary: `Activated Profile "new"`}, nil)
close(completion)
model, _ = applyOperationCommand(t, model, command)
if view := model.View(); !strings.Contains(view, "Active Profile: new") || !strings.Contains(view, `Activated Profile "new"`) {
if view := model.View(); !strings.Contains(view, "Profile: new") || !strings.Contains(view, `Activated Profile "new"`) {
t.Fatalf("confirmed activation did not finish on the dashboard:\n%s", view)
}
}
@@ -213,7 +213,7 @@ func TestCompleteModelPickerPartialFailureKeepsProgressClosesPickerAndFocusesFai
close(updates)
model, _ = applyOperationCommand(t, model, command)
view := model.View()
if model.selectedTargetID != "docker" || !strings.Contains(view, "> ! Drifted ! Failed Docker daemon") || !strings.Contains(view, "Current error: Activated Profile new with 1 Target update failure") || !strings.Contains(view, "Active Profile: new") {
if model.selectedTargetID != "docker" || !strings.Contains(view, "> ! Drifted ! Failed Docker daemon") || !strings.Contains(view, "Current error: Activated Profile new with 1 Target update failure") || !strings.Contains(view, "Profile: new") {
t.Fatalf("partial failure was not retained and focused: selected=%q\n%s", model.selectedTargetID, view)
}
}
+3 -6
View File
@@ -35,12 +35,9 @@ func TestCompleteModelRendersAndDispatchesContextualPrimaryActions(t *testing.T)
module := &targetModule{snapshot: initial, result: app.Result{Snapshot: initial, Notice: "done"}}
model := resizedModel(t, module, themeModeNoColor, 120, 36)
view := model.View()
if !strings.Contains(view, "Action: "+test.label) || !strings.Contains(view, "Space: "+test.label) {
if !strings.Contains(view, "Space: "+test.label) {
t.Fatalf("contextual action not rendered:\n%s", view)
}
if test.state == target.External && (!strings.Contains(view, "proxyctl will begin managing this configuration") || !strings.Contains(view, "while preserving restorable state")) {
t.Fatalf("Apply Profile ownership explanation missing:\n%s", view)
}
updated, command := model.Update(tea.KeyMsg{Type: tea.KeySpace})
model = updated.(Model)
@@ -91,7 +88,7 @@ func TestCompleteModelRendersUnknownTargetStateAsStructurallyUnavailable(t *test
model := resizedModel(t, module, themeModeNoColor, 120, 36)
view := model.View()
if !strings.Contains(view, "Action: Unavailable") || !strings.Contains(view, "Action unavailable:") || !strings.Contains(view, "state is unknown") || !strings.Contains(view, "Space: Unavailable disabled") {
if !strings.Contains(view, "Unavailable:") || !strings.Contains(view, "Target actions are unavailable") || !strings.Contains(view, "unknown") || !strings.Contains(view, "Space: Unavailable unavailable") {
t.Fatalf("unknown Target action was not structurally unavailable:\n%s", view)
}
updated, command := model.Update(tea.KeyMsg{Type: tea.KeySpace})
@@ -108,7 +105,7 @@ func TestCompleteModelUsesStructuredDisabledReasonWithoutInferringFromState(t *t
module := &targetModule{snapshot: initial}
model := resizedModel(t, module, themeModeNoColor, 120, 36)
view := model.View()
if !strings.Contains(view, "No Active Profile is selected") || !strings.Contains(view, "Space: Enable disabled") {
if !strings.Contains(view, "No Active Profile is selected") || !strings.Contains(view, "Space: Enable unavailable") {
t.Fatalf("structured disabled reason missing:\n%s", view)
}
updated, command := model.Update(tea.KeyMsg{Type: tea.KeySpace})
+1 -41
View File
@@ -1,9 +1,6 @@
package tui
import (
"proxyctl/internal/app"
"proxyctl/internal/target"
)
import "proxyctl/internal/app"
func targetActionLabel(kind app.TargetActionKind) string {
switch kind {
@@ -101,40 +98,3 @@ func (c targetCatalog) retain(id string, formerIndex int) string {
}
return c.items[max(0, min(len(c.items)-1, formerIndex))].ID
}
type targetStateCounts struct {
enabled int
disabled int
external int
drifted int
checking int
failed int
}
func countAvailableTargetStates(snapshot app.Snapshot) targetStateCounts {
var counts targetStateCounts
for _, item := range snapshot.Targets {
switch item.DetectionPhase {
case app.TargetChecking:
counts.checking++
continue
case app.TargetDetectionFailed:
counts.failed++
continue
}
if !item.Available {
continue
}
switch item.State {
case target.Enabled:
counts.enabled++
case target.Disabled:
counts.disabled++
case target.External:
counts.external++
case target.Drifted:
counts.drifted++
}
}
return counts
}
+10 -15
View File
@@ -23,9 +23,8 @@ func TestCompleteModelWideOperationsConsoleShowsStableAvailableTargetDashboard(t
view := resizedModel(t, module, themeModeNoColor, 120, 36).View()
assertUsableFrame(t, view, 120, 36,
"proxyctl", "Active Profile: office",
"● Enabled 1", "○ Disabled 1", "◇ External 1", "! Drifted 1",
"> ● Enabled", "Shell", "State: ● Enabled", "Evidence: matches Active Profile",
"proxyctl", "Profile: office",
"> ● Enabled", "Shell", "matches Active Profile",
)
if strings.Contains(view, "APT") || strings.Contains(view, "apt-config was not detected") {
t.Fatalf("default dashboard included an unavailable Target:\n%s", view)
@@ -71,12 +70,8 @@ func TestCompleteModelDashboardRevealsUnavailableEvidenceAndStructuredDetails(t
view := model.View()
assertUsableFrame(t, view, 120, 36,
"> ○ Unavailable APT", "State: ○ Unavailable", "Evidence: apt-config was not detected",
"Affects: package operations across privilege boundaries",
"Permissions: pre-existing root write authority",
"Ownership & restoration: isolated overlay; disabling reveals the", "previous configuration",
"Restart risk: none", "Persistent package proxy.", "Longer APT explanation.",
"u: hide unavailable",
"> ○ Unavailable APT", "○ Unavailable", "apt-config was not detected",
"Persistent package proxy.", "u: Hide unavailable",
)
if !(strings.Index(view, "Shell") < strings.Index(view, "APT") && strings.Index(view, "APT") < strings.Index(view, "Docker daemon")) {
t.Fatalf("revealing unavailable Targets changed product order:\n%s", view)
@@ -95,7 +90,7 @@ func TestCompleteModelNarrowDashboardFocusAndIndependentScrollingRetainTargetIde
}
}
targets[22].Description.Summary = "Selected identity summary"
targets[22].Description.Details = strings.Repeat("Scrollable detail line. ", 45) + "END OF TARGET DETAILS"
targets[22].Evidence = strings.Repeat("Scrollable evidence line. ", 45) + "END OF TARGET EVIDENCE"
module := &recordingModule{snapshot: app.Snapshot{ActiveProfile: "office", Targets: targets}}
model := resizedModel(t, module, themeModeNoColor, 80, 24)
for range 22 {
@@ -103,7 +98,7 @@ func TestCompleteModelNarrowDashboardFocusAndIndependentScrollingRetainTargetIde
}
view := model.View()
assertUsableFrame(t, view, 80, 24, "> ○ Disabled Product Target 22", "Selected identity summary", "▶ Targets [focused]")
assertUsableFrame(t, view, 80, 24, "> ○ Disabled Product Target 22", "▶ Targets [focused]")
model = updateKey(model, "tab")
for range 70 {
@@ -111,16 +106,16 @@ func TestCompleteModelNarrowDashboardFocusAndIndependentScrollingRetainTargetIde
}
view = model.View()
assertUsableFrame(t, view, 80, 24,
"> ○ Disabled Product Target 22", "▶ Target details [focused]", "END OF", "TARGET DETAILS",
"↑/k ↓/j PgUp/PgDn: scroll", "Tab: focus Targets",
"> ○ Disabled Product Target 22", "▶ Target details [focused]", "END OF", "TARGET EVIDENCE",
"↑/↓: Scroll", "Tab: Targets",
)
model = resize(model, 120, 36)
view = model.View()
assertUsableFrame(t, view, 120, 36, "> ○ Disabled Product Target 22", "END OF TARGET DETAILS", "▶ Target details [focused]")
assertUsableFrame(t, view, 120, 36, "> ○ Disabled Product Target 22", "END OF TARGET", "EVIDENCE", "▶ Target details [focused]")
if !sameLine(view, "Targets", "Target details") {
t.Fatalf("resized dashboard did not become side by side:\n%s", view)
}
model = resize(model, 80, 24)
assertUsableFrame(t, model.View(), 80, 24, "> ○ Disabled Product Target 22", "END OF", "TARGET DETAILS", "▶ Target details [focused]")
assertUsableFrame(t, model.View(), 80, 24, "> ○ Disabled Product Target 22", "END OF", "TARGET EVIDENCE", "▶ Target details [focused]")
}
+7 -45
View File
@@ -8,7 +8,6 @@ import (
"github.com/charmbracelet/lipgloss"
"proxyctl/internal/app"
"proxyctl/internal/target"
)
type dashboardRenderState struct {
@@ -149,55 +148,18 @@ func (p terminalPresentation) targetDetails(item app.TargetSnapshot, progress ap
var details strings.Builder
details.WriteString(p.theme.section.Render(item.Description.Name))
fmt.Fprintf(&details, "\nState: %s\nEvidence: %s", state, evidence)
fmt.Fprintf(&details, "\nAction: %s", targetActionLabel(item.PrimaryAction.Kind))
if !item.PrimaryAction.Available && item.PrimaryAction.DisabledReason != "" {
fmt.Fprintf(&details, "\nAction unavailable: %s", item.PrimaryAction.DisabledReason)
}
switch item.PrimaryAction.Kind {
case app.ApplyProfileTargetAction:
details.WriteString("\nApply Profile means proxyctl will begin managing this configuration while preserving restorable state.")
case app.ResolveDriftTargetAction:
details.WriteString("\nResolve opens Drift Resolution without choosing a recovery direction for you.")
fmt.Fprintf(&details, "\n%s\n%s", state, evidence)
action := targetActionLabel(item.PrimaryAction.Kind)
if item.PrimaryAction.Available {
fmt.Fprintf(&details, "\n\nSpace: %s", action)
} else if item.PrimaryAction.DisabledReason != "" {
fmt.Fprintf(&details, "\n\nUnavailable: %s", item.PrimaryAction.DisabledReason)
}
if item.DetectionPhase == app.TargetDetectionFailed && item.DetectionErr != nil {
fmt.Fprintf(&details, "\nCheck error: %s", item.DetectionErr)
}
facts := []struct {
label string
value string
}{
{"Affects", item.Description.Scope},
{"Permissions", item.Description.Permissions},
{"Ownership & restoration", item.Description.Ownership},
{"Restart risk", item.Description.RestartRisk},
}
for _, fact := range facts {
if fact.value != "" {
fmt.Fprintf(&details, "\n%s: %s", fact.label, fact.value)
}
fmt.Fprintf(&details, "\nCheck failed: %s", item.DetectionErr)
}
if item.Description.Summary != "" {
fmt.Fprintf(&details, "\n\n%s", item.Description.Summary)
}
if item.Description.Details != "" {
fmt.Fprintf(&details, "\n\n%s", item.Description.Details)
}
return protectRenderedText(details.String())
}
func (p terminalPresentation) stateCountSummary(snapshot app.Snapshot) string {
counts := countAvailableTargetStates(snapshot)
summary := fmt.Sprintf("%s %d %s %d %s %d %s %d",
p.theme.renderTargetState(target.Enabled, false), counts.enabled,
p.theme.renderTargetState(target.Disabled, false), counts.disabled,
p.theme.renderTargetState(target.External, false), counts.external,
p.theme.renderTargetState(target.Drifted, false), counts.drifted)
if counts.checking > 0 {
summary += fmt.Sprintf(" %s %d", p.theme.checking.Render("… Checking"), counts.checking)
}
if counts.failed > 0 {
summary += fmt.Sprintf(" %s %d", p.theme.checkFailed.Render("! Check failed"), counts.failed)
}
return summary
}
+10 -10
View File
@@ -24,7 +24,7 @@ func TestCompleteModelRendersResponsiveTerminalSizeClasses(t *testing.T) {
if !sameLine(view, "Targets", "Target details") {
t.Fatalf("wide layout did not place list and details side by side:\n%s", view)
}
assertUsableFrame(t, view, 120, 36, "Shell", "Shell summary", "Active Profile: office")
assertUsableFrame(t, view, 120, 36, "Shell", "Shell summary", "Profile: office")
})
t.Run("narrow 80x24", func(t *testing.T) {
@@ -33,7 +33,7 @@ func TestCompleteModelRendersResponsiveTerminalSizeClasses(t *testing.T) {
if sameLine(view, "Targets", "Target details") || strings.Index(view, "Target details") < strings.Index(view, "Shell") {
t.Fatalf("narrow layout did not stack list above details:\n%s", view)
}
assertUsableFrame(t, view, 80, 24, "Shell", "Shell summary", "Active Profile: office")
assertUsableFrame(t, view, 80, 24, "Shell", "Shell summary", "Profile: office")
})
t.Run("below minimum 59x15", func(t *testing.T) {
@@ -82,11 +82,11 @@ func TestCompleteModelResizePreservesValidSelectionAndFormFocus(t *testing.T) {
model := resizedModel(t, module, themeModeNoColor, 120, 36)
model = updateKey(model, "down")
model = resize(model, 80, 24)
if view := model.View(); !strings.Contains(view, "> ◇ External APT") || !strings.Contains(view, "Action: Apply Profile") {
if view := model.View(); !strings.Contains(view, "> ◇ External APT") || !strings.Contains(view, "Space: Apply Profile") {
t.Fatalf("Target selection did not survive wide-to-narrow resize:\n%s", view)
}
model = resize(model, 120, 36)
if view := model.View(); !strings.Contains(view, "> ◇ External APT") || !strings.Contains(view, "Action: Apply Profile") {
if view := model.View(); !strings.Contains(view, "> ◇ External APT") || !strings.Contains(view, "Space: Apply Profile") {
t.Fatalf("Target selection did not survive narrow-to-wide resize:\n%s", view)
}
@@ -110,7 +110,7 @@ func TestCompleteModelSemanticThemeSupportsDarkLightAndNoColor(t *testing.T) {
plain := resizedModel(t, module, themeModeNoColor, 80, 24).View()
for name, view := range map[string]string{"dark": dark, "light": light, "NO_COLOR": plain} {
for _, semantic := range []string{"Active Profile: office", "Disabled", "External", ">"} {
for _, semantic := range []string{"Profile: office", "Disabled", "External", ">"} {
if !strings.Contains(view, semantic) {
t.Fatalf("%s theme lost non-color semantic %q:\n%s", name, semantic, view)
}
@@ -134,7 +134,7 @@ func TestNewModelUsesInjectedBubbleTeaOutputForTerminalCapabilities(t *testing.T
if ansiPattern.MatchString(view) {
t.Fatalf("non-terminal Bubble Tea output received ANSI styling: %q", view)
}
for _, semantic := range []string{"Active Profile: office", "Disabled", "External", ">"} {
for _, semantic := range []string{"Profile: office", "Disabled", "External", ">"} {
if !strings.Contains(view, semantic) {
t.Fatalf("injected-output rendering lost semantic %q:\n%s", semantic, view)
}
@@ -231,19 +231,19 @@ func TestCompleteModelNarrowShellKeepsLastProductionTargetStatusAndActionsVisibl
assertUsableFrame(t, model.View(), 80, 24,
"> ! Drifted Docker daemon",
"State: ! Drifted",
"! Drifted",
"Docker daemon selected evidence.",
"Status: Refresh completed; selected Target remains actionable.",
"Space: Resolve",
"p: switch Active Profile",
"m: manage Proxy Profiles",
"p: Profile",
"m: Profiles",
)
model = resize(model, 120, 36)
model = resize(model, 80, 24)
assertUsableFrame(t, model.View(), 80, 24,
"> ! Drifted Docker daemon",
"State: ! Drifted",
"! Drifted",
"Docker daemon selected evidence.",
"Space: Resolve",
)
+8 -5
View File
@@ -30,7 +30,7 @@ func TestCompleteModelContextualHelpOpensOverEveryPageAndRestoresPageState(t *te
model = updateKey(model, "down")
model = updateKey(model, "?")
view := model.View()
assertUsableFrame(t, view, 120, 36, "Operations Console", "Contextual Help", "Dashboard", "Target details focus", "APT", "Disable")
assertUsableFrame(t, view, 120, 36, "Profile: office", "Contextual Help", "Dashboard", "Target details focus", "APT", "Disable")
model = updateKey(model, " ")
if len(module.intents) != 0 {
@@ -259,9 +259,9 @@ func TestCompleteModelFooterHintsMatchContextAndAcceptedKeys(t *testing.T) {
t.Run("dashboard and busy details", func(t *testing.T) {
model := resizedModel(t, module, themeModeNoColor, 120, 36)
assertUsableFrame(t, model.View(), 120, 36, "Space: Enable", "u: show unavailable", "r: refresh", "q/Ctrl+C: quit")
assertUsableFrame(t, model.View(), 120, 36, "Space: Enable", "u: Show hidden", "r: Refresh", "q: Quit")
model = updateKey(model, "tab")
assertUsableFrame(t, model.View(), 120, 36, "PgUp/PgDn: scroll", "u: show unavailable", "q/Ctrl+C: quit")
assertUsableFrame(t, model.View(), 120, 36, "↑/↓: Scroll", "u: Show hidden", "q: Quit")
updates := make(chan app.OperationUpdate)
busyModule := &interactiveScriptModule{snapshot: operationSnapshot(), streams: []chan app.OperationUpdate{updates}}
@@ -269,9 +269,12 @@ func TestCompleteModelFooterHintsMatchContextAndAcceptedKeys(t *testing.T) {
model = updateKey(model, "tab")
updated, _ := model.Update(tea.KeyMsg{Type: tea.KeySpace})
model = updated.(Model)
assertUsableFrame(t, model.View(), 120, 36, "u: show unavailable", "q/Ctrl+C: defer safe exit", "mutations disabled")
assertUsableFrame(t, model.View(), 120, 36, "q: Stop")
model = updateKey(model, "u")
assertUsableFrame(t, model.View(), 120, 36, "u: hide unavailable")
if !model.showUnavailable {
t.Fatal("u did not toggle unavailable Targets while busy")
}
assertUsableFrame(t, model.View(), 120, 36, "q: Stop")
close(updates)
})
+2 -2
View File
@@ -42,7 +42,7 @@ func TestMainAndProfilePagesMapKeysAndObscurePasswords(t *testing.T) {
}},
}}
model := NewModel(module)
if view := model.View(); !strings.Contains(view, "Active Profile: office") {
if view := model.View(); !strings.Contains(view, "Profile: office") {
t.Fatalf("main view missing Active Profile:\n%s", view)
}
@@ -130,7 +130,7 @@ func TestRenderedMalformedProxyURLStillObscuresPassword(t *testing.T) {
func TestNoProfileStateStaysOnAccessibleMainPage(t *testing.T) {
model := NewModel(&recordingModule{})
view := model.View()
if !strings.Contains(view, "No Active Profile") || !strings.Contains(view, "m: manage Proxy Profiles") {
if !strings.Contains(view, "No Active Profile") || !strings.Contains(view, "m: Profiles") {
t.Fatalf("no-Profile main view is not actionable:\n%s", view)
}
}
+15 -52
View File
@@ -14,12 +14,7 @@ func (p terminalPresentation) mainView(model presentationState, width, height in
if activeProfile == "" {
activeProfile = "No Active Profile"
}
header := fmt.Sprintf("%s Operations Console\nActive Profile: %s Targets: %s",
p.theme.title.Render("proxyctl"), activeProfile, p.stateCountSummary(model.snapshot))
if width < wideWidth {
header = fmt.Sprintf("%s Operations Console\nActive Profile: %s\nTargets: %s",
p.theme.title.Render("proxyctl"), activeProfile, p.stateCountSummary(model.snapshot))
}
header := fmt.Sprintf("%s Profile: %s", p.theme.title.Render("proxyctl"), activeProfile)
catalog := newTargetCatalog(model.snapshot, dashboard.showUnavailable, dashboard.selectedTargetID)
footer := p.dashboardFooter(model, catalog)
@@ -97,62 +92,30 @@ func (p terminalPresentation) driftResolutionView(selected app.TargetSnapshot) (
}
func (p terminalPresentation) dashboardFooter(model presentationState, catalog targetCatalog) string {
dashboard, operation, width := model.dashboard, model.operation, model.terminal.width
visibility := "u: show unavailable"
dashboard, operation := model.dashboard, model.operation
visibility := "u: Show hidden"
if dashboard.showUnavailable {
visibility = "u: hide unavailable"
visibility = "u: Hide unavailable"
}
if operation.exitDeferred {
return "Operation stopping; changes disabled ?: Help"
}
if dashboard.focus == targetDetailsPane {
if operation.exitDeferred {
return "↑/k ↓/j PgUp/PgDn: browse Tab: focus Targets " + visibility + " ?: help\nExit pending; new work disabled until safe completion"
}
if width < wideWidth {
if operation.active {
return "↑/k ↓/j PgUp/PgDn: browse Tab: focus Targets\n?: help q/Ctrl+C: defer exit; mutations disabled"
}
if width < 70 {
return "↑/k ↓/j PgUp/PgDn: scroll Tab: focus Targets\np: switch Profile m: manage ?: help q: quit"
}
return "↑/k ↓/j PgUp/PgDn: scroll Tab: focus Targets\np: switch Active Profile m: manage Proxy Profiles ?: help q: quit"
}
footer := "↑/k ↓/j PgUp/PgDn: scroll Tab: focus Targets " + visibility + "\np: switch Active Profile m: manage Proxy Profiles ?: help q/Ctrl+C: quit"
if operation.active {
footer = "↑/k ↓/j PgUp/PgDn: scroll Tab: focus Targets " + visibility + " ?: help\nq/Ctrl+C: defer safe exit; mutations disabled"
return "↑/↓: Scroll Tab: Targets ?: Help q: Stop"
}
return footer
}
actions := "↑/k ↓/j: select Tab: focus details " + visibility
if operation.exitDeferred {
return actions + " ?: help\nExit pending; new work disabled until safe completion"
return "↑/↓: Scroll Tab: Targets " + visibility + "\np: Profile m: Profiles r: Refresh ?: Help q: Quit"
}
selected, ok := catalog.selected(dashboard.selectedTargetID)
availability := targetMutationAvailability(selected, ok, operation.active || operation.exitDeferred)
label := targetActionLabel(selected.PrimaryAction.Kind)
if availability.available {
actions = "Space: " + label + " " + actions
} else {
actions = "Space: " + label + " disabled (" + availability.compactReason + ") " + actions
availability := targetMutationAvailability(selected, ok, operation.active)
action := "Space: " + targetActionLabel(selected.PrimaryAction.Kind)
if !availability.available {
action += " unavailable"
}
if width < wideWidth {
if availability.available {
actions = "Space: " + label + " ↑/k ↓/j: select Tab: focus details"
} else {
actions = "Space: " + label + " disabled ↑/k ↓/j: select Tab: focus details"
}
if operation.active {
return actions + "\n?: help q/Ctrl+C: defer exit; mutations disabled"
}
if width < 70 {
return actions + "\np: switch Profile m: manage ?: help q: quit"
}
return actions + "\np: switch Active Profile m: manage Proxy Profiles ?: help q: quit"
}
footer := actions + "\np: switch Active Profile m: manage Proxy Profiles r: refresh ?: help q/Ctrl+C: quit"
if operation.active {
footer = actions + "\n?: help q: defer safe exit; new mutations disabled"
return action + " ↑/↓: Select Tab: Details\n?: Help q: Stop"
}
return footer
return action + " ↑/↓: Select Tab: Details " + visibility + "\np: Profile m: Profiles r: Refresh ?: Help q: Quit"
}
func (p terminalPresentation) profilesView(model presentationState) terminalPage {
+1 -1
View File
@@ -219,7 +219,7 @@ func TestCompleteModelProfileManagementNavigationAndBusyReasonsAreConsistent(t *
model = updateKey(model, "m")
updated, command := model.Update(back)
model = updated.(Model)
if command != nil || !strings.Contains(model.View(), "Operations Console") {
if command != nil || !strings.Contains(model.View(), "Profile:") {
t.Fatalf("%q did not return to the dashboard:\n%s", back.String(), model.View())
}
}
+1 -1
View File
@@ -125,7 +125,7 @@ func TestCompleteModelReconcilesAuthoritativeSnapshotWhenDetectionGenerationClos
if next != nil || model.operation.active {
t.Fatalf("stale closure left detection active: next=%v active=%v", next != nil, model.operation.active)
}
assertUsableFrame(t, model.View(), 80, 24, "> ● Enabled Shell", "Evidence: shell enabled")
assertUsableFrame(t, model.View(), 80, 24, "> ● Enabled Shell", "shell enabled")
}
func (m *progressiveDetectionModule) detectionUpdate(id string, phase app.TargetDetectionPhase, available bool, state target.State, evidence string, err error) app.OperationUpdate {
+9 -9
View File
@@ -33,7 +33,7 @@ func TestCompleteModelFixedSizeCoverageAcrossCompletedWorkflows(t *testing.T) {
}
return resizedModel(t, &recordingModule{snapshot: snapshot}, themeModeNoColor, width, height)
},
want: []string{"Operations Console", "Checking", "Target availability"},
want: []string{"Profile:", "Checking", "Target availability"},
},
{
name: "refresh",
@@ -46,7 +46,7 @@ func TestCompleteModelFixedSizeCoverageAcrossCompletedWorkflows(t *testing.T) {
}
return model
},
want: []string{"Operations Console", "Checking Target availability and state"},
want: []string{"Profile:", "Checking Target availability and state"},
},
{
name: "Target action",
@@ -155,7 +155,7 @@ func TestCompleteModelLightDarkAndNoColorRetainEquivalentSemantics(t *testing.T)
model, _ = applyOperationCommand(t, model, command)
model = updateKey(model, "e")
views[mode] = progressFrame + "--- operation completed ---\n" + model.View()
for _, semantic := range []string{"[focused]", "Disabled", "Drifted", "Applying", "mutations disabled", "Current error:", "REDACTED", "Action: Enable"} {
for _, semantic := range []string{"[focused]", "Disabled", "Drifted", "Applying", "q: Stop", "Current error:", "REDACTED", "Space: Enable"} {
if !strings.Contains(views[mode], semantic) {
t.Fatalf("theme %d lost %q:\n%s", mode, semantic, views[mode])
}
@@ -163,7 +163,7 @@ func TestCompleteModelLightDarkAndNoColorRetainEquivalentSemantics(t *testing.T)
}
plain := views[themeModeNoColor]
for _, symbol := range []string{"● Enabled", "○ Disabled", "! Drifted", "▶ Target details [focused]"} {
for _, symbol := range []string{"○ Disabled", "! Drifted", "▶ Target details [focused]"} {
if !strings.Contains(plain, symbol) {
t.Fatalf("standard Unicode/ASCII status strategy lost %q:\n%s", symbol, plain)
}
@@ -188,7 +188,7 @@ func TestCompleteModelBoundsUnicodeAndKeepsLongContentReachable(t *testing.T) {
snapshot.Profiles[0].Name = longProfile
snapshot.Targets[0].Description.Name = longName
snapshot.Targets[0].Evidence = strings.Repeat("証拠 and wrapped evidence ", 80) + " EVIDENCE-END"
snapshot.Targets[0].Description.Details = strings.Repeat("詳細 line ", 100) + " DETAILS-END"
snapshot.Targets[0].Evidence = strings.Repeat("証拠 and wrapped evidence ", 120) + " EVIDENCE-END"
model := resizedModel(t, &recordingModule{snapshot: snapshot}, themeModeNoColor, 80, 24)
assertCellBoundedFrame(t, model.View(), 80, 24, "Disabled")
@@ -196,7 +196,7 @@ func TestCompleteModelBoundsUnicodeAndKeepsLongContentReachable(t *testing.T) {
for range 120 {
model = updateKey(model, "pgdown")
}
assertCellBoundedFrame(t, model.View(), 80, 24, "DETAILS-END")
assertCellBoundedFrame(t, model.View(), 80, 24, "EVIDENCE-END")
model = updateKey(model, "m")
for range 60 {
@@ -318,7 +318,7 @@ func TestCompleteModelLongFieldsAndDialogsRemainReachableAcrossResizeAtNontermin
func TestCompleteModelResizeStressPreservesDialogFocusSelectionViewportInFlightAndDeferredExit(t *testing.T) {
snapshot := hardeningSnapshot()
snapshot.Targets[1].Description.Details = strings.Repeat("APT scrollable detail. ", 90) + " APT-VIEWPORT-END"
snapshot.Targets[1].Evidence = strings.Repeat("APT scrollable evidence. ", 90) + " APT-VIEWPORT-END"
updates := make(chan app.OperationUpdate, 2)
module := &interactiveScriptModule{snapshot: snapshot, streams: []chan app.OperationUpdate{updates}}
model := resizedModel(t, module, themeModeNoColor, 120, 36)
@@ -354,8 +354,8 @@ func TestCompleteModelResizeStressPreservesDialogFocusSelectionViewportInFlightA
model = updateKey(model, "q")
assertCellBoundedFrame(t, model.View(), 80, 24,
"> ! Drifted APT", "▶ Target details [focused]", "APT-VIEWPORT-", "END",
"Applying", "Exit requested", "new work disabled")
"> ! Drifted APT", "▶ Target details [focused]", "VIEWPORT-END",
"Applying", "Exit requested", "changes disabled")
updates <- app.SucceededOperationUpdate(snapshot,
app.OperationStatus{Summary: "Shell Target is now Enabled", TargetID: "shell"},
+7 -7
View File
@@ -49,7 +49,7 @@ func TestTargetPanelShowsOnlyAvailableTargetsAndAppliesAsynchronously(t *testing
module.result = app.Result{Snapshot: app.Snapshot{ActiveProfile: "office", Targets: []app.TargetSnapshot{{ID: "shell", Description: target.Description{Name: "Shell", Summary: "Exports for Bash/Zsh"}, Available: true, State: target.Enabled, Evidence: "matches", PrimaryAction: app.TargetAction{Kind: app.DisableTargetAction, Available: true}}}}, Notice: "Shell Target is now Enabled"}
model := NewModel(module)
view := model.View()
if !strings.Contains(view, "Shell") || strings.Contains(view, "APT") || !strings.Contains(view, "Action: Apply Profile") {
if !strings.Contains(view, "Shell") || strings.Contains(view, "APT") || !strings.Contains(view, "Space: Apply Profile") {
t.Fatalf("Target panel:\n%s", view)
}
@@ -104,7 +104,7 @@ func TestHelpListsEveryTargetAndMainListsOnlyAvailableTargets(t *testing.T) {
}}}
model := NewModel(module)
view := model.View()
if strings.Contains(view, "APT") || !strings.Contains(view, "Action: Enable") || !strings.Contains(view, "integration installed") {
if strings.Contains(view, "APT") || !strings.Contains(view, "Unavailable:") || !strings.Contains(view, "integration installed") {
t.Fatalf("main Target panel:\n%s", view)
}
model = updateKey(model, "?")
@@ -123,7 +123,7 @@ func TestHelpListsEveryTargetAndMainListsOnlyAvailableTargets(t *testing.T) {
t.Fatalf("scrollable Target reference:\n%s", view)
}
model = updateKey(model, "esc")
if !strings.Contains(model.View(), "Operations Console") {
if !strings.Contains(model.View(), "Profile:") {
t.Fatalf("Escape did not return from help:\n%s", model.View())
}
}
@@ -279,12 +279,12 @@ func TestQAndEscapeReturnFromNestedPages(t *testing.T) {
for _, key := range []tea.KeyMsg{{Type: tea.KeyRunes, Runes: []rune{'q'}}, {Type: tea.KeyEsc}} {
model := updateKey(NewModel(module), "?")
updated, command := model.Update(key)
if command != nil || !strings.Contains(updated.(Model).View(), "Operations Console") {
t.Fatalf("help key %q did not return to Operations Console", key.String())
if command != nil || !strings.Contains(updated.(Model).View(), "Profile:") {
t.Fatalf("help key %q did not return to dashboard", key.String())
}
model = updateKey(NewModel(module), "m")
updated, command = model.Update(key)
if command != nil || !strings.Contains(updated.(Model).View(), "Operations Console") {
if command != nil || !strings.Contains(updated.(Model).View(), "Profile:") {
t.Fatalf("Profile key %q did not return to Target panel", key.String())
}
}
@@ -315,7 +315,7 @@ func TestActiveProfileTransitionRendersPerTargetProgress(t *testing.T) {
t.Fatal("Profile transition did not start progressive operation")
}
model, command = applyOperationCommand(t, model, command)
if command == nil || !strings.Contains(model.View(), "Applying") || !strings.Contains(model.View(), "Active Profile: new") {
if command == nil || !strings.Contains(model.View(), "Applying") || !strings.Contains(model.View(), "Profile: new") {
t.Fatalf("applying progress:\n%s", model.View())
}
model, command = applyOperationCommand(t, model, command)
+32 -17
View File
@@ -2,22 +2,37 @@
set -eu
repo=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
readme="$repo/README.md"
test -s "$readme"
for text in \
'## Install' 'go install ./cmd/proxyctl' '## First use and Profiles' \
'## Shell integration' 'Shell' 'APT' 'Docker daemon' \
'Docker containers/builds' 'GNOME' '## Target states' 'Enabled' \
'Disabled' 'External' 'Drifted' '## Permissions, sudo, and restarts' \
'proxyctl doctor' 'proxyctl reset' 'proxyctl shell uninstall' \
'no telemetry' 'automatic update checks' 'proxy-connectivity tests' \
'does **not** manage or supervise proxy processes' 'Support is limited'
do
grep -Fq "$text" "$readme" || {
echo "README is missing required documentation: $text" >&2
exit 1
}
done
require_text() {
file=$1
shift
test -s "$file"
for text
do
grep -Fq "$text" "$file" || {
echo "$file is missing required documentation: $text" >&2
exit 1
}
done
}
printf 'README documentation contract passed\n'
require_text "$repo/README.md" \
'## Install' 'go install ./cmd/proxyctl' '## Quick start' \
'## Shell integration' 'proxyctl doctor' 'proxyctl reset' \
'no telemetry' 'docs/user-guide.md' 'docs/security.md' 'docs/development.md'
require_text "$repo/docs/user-guide.md" \
'## Profiles' 'Protocol Probe' '## Target states' 'Enabled' 'Disabled' \
'External' 'Drifted' 'Shell' 'APT' 'Docker daemon' \
'Docker containers/builds' 'GNOME' 'NO_COLOR'
require_text "$repo/docs/security.md" \
'proxyctl never starts `sudo`' 'Configuration recovery' \
'no automatic update checks' 'does **not** manage or supervise proxy processes' \
'Support is limited'
require_text "$repo/docs/development.md" \
'go test ./...' 'go vet ./...' 'test-hermetic.sh' \
'test-release.sh' 'verify-clean-machine.sh' 'SHA256SUMS'
printf 'documentation contract passed\n'