From cc87ee0821d14ee8e4840833ed77562e602572b1 Mon Sep 17 00:00:00 2001 From: falbany Date: Wed, 18 Nov 2026 23:35:40 +0100 Subject: [PATCH 1/6] feat(web): LAN dialog stays open as a status panel with QR + loopback link MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Enable-LAN used to close the dialog before the async rebind (the "dialog-closes-first" quirk), leaving only toasts behind: the copyable hostname/IP URLs vanished exactly when they became reachable, and a failed bind flashed by unnoticed (issue #197). The enable flow now owns the modal until the user closes it: - confirming moves to a status panel (Enabling… → Enabled / Failed) that reports the rebind outcome inline instead of toast-only; - the enabled panel keeps the copyable hostname + IP URLs, adds the one-line "on another device" instruction, and an explicit ❌ close (Escape works too) — the panel uses useModalA11y (#146); - a QR encoding the IP URL appears once LAN is actually enabled, reusing generateBarcode / POST /api/actions/barcode — no new client dependency, display-only for phone scanning (issue #198); - a clickable http://127.0.0.1:{port} link sits alongside the copyable URLs in both phases — loopback always resolves on this machine and gives a one-click re-entry for --server-only runs (issue #199). The restrict path keeps its historical confirm-and-vanish flow, the App.tsx contract is unchanged (pending/onConfirmed/onCancel), and a stale flow can never paint over a reopened dialog (BarcodeModal's issue-#140 seq pattern). Closes #197 Closes #198 Closes #199 --- .../src/components/LanConfirmDialog.test.tsx | 259 +++++++++-- .../web/src/components/LanConfirmDialog.tsx | 427 +++++++++++++++--- 2 files changed, 566 insertions(+), 120 deletions(-) diff --git a/src/profiles/web/src/components/LanConfirmDialog.test.tsx b/src/profiles/web/src/components/LanConfirmDialog.test.tsx index c44217a..7a160ce 100644 --- a/src/profiles/web/src/components/LanConfirmDialog.test.tsx +++ b/src/profiles/web/src/components/LanConfirmDialog.test.tsx @@ -3,24 +3,33 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { cleanup, render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { LanConfirmDialog } from "./LanConfirmDialog"; -import { fetchSystemInfo, setLanEnabled, waitForLanState } from "../api/client"; +import { + fetchSystemInfo, + generateBarcode, + setLanEnabled, + waitForLanState, +} from "../api/client"; import type { SystemInfo } from "../api/types"; vi.mock("../api/client", async (importOriginal) => { - // Keep the real module: the dialog only needs the three flow functions - // mocked (ConfigEditorModal precedent for direct-imported api clients). + // Keep the real module: the dialog only needs the flow functions mocked + // (ConfigEditorModal precedent for direct-imported api clients). const actual = await importOriginal(); return { ...actual, setLanEnabled: vi.fn(), waitForLanState: vi.fn(), fetchSystemInfo: vi.fn(), + generateBarcode: vi.fn(), }; }); const setLanSpy = vi.mocked(setLanEnabled); const waitSpy = vi.mocked(waitForLanState); const fetchSpy = vi.mocked(fetchSystemInfo); +const qrSpy = vi.mocked(generateBarcode); + +const QR_IMAGE = "data:image/png;base64,FAKEQR"; /** LAN-enabled machine fixture; realistic for the dialog's URLs. */ function makeSystemInfo(overrides: Partial = {}): SystemInfo { @@ -34,6 +43,15 @@ function makeSystemInfo(overrides: Partial = {}): SystemInfo { }; } +/** Manually-resolved promise so enabling-state timing is deterministic. */ +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((res) => { + resolve = res; + }); + return { promise, resolve }; +} + function renderDialog( overrides: { pending?: boolean | null; systemInfo?: SystemInfo | null } = {}, ) { @@ -44,14 +62,26 @@ function renderDialog( onConfirmed: vi.fn(), onCancel: vi.fn(), }; - render(); - return props; + const utils = render(); + return { ...props, rerender: utils.rerender }; +} + +/** Click "Enable LAN" and hold the flow on the enabling state via a gate. + * QR behavior is left to the caller / the beforeEach default. */ +async function enableThroughEnablingGate() { + const gate = deferred(); + waitSpy.mockReturnValue(gate.promise); + const props = renderDialog({ pending: true }); + const user = userEvent.setup(); + await user.click(screen.getByRole("button", { name: "Enable LAN" })); + return { gate, props, user }; } beforeEach(() => { setLanSpy.mockResolvedValue({ host: "st-465", lan_enabled: true, status: "ok" }); waitSpy.mockResolvedValue(makeSystemInfo()); fetchSpy.mockResolvedValue(makeSystemInfo()); + qrSpy.mockResolvedValue({ image: QR_IMAGE, content: "any" }); }); afterEach(() => { @@ -59,7 +89,7 @@ afterEach(() => { vi.restoreAllMocks(); }); -describe("LanConfirmDialog", () => { +describe("LanConfirmDialog — confirm phase", () => { it("renders nothing when pending is null", () => { renderDialog({ pending: null }); expect(screen.queryByRole("dialog")).toBeNull(); @@ -72,14 +102,31 @@ describe("LanConfirmDialog", () => { expect(screen.getByText("Enable LAN access?")).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Enable LAN" })).toBeInTheDocument(); expect(screen.getByText(/reachable by anyone on this network/)).toBeInTheDocument(); - // The hostname/IP URLs use the app port — same construction as App's - // message body (moved verbatim). expect(screen.getByText(`http://${sys.hostname}:${window.location.port}`)).toBeInTheDocument(); expect(screen.getByText(`http://${sys.ip}:${window.location.port}`)).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Copy hostname URL" })).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Copy IP URL" })).toBeInTheDocument(); }); + it("offers the loopback URL as a clickable link (issue #199)", () => { + renderDialog({ pending: true }); + + const loopback = screen.getByRole("link", { name: /127\.0\.0\.1/ }); + expect(loopback).toHaveAttribute( + "href", + `http://127.0.0.1:${window.location.port}` + ); + expect(loopback).toHaveAttribute("target", "_blank"); + expect(loopback).toHaveAttribute("rel", expect.stringContaining("noopener")); + }); + + it("renders no QR while LAN is not enabled yet (issue #198)", () => { + renderDialog({ pending: true }); + + expect(screen.queryByRole("img", { name: /QR/i })).toBeNull(); + expect(qrSpy).not.toHaveBeenCalled(); + }); + it("renders the restrict message when disabling", () => { renderDialog({ pending: false }); @@ -90,31 +137,95 @@ describe("LanConfirmDialog", () => { expect(screen.queryByRole("button", { name: "Copy IP URL" })).toBeNull(); }); - it("confirm closes the dialog first and still completes the flow", async () => { - const sys = makeSystemInfo(); - waitSpy.mockResolvedValue(sys); + it("cancel in the confirm phase closes without touching the API", async () => { const user = userEvent.setup(); - const { onCancel, onConfirmed, showToast } = renderDialog({ pending: true }); + const { onCancel } = renderDialog({ pending: true }); - await user.click(screen.getByRole("button", { name: "Enable LAN" })); + await user.click(screen.getByRole("button", { name: "Cancel" })); - // Dialog-closes-first quirk: the close action (onCancel) fires before - // the API call, yet the flow still completes behind the closed dialog. expect(onCancel).toHaveBeenCalledTimes(1); - expect(setLanSpy).toHaveBeenCalledWith(true); - expect(onCancel.mock.invocationCallOrder[0]).toBeLessThan( - setLanSpy.mock.invocationCallOrder[0] + expect(setLanSpy).not.toHaveBeenCalled(); + expect(waitSpy).not.toHaveBeenCalled(); + expect(fetchSpy).not.toHaveBeenCalled(); + expect(qrSpy).not.toHaveBeenCalled(); + }); +}); + +describe("LanConfirmDialog — enable flow panel (issue #197)", () => { + it("keeps the modal open through the flow and lands on the enabled panel", async () => { + const sys = makeSystemInfo(); + const { gate, props } = await enableThroughEnablingGate(); + + // No dialog-closes-first anymore: the modal stays up, flow inside. + expect(props.onCancel).not.toHaveBeenCalled(); + expect(screen.getByText("Enabling LAN…")).toBeInTheDocument(); + + gate.resolve(sys); + expect(await screen.findByText("LAN access enabled")).toBeInTheDocument(); + + expect(props.onConfirmed).toHaveBeenCalledWith(sys); + expect(props.onCancel).not.toHaveBeenCalled(); + // Inline status replaces the toasts while the panel is open. + expect(props.showToast).not.toHaveBeenCalled(); + expect(screen.getByText(/reachable on (this|the local) network/i)).toBeInTheDocument(); + // The URLs survive the toggle — the user can copy them now (issue #197). + expect(screen.getByRole("button", { name: "Copy hostname URL" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Copy IP URL" })).toBeInTheDocument(); + }); + + it("shows the instruction line and the loopback link in the enabled panel", async () => { + const { gate } = await enableThroughEnablingGate(); + gate.resolve(makeSystemInfo()); + await screen.findByText("LAN access enabled"); + + expect( + screen.getByText(/On another device on this network/) + ).toBeInTheDocument(); + expect(screen.getByRole("link", { name: /127\.0\.0\.1/ })).toBeInTheDocument(); + }); + + it("closes from the enabled panel via the ❌ button", async () => { + const { gate, props, user } = await enableThroughEnablingGate(); + gate.resolve(makeSystemInfo()); + await screen.findByText("LAN access enabled"); + + await user.click(screen.getByRole("button", { name: "Close" })); + + expect(props.onCancel).toHaveBeenCalledTimes(1); + }); + + it("closes the panel with Escape mid-flow and falls back to toasts", async () => { + const sys = makeSystemInfo(); + const { gate, props, user } = await enableThroughEnablingGate(); + expect(screen.getByText("Enabling LAN…")).toBeInTheDocument(); + + const close = screen.getByRole("button", { name: "Close" }); + await waitFor(() => expect(close).toHaveFocus()); + await user.keyboard("{Escape}"); + expect(props.onCancel).toHaveBeenCalledTimes(1); + // App answers onCancel by closing: the dialog unmounts its panel while + // the flow keeps running (same component instance, pending null). + props.rerender( + ); - await waitFor(() => expect(onConfirmed).toHaveBeenCalledWith(sys)); - expect(onConfirmed).toHaveBeenCalledTimes(1); - expect(showToast).toHaveBeenCalledWith("Updating LAN binding…", "info"); - expect(showToast).toHaveBeenCalledWith( + + // The flow completes behind the closed panel; the toast is now the only + // feedback channel. + gate.resolve(sys); + await waitFor(() => expect(props.onConfirmed).toHaveBeenCalledWith(sys)); + expect(props.showToast).toHaveBeenCalledWith( "ProFiles is now reachable on the local network.", "info" ); }); - it("waitForLanState disagreement toasts the still-active failure", async () => { + it("observed disagreement lands on the failed panel, inline and silent", async () => { // The bind response said ok, but the observed state never caught up: // the outcome branch reads waitForLanState's sys, not the response. const stale = makeSystemInfo({ lan_enabled: false }); @@ -124,47 +235,103 @@ describe("LanConfirmDialog", () => { await user.click(screen.getByRole("button", { name: "Enable LAN" })); - await waitFor(() => - expect(showToast).toHaveBeenCalledWith( - "Failed to update LAN binding — the previous address is still active.", - "error" - ) - ); - expect(onConfirmed).toHaveBeenCalledTimes(1); + expect(await screen.findByText("LAN update failed")).toBeInTheDocument(); + expect(screen.getByText(/previous address is still active/)).toBeInTheDocument(); expect(onConfirmed).toHaveBeenCalledWith(stale); - expect(fetchSpy).not.toHaveBeenCalled(); - expect(showToast).not.toHaveBeenCalledWith( - "ProFiles is now reachable on the local network.", - expect.anything() - ); + // Panel open → the failure is inline, not toast-only (issue #197). + expect(showToast).not.toHaveBeenCalled(); }); - it("rejected setLanEnabled toasts the failure and refetches system info", async () => { + it("rejected bind lands on the failed panel and refetches system info", async () => { setLanSpy.mockRejectedValue(new Error("boom")); const refetched = makeSystemInfo({ lan_enabled: false }); fetchSpy.mockResolvedValue(refetched); const user = userEvent.setup(); - const { onConfirmed, showToast } = renderDialog({ pending: true }); + const { onConfirmed } = renderDialog({ pending: true }); await user.click(screen.getByRole("button", { name: "Enable LAN" })); + expect(await screen.findByText("LAN update failed")).toBeInTheDocument(); + expect(screen.getByText(/Failed to update LAN binding: boom/)).toBeInTheDocument(); await waitFor(() => expect(onConfirmed).toHaveBeenCalledWith(refetched)); - expect(showToast).toHaveBeenCalledWith("Failed to update LAN binding: boom", "error"); expect(fetchSpy).toHaveBeenCalledTimes(1); - // The transitional toast ships only after the awaited bind call — - // a rejection skips it entirely. - expect(showToast).not.toHaveBeenCalledWith("Updating LAN binding…", expect.anything()); + }); +}); + +describe("LanConfirmDialog — QR code (issue #198)", () => { + it("renders a QR of the IP URL once LAN is enabled", async () => { + const sys = makeSystemInfo(); + const { gate } = await enableThroughEnablingGate(); + gate.resolve(sys); + + const qr = await screen.findByRole("img", { name: /QR/i }); + expect(qr).toHaveAttribute("src", QR_IMAGE); + expect(qrSpy).toHaveBeenCalledTimes(1); + expect(qrSpy).toHaveBeenCalledWith({ + content: `http://${sys.ip}:${window.location.port}`, + }); }); - it("cancel calls onCancel", async () => { + it("degrades to an inline message when QR generation fails", async () => { + qrSpy.mockRejectedValue(new Error("qr boom")); + const { gate } = await enableThroughEnablingGate(); + gate.resolve(makeSystemInfo()); + + expect(await screen.findByText(/qr boom/)).toBeInTheDocument(); + expect(screen.queryByRole("img", { name: /QR/i })).toBeNull(); + expect(screen.getByText("LAN access enabled")).toBeInTheDocument(); + }); +}); + +describe("LanConfirmDialog — restrict flow (unchanged)", () => { + it("confirm closes the dialog first and still completes the flow", async () => { + const sys = makeSystemInfo({ lan_enabled: false }); + waitSpy.mockResolvedValue(sys); const user = userEvent.setup(); - const { onCancel } = renderDialog({ pending: true }); + const { onCancel, onConfirmed, showToast } = renderDialog({ pending: false }); - await user.click(screen.getByRole("button", { name: "Cancel" })); + await user.click(screen.getByRole("button", { name: "Restrict" })); + // Dialog-closes-first quirk preserved on the restrict path: the close + // action (onCancel) fires before the API call, yet the flow still + // completes behind the closed dialog. expect(onCancel).toHaveBeenCalledTimes(1); - expect(setLanSpy).not.toHaveBeenCalled(); - expect(waitSpy).not.toHaveBeenCalled(); + expect(setLanSpy).toHaveBeenCalledWith(false); + expect(onCancel.mock.invocationCallOrder[0]).toBeLessThan( + setLanSpy.mock.invocationCallOrder[0] + ); + await waitFor(() => expect(onConfirmed).toHaveBeenCalledWith(sys)); + expect(onConfirmed).toHaveBeenCalledTimes(1); + expect(showToast).toHaveBeenCalledWith( + "Restricting ProFiles to this machine…", + "info" + ); + expect(showToast).toHaveBeenCalledWith( + "ProFiles is restricted to this machine.", + "info" + ); + }); + + it("waitForLanState disagreement toasts the still-active failure", async () => { + const stale = makeSystemInfo({ lan_enabled: true }); + waitSpy.mockResolvedValue(stale); + const user = userEvent.setup(); + const { onConfirmed, showToast } = renderDialog({ pending: false }); + + await user.click(screen.getByRole("button", { name: "Restrict" })); + + await waitFor(() => + expect(showToast).toHaveBeenCalledWith( + "Failed to update LAN binding — the previous address is still active.", + "error" + ) + ); + expect(onConfirmed).toHaveBeenCalledTimes(1); + expect(onConfirmed).toHaveBeenCalledWith(stale); expect(fetchSpy).not.toHaveBeenCalled(); + expect(showToast).not.toHaveBeenCalledWith( + "ProFiles is restricted to this machine.", + expect.anything() + ); }); }); diff --git a/src/profiles/web/src/components/LanConfirmDialog.tsx b/src/profiles/web/src/components/LanConfirmDialog.tsx index af5b512..671e797 100644 --- a/src/profiles/web/src/components/LanConfirmDialog.tsx +++ b/src/profiles/web/src/components/LanConfirmDialog.tsx @@ -1,7 +1,16 @@ -import { setLanEnabled, waitForLanState, fetchSystemInfo } from "../api/client"; +import { useEffect, useRef, useState } from "react"; +import { AlertTriangle, Check, ExternalLink, Wifi, X } from "lucide-react"; + +import { + fetchSystemInfo, + generateBarcode, + setLanEnabled, + waitForLanState, +} from "../api/client"; import type { SystemInfo } from "../api/types"; import { ConfirmDialog } from "./ConfirmDialog"; import { CopyableUrl } from "./CopyableUrl"; +import { useModalA11y } from "../hooks/useModalA11y"; export interface LanConfirmDialogProps { /** Tri-state: null = closed, true = enabling LAN access, false = restricting. */ @@ -13,19 +22,28 @@ export interface LanConfirmDialogProps { onCancel: () => void; } +/** Phases of the enable flow (issue #197): confirm → panel states. */ +type EnablePhase = "confirm" | "enabling" | "enabled" | "failed"; + /** - * LAN-toggle confirmation dialog — owns the observe-and-verify flow moved - * verbatim from App.tsx: `setLanEnabled` → transitional toast → - * `waitForLanState` (the rebind runs after the response, so the *observed* - * state decides the outcome branch) → success/failure toast, or a rejected - * bind → error toast + refetch. The api client is imported directly - * (ConfigEditorModal precedent); toasts flow through the injected - * `showToast` and observed state is reported via `onConfirmed(sys)`. + * LAN-toggle dialog (issues #197/#198/#199). The two directions diverge: + * + * - **Restrict** keeps the old confirm-and-vanish dialog — the confirm flow + * calls `onCancel()` at its start, the dialog disappears before the async + * work, and the flow completes behind it with toast-only feedback. + * - **Enable** keeps the modal open: confirming moves to a status panel + * (Enabling… → Enabled / Failed) that reports the rebind outcome inline. + * The copyable hostname/IP URLs survive the toggle, a clickable loopback + * link is offered in both phases, and the enabled panel shows a QR of the + * IP URL (`generateBarcode`, the files' "Generate QR Code" endpoint — no + * client-side dependency). Closing the panel mid-flow falls back to the + * toast channel: the async flow keeps running and reports through + * `onConfirmed(sys)` + toasts, exactly like the restrict path. * - * The dialog-closes-first quirk is preserved: the confirm flow calls - * `onCancel()` at its start — the same close action App already performs - * (`setLanPending(null)`) — so the dialog disappears before the async work - * and the flow still completes behind it. + * The api client is imported directly (ConfigEditorModal precedent); toasts + * flow through the injected `showToast` and observed state is reported via + * `onConfirmed(sys)`. App's contract is unchanged — `onCancel()` still only + * closes, it is simply no longer called by the enable flow itself. */ export function LanConfirmDialog({ pending, @@ -34,71 +52,332 @@ export function LanConfirmDialog({ onConfirmed, onCancel, }: LanConfirmDialogProps) { - return ( - - ProFiles will be reachable by anyone on this network: - showToast("URL copied to clipboard.")} - onCopyError={() => showToast("Failed to copy URL.", "error")} - /> - showToast("URL copied to clipboard.")} - onCopyError={() => showToast("Failed to copy URL.", "error")} - /> - - ) : ( - "ProFiles will be reachable only on this machine." - ) + const [phase, setPhase] = useState("confirm"); + const [failureMessage, setFailureMessage] = useState(null); + const [qrImage, setQrImage] = useState(null); + const [qrError, setQrError] = useState(null); + const panelRef = useRef(null); + const closeRef = useRef(null); + /** Monotonic tag per confirm click — a slow stale flow must never paint + * over a reopened dialog (BarcodeModal's issue-#140 pattern). */ + const flowSeqRef = useRef(0); + /** Mirror of "status panel visible", read by async completions to pick + * between inline state (open) and toasts (closed mid-flow). */ + const panelOpenRef = useRef(false); + + useEffect(() => { + panelOpenRef.current = pending !== null && phase !== "confirm"; + }, [pending, phase]); + + // A reopened dialog always starts from the confirmation view and + // invalidates any flow still in flight from a previous open. + useEffect(() => { + if (pending !== null) { + flowSeqRef.current += 1; + setPhase("confirm"); + setFailureMessage(null); + } + }, [pending]); + + const port = window.location.port; + const hostnameUrl = systemInfo ? `http://${systemInfo.hostname}:${port}` : null; + const ipUrl = systemInfo ? `http://${systemInfo.ip}:${port}` : null; + const loopbackUrl = `http://127.0.0.1:${port}`; + + // QR for the IP URL (issue #198): generated once on entering the enabled + // state — before the rebind the URL would scan into a dead address. + useEffect(() => { + if (phase !== "enabled" || !ipUrl) return; + let cancelled = false; + setQrImage(null); + setQrError(null); + generateBarcode({ content: ipUrl }) + .then((res) => { + if (!cancelled) setQrImage(res.image); + }) + .catch((err) => { + if (!cancelled) + setQrError( + err instanceof Error ? err.message : "Failed to generate the QR code" + ); + }); + return () => { + cancelled = true; + }; + }, [phase, ipUrl]); + + const panelIsOpen = pending !== null && phase !== "confirm"; + const handlePanelKeyDown = useModalA11y({ + isOpen: panelIsOpen, + onClose: onCancel, + dialogRef: panelRef, + initialFocusRef: closeRef, + }); + + if (pending === null) return null; + + /** Restrict keeps the historical dialog-closes-first flow (toast-only). */ + const runRestrictFlow = async () => { + // Dialog-closes-first: close through onCancel before the flow runs. + onCancel(); + try { + await setLanEnabled(false); + showToast("Restricting ProFiles to this machine…", "info"); + // The rebind runs after the response; observe the real outcome. + const sys = await waitForLanState(false); + if (sys) onConfirmed(sys); + if (sys?.lan_enabled === false) { + showToast("ProFiles is restricted to this machine.", "info"); + } else { + showToast( + "Failed to update LAN binding — the previous address is still active.", + "error" + ); } - confirmLabel={pending ? "Enable LAN" : "Restrict"} - onConfirm={async () => { - const next = pending!; - // Dialog-closes-first: close through onCancel before the flow runs. - onCancel(); - try { - await setLanEnabled(next); + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to update LAN binding"; + showToast(`Failed to update LAN binding: ${msg}`, "error"); + // Refetch to restore the actual state + const sys = await fetchSystemInfo(); + onConfirmed(sys); + } + }; + + /** Enable keeps the modal open and reports inline (issue #197). */ + const runEnableFlow = async () => { + const seq = ++flowSeqRef.current; + setFailureMessage(null); + setPhase("enabling"); + try { + await setLanEnabled(true); + // The rebind runs after the response; observe the real outcome. + const sys = await waitForLanState(true); + if (sys) onConfirmed(sys); + if (seq !== flowSeqRef.current) return; // dialog was reopened meanwhile + if (sys?.lan_enabled === true) { + setPhase("enabled"); + if (!panelOpenRef.current) { + showToast("ProFiles is now reachable on the local network.", "info"); + } + } else { + setPhase("failed"); + setFailureMessage( + "Failed to update LAN binding — the previous address is still active." + ); + if (!panelOpenRef.current) { showToast( - next - ? "Updating LAN binding…" - : "Restricting ProFiles to this machine…", - "info" + "Failed to update LAN binding — the previous address is still active.", + "error" ); - // The rebind runs after the response; observe the real outcome. - const sys = await waitForLanState(next); - if (sys) onConfirmed(sys); - if (sys?.lan_enabled === next) { - showToast( - next - ? "ProFiles is now reachable on the local network." - : "ProFiles is restricted to this machine.", - "info" - ); - } else { - showToast( - "Failed to update LAN binding — the previous address is still active.", - "error" - ); - } - } catch (err) { - const msg = err instanceof Error ? err.message : "Failed to update LAN binding"; - showToast(`Failed to update LAN binding: ${msg}`, "error"); - // Refetch to restore the actual state - const sys = await fetchSystemInfo(); - onConfirmed(sys); } - }} - onCancel={onCancel} - /> + } + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to update LAN binding"; + if (seq !== flowSeqRef.current) return; + setPhase("failed"); + setFailureMessage(`Failed to update LAN binding: ${msg}`); + // Refetch to restore the actual state + const sys = await fetchSystemInfo(); + onConfirmed(sys); + if (!panelOpenRef.current) { + showToast(`Failed to update LAN binding: ${msg}`, "error"); + } + } + }; + + if (pending === false) { + return ( + void runRestrictFlow()} + onCancel={onCancel} + /> + ); + } + + if (phase === "confirm") { + return ( + + ProFiles will be reachable by anyone on this network: + {hostnameUrl && ( + showToast("URL copied to clipboard.")} + onCopyError={() => showToast("Failed to copy URL.", "error")} + /> + )} + {ipUrl && ( + showToast("URL copied to clipboard.")} + onCopyError={() => showToast("Failed to copy URL.", "error")} + /> + )} + + + + } + confirmLabel="Enable LAN" + onConfirm={() => void runEnableFlow()} + onCancel={onCancel} + /> + ); + } + + // Status panel — Enabling… / Enabled / Failed (issue #197). + return ( +
+
e.stopPropagation()} + className="animate-modal-in w-[400px] max-w-full rounded-2xl border border-frame-line glass-panel p-5" + > +
+ + {phase === "enabled" ? ( + + ) : phase === "failed" ? ( + + ) : ( + + )} + +

+ {phase === "enabling" + ? "Enabling LAN…" + : phase === "enabled" + ? "LAN access enabled" + : "LAN update failed"} +

+ +
+ + {phase === "enabling" && ( +
+
+ )} + + {phase === "enabled" && ( +
+

+

+

On another device on this network, open one of these addresses:

+ {hostnameUrl && ( + showToast("URL copied to clipboard.")} + onCopyError={() => showToast("Failed to copy URL.", "error")} + /> + )} + {ipUrl && ( + showToast("URL copied to clipboard.")} + onCopyError={() => showToast("Failed to copy URL.", "error")} + /> + )} + + +
+
+ {qrImage ? ( + QR code of the LAN address + ) : qrError ? ( + + {qrError} + + ) : ( + + )} +
+

Scan to connect from a phone.

+
+
+ )} + + {phase === "failed" && ( +
+ {failureMessage} +
+ )} +
+
); } From b2220eedcb2928e436140a6767ab5a2f4fdc4296 Mon Sep 17 00:00:00 2001 From: falbany Date: Wed, 18 Nov 2026 23:58:02 +0100 Subject: [PATCH 2/6] =?UTF-8?q?feat(web):=20unify=20the=20LAN=20modal=20?= =?UTF-8?q?=E2=80=94=20QR=20always=20left,=20persistent=20footer,=20same?= =?UTF-8?q?=20UX=20both=20ways?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit User review on PR #200 reshaped the modal into a single LAN panel used for BOTH directions: - ONE modal (LanConfirmDialog → LanModal): it reflects the live systemInfo.lan_enabled and offers the opposite action, so enable and disable share the same UX. The disable path no longer uses the confirm-and-vanish flow — it runs in place like the enable one, and the dialog-closes-first quirk is gone entirely. - QR always displayed, on the LEFT of the addresses column, even while LAN is disabled (user decision overriding #198's original gating: the URL is unreachable for other devices until enabled). - Footer buttons never disappear: Cancel + the flip action ("Enable LAN" / "Disable LAN" per the live state) stay in every state, the action disabling while a rebind is in flight. - ❌ close always visible in the header; Escape still works; initial focus sits on Cancel (ConfirmDialog safety precedent). - App contract: pending/onCancel becomes open/onClose — toggleLan ignores the requested direction and just opens the modal. 391 web tests pass (31 files); verified in the real browser across enable → disable round trip with the rebuilt dist. --- src/profiles/web/src/App.tsx | 22 +- .../src/components/LanConfirmDialog.test.tsx | 337 --------------- .../web/src/components/LanConfirmDialog.tsx | 383 ------------------ .../web/src/components/LanModal.test.tsx | 273 +++++++++++++ src/profiles/web/src/components/LanModal.tsx | 327 +++++++++++++++ 5 files changed, 612 insertions(+), 730 deletions(-) delete mode 100644 src/profiles/web/src/components/LanConfirmDialog.test.tsx delete mode 100644 src/profiles/web/src/components/LanConfirmDialog.tsx create mode 100644 src/profiles/web/src/components/LanModal.test.tsx create mode 100644 src/profiles/web/src/components/LanModal.tsx diff --git a/src/profiles/web/src/App.tsx b/src/profiles/web/src/App.tsx index a2d9cc8..e82c169 100644 --- a/src/profiles/web/src/App.tsx +++ b/src/profiles/web/src/App.tsx @@ -32,7 +32,7 @@ import { DropConfigOverlay } from "./components/DropConfigOverlay"; import { FileListTable } from "./components/FileListTable"; import { HeaderBar } from "./components/HeaderBar"; import { InitErrorPanel } from "./components/InitErrorPanel"; -import { LanConfirmDialog } from "./components/LanConfirmDialog"; +import { LanModal } from "./components/LanModal"; import { SearchBar } from "./components/SearchBar"; import { LogViewerModal } from "./components/LogViewerModal"; import { ShortcutsModal } from "./components/ShortcutsModal"; @@ -96,8 +96,8 @@ export default function App() { const [propertiesFile, setPropertiesFile] = useState(null); const [showLogViewer, setShowLogViewer] = useState(false); const [showTimerModal, setShowTimerModal] = useState(false); - /** Pending LAN toggle (true/false) awaiting user confirmation. */ - const [lanPending, setLanPending] = useState(null); + /** LAN access modal visibility — one modal for enable and disable. */ + const [lanModalOpen, setLanModalOpen] = useState(false); // Workflow Modal state const [workflowLaunchParams, setWorkflowLaunchParams] = useState<{ @@ -121,9 +121,10 @@ export default function App() { const [showCameraScanner, setShowCameraScanner] = useState(false); const [singleMatchFile, setSingleMatchFile] = useState(null); - /** Open the in-app confirmation dialog for a LAN toggle request. */ - const toggleLan = (next: boolean) => { - setLanPending(next); + /** Open the LAN modal; it reflects the live bind state and offers the + * opposite action, so the requested direction from the header is unused. */ + const toggleLan = (_next: boolean) => { + setLanModalOpen(true); }; /** @@ -1171,13 +1172,14 @@ export default function App() { onCancel={() => setPendingDeleteFile(null)} /> - {/* LAN toggle confirmation */} - setLanPending(null)} + onClose={() => setLanModalOpen(false)} /> {/* Single Match Launch Confirmation */} diff --git a/src/profiles/web/src/components/LanConfirmDialog.test.tsx b/src/profiles/web/src/components/LanConfirmDialog.test.tsx deleted file mode 100644 index 7a160ce..0000000 --- a/src/profiles/web/src/components/LanConfirmDialog.test.tsx +++ /dev/null @@ -1,337 +0,0 @@ -// @vitest-environment jsdom -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { cleanup, render, screen, waitFor } from "@testing-library/react"; -import userEvent from "@testing-library/user-event"; -import { LanConfirmDialog } from "./LanConfirmDialog"; -import { - fetchSystemInfo, - generateBarcode, - setLanEnabled, - waitForLanState, -} from "../api/client"; -import type { SystemInfo } from "../api/types"; - -vi.mock("../api/client", async (importOriginal) => { - // Keep the real module: the dialog only needs the flow functions mocked - // (ConfigEditorModal precedent for direct-imported api clients). - const actual = await importOriginal(); - return { - ...actual, - setLanEnabled: vi.fn(), - waitForLanState: vi.fn(), - fetchSystemInfo: vi.fn(), - generateBarcode: vi.fn(), - }; -}); - -const setLanSpy = vi.mocked(setLanEnabled); -const waitSpy = vi.mocked(waitForLanState); -const fetchSpy = vi.mocked(fetchSystemInfo); -const qrSpy = vi.mocked(generateBarcode); - -const QR_IMAGE = "data:image/png;base64,FAKEQR"; - -/** LAN-enabled machine fixture; realistic for the dialog's URLs. */ -function makeSystemInfo(overrides: Partial = {}): SystemInfo { - return { - hostname: "st-465", - ip: "172.16.41.65", - username: "operator", - os_release: "TestOS 1.0", - lan_enabled: true, - ...overrides, - }; -} - -/** Manually-resolved promise so enabling-state timing is deterministic. */ -function deferred() { - let resolve!: (value: T) => void; - const promise = new Promise((res) => { - resolve = res; - }); - return { promise, resolve }; -} - -function renderDialog( - overrides: { pending?: boolean | null; systemInfo?: SystemInfo | null } = {}, -) { - const props = { - pending: overrides.pending ?? null, - systemInfo: overrides.systemInfo ?? makeSystemInfo(), - showToast: vi.fn(), - onConfirmed: vi.fn(), - onCancel: vi.fn(), - }; - const utils = render(); - return { ...props, rerender: utils.rerender }; -} - -/** Click "Enable LAN" and hold the flow on the enabling state via a gate. - * QR behavior is left to the caller / the beforeEach default. */ -async function enableThroughEnablingGate() { - const gate = deferred(); - waitSpy.mockReturnValue(gate.promise); - const props = renderDialog({ pending: true }); - const user = userEvent.setup(); - await user.click(screen.getByRole("button", { name: "Enable LAN" })); - return { gate, props, user }; -} - -beforeEach(() => { - setLanSpy.mockResolvedValue({ host: "st-465", lan_enabled: true, status: "ok" }); - waitSpy.mockResolvedValue(makeSystemInfo()); - fetchSpy.mockResolvedValue(makeSystemInfo()); - qrSpy.mockResolvedValue({ image: QR_IMAGE, content: "any" }); -}); - -afterEach(() => { - cleanup(); - vi.restoreAllMocks(); -}); - -describe("LanConfirmDialog — confirm phase", () => { - it("renders nothing when pending is null", () => { - renderDialog({ pending: null }); - expect(screen.queryByRole("dialog")).toBeNull(); - }); - - it("renders the LAN-on message with copyable URLs when enabling", () => { - const sys = makeSystemInfo(); - renderDialog({ pending: true, systemInfo: sys }); - - expect(screen.getByText("Enable LAN access?")).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Enable LAN" })).toBeInTheDocument(); - expect(screen.getByText(/reachable by anyone on this network/)).toBeInTheDocument(); - expect(screen.getByText(`http://${sys.hostname}:${window.location.port}`)).toBeInTheDocument(); - expect(screen.getByText(`http://${sys.ip}:${window.location.port}`)).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Copy hostname URL" })).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Copy IP URL" })).toBeInTheDocument(); - }); - - it("offers the loopback URL as a clickable link (issue #199)", () => { - renderDialog({ pending: true }); - - const loopback = screen.getByRole("link", { name: /127\.0\.0\.1/ }); - expect(loopback).toHaveAttribute( - "href", - `http://127.0.0.1:${window.location.port}` - ); - expect(loopback).toHaveAttribute("target", "_blank"); - expect(loopback).toHaveAttribute("rel", expect.stringContaining("noopener")); - }); - - it("renders no QR while LAN is not enabled yet (issue #198)", () => { - renderDialog({ pending: true }); - - expect(screen.queryByRole("img", { name: /QR/i })).toBeNull(); - expect(qrSpy).not.toHaveBeenCalled(); - }); - - it("renders the restrict message when disabling", () => { - renderDialog({ pending: false }); - - expect(screen.getByText("Restrict to this machine?")).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Restrict" })).toBeInTheDocument(); - expect(screen.getByText("ProFiles will be reachable only on this machine.")).toBeInTheDocument(); - expect(screen.queryByRole("button", { name: "Copy hostname URL" })).toBeNull(); - expect(screen.queryByRole("button", { name: "Copy IP URL" })).toBeNull(); - }); - - it("cancel in the confirm phase closes without touching the API", async () => { - const user = userEvent.setup(); - const { onCancel } = renderDialog({ pending: true }); - - await user.click(screen.getByRole("button", { name: "Cancel" })); - - expect(onCancel).toHaveBeenCalledTimes(1); - expect(setLanSpy).not.toHaveBeenCalled(); - expect(waitSpy).not.toHaveBeenCalled(); - expect(fetchSpy).not.toHaveBeenCalled(); - expect(qrSpy).not.toHaveBeenCalled(); - }); -}); - -describe("LanConfirmDialog — enable flow panel (issue #197)", () => { - it("keeps the modal open through the flow and lands on the enabled panel", async () => { - const sys = makeSystemInfo(); - const { gate, props } = await enableThroughEnablingGate(); - - // No dialog-closes-first anymore: the modal stays up, flow inside. - expect(props.onCancel).not.toHaveBeenCalled(); - expect(screen.getByText("Enabling LAN…")).toBeInTheDocument(); - - gate.resolve(sys); - expect(await screen.findByText("LAN access enabled")).toBeInTheDocument(); - - expect(props.onConfirmed).toHaveBeenCalledWith(sys); - expect(props.onCancel).not.toHaveBeenCalled(); - // Inline status replaces the toasts while the panel is open. - expect(props.showToast).not.toHaveBeenCalled(); - expect(screen.getByText(/reachable on (this|the local) network/i)).toBeInTheDocument(); - // The URLs survive the toggle — the user can copy them now (issue #197). - expect(screen.getByRole("button", { name: "Copy hostname URL" })).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Copy IP URL" })).toBeInTheDocument(); - }); - - it("shows the instruction line and the loopback link in the enabled panel", async () => { - const { gate } = await enableThroughEnablingGate(); - gate.resolve(makeSystemInfo()); - await screen.findByText("LAN access enabled"); - - expect( - screen.getByText(/On another device on this network/) - ).toBeInTheDocument(); - expect(screen.getByRole("link", { name: /127\.0\.0\.1/ })).toBeInTheDocument(); - }); - - it("closes from the enabled panel via the ❌ button", async () => { - const { gate, props, user } = await enableThroughEnablingGate(); - gate.resolve(makeSystemInfo()); - await screen.findByText("LAN access enabled"); - - await user.click(screen.getByRole("button", { name: "Close" })); - - expect(props.onCancel).toHaveBeenCalledTimes(1); - }); - - it("closes the panel with Escape mid-flow and falls back to toasts", async () => { - const sys = makeSystemInfo(); - const { gate, props, user } = await enableThroughEnablingGate(); - expect(screen.getByText("Enabling LAN…")).toBeInTheDocument(); - - const close = screen.getByRole("button", { name: "Close" }); - await waitFor(() => expect(close).toHaveFocus()); - await user.keyboard("{Escape}"); - expect(props.onCancel).toHaveBeenCalledTimes(1); - // App answers onCancel by closing: the dialog unmounts its panel while - // the flow keeps running (same component instance, pending null). - props.rerender( - - ); - - // The flow completes behind the closed panel; the toast is now the only - // feedback channel. - gate.resolve(sys); - await waitFor(() => expect(props.onConfirmed).toHaveBeenCalledWith(sys)); - expect(props.showToast).toHaveBeenCalledWith( - "ProFiles is now reachable on the local network.", - "info" - ); - }); - - it("observed disagreement lands on the failed panel, inline and silent", async () => { - // The bind response said ok, but the observed state never caught up: - // the outcome branch reads waitForLanState's sys, not the response. - const stale = makeSystemInfo({ lan_enabled: false }); - waitSpy.mockResolvedValue(stale); - const user = userEvent.setup(); - const { onConfirmed, showToast } = renderDialog({ pending: true }); - - await user.click(screen.getByRole("button", { name: "Enable LAN" })); - - expect(await screen.findByText("LAN update failed")).toBeInTheDocument(); - expect(screen.getByText(/previous address is still active/)).toBeInTheDocument(); - expect(onConfirmed).toHaveBeenCalledWith(stale); - // Panel open → the failure is inline, not toast-only (issue #197). - expect(showToast).not.toHaveBeenCalled(); - }); - - it("rejected bind lands on the failed panel and refetches system info", async () => { - setLanSpy.mockRejectedValue(new Error("boom")); - const refetched = makeSystemInfo({ lan_enabled: false }); - fetchSpy.mockResolvedValue(refetched); - const user = userEvent.setup(); - const { onConfirmed } = renderDialog({ pending: true }); - - await user.click(screen.getByRole("button", { name: "Enable LAN" })); - - expect(await screen.findByText("LAN update failed")).toBeInTheDocument(); - expect(screen.getByText(/Failed to update LAN binding: boom/)).toBeInTheDocument(); - await waitFor(() => expect(onConfirmed).toHaveBeenCalledWith(refetched)); - expect(fetchSpy).toHaveBeenCalledTimes(1); - }); -}); - -describe("LanConfirmDialog — QR code (issue #198)", () => { - it("renders a QR of the IP URL once LAN is enabled", async () => { - const sys = makeSystemInfo(); - const { gate } = await enableThroughEnablingGate(); - gate.resolve(sys); - - const qr = await screen.findByRole("img", { name: /QR/i }); - expect(qr).toHaveAttribute("src", QR_IMAGE); - expect(qrSpy).toHaveBeenCalledTimes(1); - expect(qrSpy).toHaveBeenCalledWith({ - content: `http://${sys.ip}:${window.location.port}`, - }); - }); - - it("degrades to an inline message when QR generation fails", async () => { - qrSpy.mockRejectedValue(new Error("qr boom")); - const { gate } = await enableThroughEnablingGate(); - gate.resolve(makeSystemInfo()); - - expect(await screen.findByText(/qr boom/)).toBeInTheDocument(); - expect(screen.queryByRole("img", { name: /QR/i })).toBeNull(); - expect(screen.getByText("LAN access enabled")).toBeInTheDocument(); - }); -}); - -describe("LanConfirmDialog — restrict flow (unchanged)", () => { - it("confirm closes the dialog first and still completes the flow", async () => { - const sys = makeSystemInfo({ lan_enabled: false }); - waitSpy.mockResolvedValue(sys); - const user = userEvent.setup(); - const { onCancel, onConfirmed, showToast } = renderDialog({ pending: false }); - - await user.click(screen.getByRole("button", { name: "Restrict" })); - - // Dialog-closes-first quirk preserved on the restrict path: the close - // action (onCancel) fires before the API call, yet the flow still - // completes behind the closed dialog. - expect(onCancel).toHaveBeenCalledTimes(1); - expect(setLanSpy).toHaveBeenCalledWith(false); - expect(onCancel.mock.invocationCallOrder[0]).toBeLessThan( - setLanSpy.mock.invocationCallOrder[0] - ); - await waitFor(() => expect(onConfirmed).toHaveBeenCalledWith(sys)); - expect(onConfirmed).toHaveBeenCalledTimes(1); - expect(showToast).toHaveBeenCalledWith( - "Restricting ProFiles to this machine…", - "info" - ); - expect(showToast).toHaveBeenCalledWith( - "ProFiles is restricted to this machine.", - "info" - ); - }); - - it("waitForLanState disagreement toasts the still-active failure", async () => { - const stale = makeSystemInfo({ lan_enabled: true }); - waitSpy.mockResolvedValue(stale); - const user = userEvent.setup(); - const { onConfirmed, showToast } = renderDialog({ pending: false }); - - await user.click(screen.getByRole("button", { name: "Restrict" })); - - await waitFor(() => - expect(showToast).toHaveBeenCalledWith( - "Failed to update LAN binding — the previous address is still active.", - "error" - ) - ); - expect(onConfirmed).toHaveBeenCalledTimes(1); - expect(onConfirmed).toHaveBeenCalledWith(stale); - expect(fetchSpy).not.toHaveBeenCalled(); - expect(showToast).not.toHaveBeenCalledWith( - "ProFiles is restricted to this machine.", - expect.anything() - ); - }); -}); diff --git a/src/profiles/web/src/components/LanConfirmDialog.tsx b/src/profiles/web/src/components/LanConfirmDialog.tsx deleted file mode 100644 index 671e797..0000000 --- a/src/profiles/web/src/components/LanConfirmDialog.tsx +++ /dev/null @@ -1,383 +0,0 @@ -import { useEffect, useRef, useState } from "react"; -import { AlertTriangle, Check, ExternalLink, Wifi, X } from "lucide-react"; - -import { - fetchSystemInfo, - generateBarcode, - setLanEnabled, - waitForLanState, -} from "../api/client"; -import type { SystemInfo } from "../api/types"; -import { ConfirmDialog } from "./ConfirmDialog"; -import { CopyableUrl } from "./CopyableUrl"; -import { useModalA11y } from "../hooks/useModalA11y"; - -export interface LanConfirmDialogProps { - /** Tri-state: null = closed, true = enabling LAN access, false = restricting. */ - pending: boolean | null; - systemInfo: SystemInfo | null; - showToast: (msg: string, kind?: "info" | "error") => void; - /** Called with the observed SystemInfo on both success and refetch paths. */ - onConfirmed: (sys: SystemInfo) => void; - onCancel: () => void; -} - -/** Phases of the enable flow (issue #197): confirm → panel states. */ -type EnablePhase = "confirm" | "enabling" | "enabled" | "failed"; - -/** - * LAN-toggle dialog (issues #197/#198/#199). The two directions diverge: - * - * - **Restrict** keeps the old confirm-and-vanish dialog — the confirm flow - * calls `onCancel()` at its start, the dialog disappears before the async - * work, and the flow completes behind it with toast-only feedback. - * - **Enable** keeps the modal open: confirming moves to a status panel - * (Enabling… → Enabled / Failed) that reports the rebind outcome inline. - * The copyable hostname/IP URLs survive the toggle, a clickable loopback - * link is offered in both phases, and the enabled panel shows a QR of the - * IP URL (`generateBarcode`, the files' "Generate QR Code" endpoint — no - * client-side dependency). Closing the panel mid-flow falls back to the - * toast channel: the async flow keeps running and reports through - * `onConfirmed(sys)` + toasts, exactly like the restrict path. - * - * The api client is imported directly (ConfigEditorModal precedent); toasts - * flow through the injected `showToast` and observed state is reported via - * `onConfirmed(sys)`. App's contract is unchanged — `onCancel()` still only - * closes, it is simply no longer called by the enable flow itself. - */ -export function LanConfirmDialog({ - pending, - systemInfo, - showToast, - onConfirmed, - onCancel, -}: LanConfirmDialogProps) { - const [phase, setPhase] = useState("confirm"); - const [failureMessage, setFailureMessage] = useState(null); - const [qrImage, setQrImage] = useState(null); - const [qrError, setQrError] = useState(null); - const panelRef = useRef(null); - const closeRef = useRef(null); - /** Monotonic tag per confirm click — a slow stale flow must never paint - * over a reopened dialog (BarcodeModal's issue-#140 pattern). */ - const flowSeqRef = useRef(0); - /** Mirror of "status panel visible", read by async completions to pick - * between inline state (open) and toasts (closed mid-flow). */ - const panelOpenRef = useRef(false); - - useEffect(() => { - panelOpenRef.current = pending !== null && phase !== "confirm"; - }, [pending, phase]); - - // A reopened dialog always starts from the confirmation view and - // invalidates any flow still in flight from a previous open. - useEffect(() => { - if (pending !== null) { - flowSeqRef.current += 1; - setPhase("confirm"); - setFailureMessage(null); - } - }, [pending]); - - const port = window.location.port; - const hostnameUrl = systemInfo ? `http://${systemInfo.hostname}:${port}` : null; - const ipUrl = systemInfo ? `http://${systemInfo.ip}:${port}` : null; - const loopbackUrl = `http://127.0.0.1:${port}`; - - // QR for the IP URL (issue #198): generated once on entering the enabled - // state — before the rebind the URL would scan into a dead address. - useEffect(() => { - if (phase !== "enabled" || !ipUrl) return; - let cancelled = false; - setQrImage(null); - setQrError(null); - generateBarcode({ content: ipUrl }) - .then((res) => { - if (!cancelled) setQrImage(res.image); - }) - .catch((err) => { - if (!cancelled) - setQrError( - err instanceof Error ? err.message : "Failed to generate the QR code" - ); - }); - return () => { - cancelled = true; - }; - }, [phase, ipUrl]); - - const panelIsOpen = pending !== null && phase !== "confirm"; - const handlePanelKeyDown = useModalA11y({ - isOpen: panelIsOpen, - onClose: onCancel, - dialogRef: panelRef, - initialFocusRef: closeRef, - }); - - if (pending === null) return null; - - /** Restrict keeps the historical dialog-closes-first flow (toast-only). */ - const runRestrictFlow = async () => { - // Dialog-closes-first: close through onCancel before the flow runs. - onCancel(); - try { - await setLanEnabled(false); - showToast("Restricting ProFiles to this machine…", "info"); - // The rebind runs after the response; observe the real outcome. - const sys = await waitForLanState(false); - if (sys) onConfirmed(sys); - if (sys?.lan_enabled === false) { - showToast("ProFiles is restricted to this machine.", "info"); - } else { - showToast( - "Failed to update LAN binding — the previous address is still active.", - "error" - ); - } - } catch (err) { - const msg = err instanceof Error ? err.message : "Failed to update LAN binding"; - showToast(`Failed to update LAN binding: ${msg}`, "error"); - // Refetch to restore the actual state - const sys = await fetchSystemInfo(); - onConfirmed(sys); - } - }; - - /** Enable keeps the modal open and reports inline (issue #197). */ - const runEnableFlow = async () => { - const seq = ++flowSeqRef.current; - setFailureMessage(null); - setPhase("enabling"); - try { - await setLanEnabled(true); - // The rebind runs after the response; observe the real outcome. - const sys = await waitForLanState(true); - if (sys) onConfirmed(sys); - if (seq !== flowSeqRef.current) return; // dialog was reopened meanwhile - if (sys?.lan_enabled === true) { - setPhase("enabled"); - if (!panelOpenRef.current) { - showToast("ProFiles is now reachable on the local network.", "info"); - } - } else { - setPhase("failed"); - setFailureMessage( - "Failed to update LAN binding — the previous address is still active." - ); - if (!panelOpenRef.current) { - showToast( - "Failed to update LAN binding — the previous address is still active.", - "error" - ); - } - } - } catch (err) { - const msg = err instanceof Error ? err.message : "Failed to update LAN binding"; - if (seq !== flowSeqRef.current) return; - setPhase("failed"); - setFailureMessage(`Failed to update LAN binding: ${msg}`); - // Refetch to restore the actual state - const sys = await fetchSystemInfo(); - onConfirmed(sys); - if (!panelOpenRef.current) { - showToast(`Failed to update LAN binding: ${msg}`, "error"); - } - } - }; - - if (pending === false) { - return ( - void runRestrictFlow()} - onCancel={onCancel} - /> - ); - } - - if (phase === "confirm") { - return ( - - ProFiles will be reachable by anyone on this network: - {hostnameUrl && ( - showToast("URL copied to clipboard.")} - onCopyError={() => showToast("Failed to copy URL.", "error")} - /> - )} - {ipUrl && ( - showToast("URL copied to clipboard.")} - onCopyError={() => showToast("Failed to copy URL.", "error")} - /> - )} - - - - } - confirmLabel="Enable LAN" - onConfirm={() => void runEnableFlow()} - onCancel={onCancel} - /> - ); - } - - // Status panel — Enabling… / Enabled / Failed (issue #197). - return ( -
-
e.stopPropagation()} - className="animate-modal-in w-[400px] max-w-full rounded-2xl border border-frame-line glass-panel p-5" - > -
- - {phase === "enabled" ? ( - - ) : phase === "failed" ? ( - - ) : ( - - )} - -

- {phase === "enabling" - ? "Enabling LAN…" - : phase === "enabled" - ? "LAN access enabled" - : "LAN update failed"} -

- -
- - {phase === "enabling" && ( -
-
- )} - - {phase === "enabled" && ( -
-

-

-

On another device on this network, open one of these addresses:

- {hostnameUrl && ( - showToast("URL copied to clipboard.")} - onCopyError={() => showToast("Failed to copy URL.", "error")} - /> - )} - {ipUrl && ( - showToast("URL copied to clipboard.")} - onCopyError={() => showToast("Failed to copy URL.", "error")} - /> - )} - - -
-
- {qrImage ? ( - QR code of the LAN address - ) : qrError ? ( - - {qrError} - - ) : ( - - )} -
-

Scan to connect from a phone.

-
-
- )} - - {phase === "failed" && ( -
- {failureMessage} -
- )} -
-
- ); -} diff --git a/src/profiles/web/src/components/LanModal.test.tsx b/src/profiles/web/src/components/LanModal.test.tsx new file mode 100644 index 0000000..e0e906e --- /dev/null +++ b/src/profiles/web/src/components/LanModal.test.tsx @@ -0,0 +1,273 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { cleanup, render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { LanModal } from "./LanModal"; +import { + fetchSystemInfo, + generateBarcode, + setLanEnabled, + waitForLanState, +} from "../api/client"; +import type { SystemInfo } from "../api/types"; + +vi.mock("../api/client", async (importOriginal) => { + // Keep the real module: the modal only needs the flow functions mocked + // (ConfigEditorModal precedent for direct-imported api clients). + const actual = await importOriginal(); + return { + ...actual, + setLanEnabled: vi.fn(), + waitForLanState: vi.fn(), + fetchSystemInfo: vi.fn(), + generateBarcode: vi.fn(), + }; +}); + +const setLanSpy = vi.mocked(setLanEnabled); +const waitSpy = vi.mocked(waitForLanState); +const fetchSpy = vi.mocked(fetchSystemInfo); +const qrSpy = vi.mocked(generateBarcode); + +const QR_IMAGE = "data:image/png;base64,FAKEQR"; + +/** LAN-enabled machine fixture; realistic for the modal's URLs. */ +function makeSystemInfo(overrides: Partial = {}): SystemInfo { + return { + hostname: "st-465", + ip: "172.16.41.65", + username: "operator", + os_release: "TestOS 1.0", + lan_enabled: false, + ...overrides, + }; +} + +/** Manually-resolved promise so in-flight timing is deterministic. */ +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((res) => { + resolve = res; + }); + return { promise, resolve }; +} + +function renderModal( + overrides: { open?: boolean; systemInfo?: SystemInfo | null } = {}, +) { + const props = { + open: overrides.open ?? true, + systemInfo: + overrides.systemInfo !== undefined + ? overrides.systemInfo + : makeSystemInfo(), + showToast: vi.fn(), + onConfirmed: vi.fn(), + onClose: vi.fn(), + }; + const utils = render(); + return { ...props, rerender: utils.rerender }; +} + +beforeEach(() => { + setLanSpy.mockResolvedValue({ host: "st-465", lan_enabled: true, status: "ok" }); + waitSpy.mockResolvedValue(makeSystemInfo()); + fetchSpy.mockResolvedValue(makeSystemInfo()); + qrSpy.mockResolvedValue({ image: QR_IMAGE, content: "any" }); +}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +describe("LanModal — visibility & state display", () => { + it("renders nothing when open is false and generates no QR", () => { + renderModal({ open: false }); + + expect(screen.queryByRole("dialog")).toBeNull(); + expect(qrSpy).not.toHaveBeenCalled(); + }); + + it("shows the restricted state with an Enable LAN footer button", () => { + renderModal({ systemInfo: makeSystemInfo({ lan_enabled: false }) }); + + expect(screen.getByText("LAN access")).toBeInTheDocument(); + expect(screen.getByText(/restricted to this machine/)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Enable LAN" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Cancel" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Close" })).toBeInTheDocument(); + // Same URLs either way — informational, plus the loopback link (#199). + expect(screen.getByRole("button", { name: "Copy hostname URL" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Copy IP URL" })).toBeInTheDocument(); + expect(screen.getByRole("link", { name: /127\.0\.0\.1/ })).toBeInTheDocument(); + }); + + it("shows the enabled state with a Disable LAN footer button", () => { + renderModal({ systemInfo: makeSystemInfo({ lan_enabled: true }) }); + + expect(screen.getByText(/reachable on this network/)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Disable LAN" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Cancel" })).toBeInTheDocument(); + }); + + it("always displays the QR, even while LAN is disabled (issue #198 override)", async () => { + const sys = makeSystemInfo({ lan_enabled: false }); + renderModal({ systemInfo: sys }); + + const qr = await screen.findByRole("img", { name: /QR/i }); + expect(qr).toHaveAttribute("src", QR_IMAGE); + expect(qrSpy).toHaveBeenCalledWith({ + content: `http://${sys.ip}:${window.location.port}`, + }); + }); + + it("degrades to an inline message when QR generation fails", async () => { + qrSpy.mockRejectedValue(new Error("qr boom")); + renderModal(); + + expect(await screen.findByText(/qr boom/)).toBeInTheDocument(); + expect(screen.queryByRole("img", { name: /QR/i })).toBeNull(); + expect(screen.getByRole("button", { name: "Enable LAN" })).toBeEnabled(); + }); +}); + +describe("LanModal — enable flow (stays open)", () => { + it("runs in place and flips the modal to the enabled state", async () => { + const sys = makeSystemInfo({ lan_enabled: true }); + const gate = deferred(); + waitSpy.mockReturnValue(gate.promise); + const props = renderModal({ systemInfo: makeSystemInfo() }); + const user = userEvent.setup(); + + await user.click(screen.getByRole("button", { name: "Enable LAN" })); + + // No dialog-closes-first: the modal stays up, flow inside. + expect(props.onClose).not.toHaveBeenCalled(); + expect(screen.getByText("Updating the LAN binding…")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Enable LAN" })).toBeDisabled(); + expect(screen.getByRole("button", { name: "Cancel" })).toBeEnabled(); + + gate.resolve(sys); + await waitFor(() => expect(props.onConfirmed).toHaveBeenCalledWith(sys)); + // App answers onConfirmed by updating systemInfo → the modal reflects it. + props.rerender(); + expect(screen.getByText(/reachable on this network/)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Disable LAN" })).toBeEnabled(); + // Inline outcome replaces toasts while the modal is open. + expect(props.showToast).not.toHaveBeenCalled(); + }); + + it("observed disagreement shows the failure inline, silent while open", async () => { + const stale = makeSystemInfo({ lan_enabled: false }); + waitSpy.mockResolvedValue(stale); + const user = userEvent.setup(); + const props = renderModal({ systemInfo: makeSystemInfo() }); + + await user.click(screen.getByRole("button", { name: "Enable LAN" })); + + expect(await screen.findByText(/previous address is still active/)).toBeInTheDocument(); + expect(props.onConfirmed).toHaveBeenCalledWith(stale); + expect(props.showToast).not.toHaveBeenCalled(); + expect(screen.getByRole("button", { name: "Enable LAN" })).toBeEnabled(); + }); + + it("rejected bind shows the failure inline and refetches system info", async () => { + setLanSpy.mockRejectedValue(new Error("boom")); + const refetched = makeSystemInfo({ lan_enabled: false }); + fetchSpy.mockResolvedValue(refetched); + const user = userEvent.setup(); + const props = renderModal({ systemInfo: makeSystemInfo() }); + + await user.click(screen.getByRole("button", { name: "Enable LAN" })); + + expect(await screen.findByText(/Failed to update LAN binding: boom/)).toBeInTheDocument(); + await waitFor(() => expect(props.onConfirmed).toHaveBeenCalledWith(refetched)); + expect(fetchSpy).toHaveBeenCalledTimes(1); + }); +}); + +describe("LanModal — disable flow (same UX, issue #197 override)", () => { + it("runs in place and flips the modal back to the restricted state", async () => { + const sys = makeSystemInfo({ lan_enabled: false }); + const gate = deferred(); + waitSpy.mockReturnValue(gate.promise); + const props = renderModal({ systemInfo: makeSystemInfo({ lan_enabled: true }) }); + const user = userEvent.setup(); + + await user.click(screen.getByRole("button", { name: "Disable LAN" })); + + expect(props.onClose).not.toHaveBeenCalled(); + expect(setLanSpy).toHaveBeenCalledWith(false); + expect(screen.getByText("Updating the LAN binding…")).toBeInTheDocument(); + + gate.resolve(sys); + await waitFor(() => expect(props.onConfirmed).toHaveBeenCalledWith(sys)); + props.rerender(); + expect(screen.getByText(/restricted to this machine/)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Enable LAN" })).toBeEnabled(); + expect(props.showToast).not.toHaveBeenCalled(); + }); + + it("observed disagreement shows the failure inline", async () => { + const stale = makeSystemInfo({ lan_enabled: true }); + waitSpy.mockResolvedValue(stale); + const user = userEvent.setup(); + const props = renderModal({ systemInfo: makeSystemInfo({ lan_enabled: true }) }); + + await user.click(screen.getByRole("button", { name: "Disable LAN" })); + + expect(await screen.findByText(/previous address is still active/)).toBeInTheDocument(); + expect(props.onConfirmed).toHaveBeenCalledWith(stale); + expect(props.showToast).not.toHaveBeenCalled(); + }); +}); + +describe("LanModal — closing", () => { + it("❌ and Escape both close the modal", async () => { + const user = userEvent.setup(); + const props = renderModal(); + + const cancel = screen.getByRole("button", { name: "Cancel" }); + await waitFor(() => expect(cancel).toHaveFocus()); + await user.keyboard("{Escape}"); + expect(props.onClose).toHaveBeenCalledTimes(1); + + await user.click(screen.getByRole("button", { name: "Close" })); + expect(props.onClose).toHaveBeenCalledTimes(2); + }); + + it("cancel closes without touching the API when idle", async () => { + const user = userEvent.setup(); + const props = renderModal(); + + await user.click(screen.getByRole("button", { name: "Cancel" })); + + expect(props.onClose).toHaveBeenCalledTimes(1); + expect(setLanSpy).not.toHaveBeenCalled(); + expect(waitSpy).not.toHaveBeenCalled(); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it("cancel mid-flow falls back to toasts when the flow completes", async () => { + const sys = makeSystemInfo({ lan_enabled: true }); + const gate = deferred(); + waitSpy.mockReturnValue(gate.promise); + const props = renderModal({ systemInfo: makeSystemInfo() }); + const user = userEvent.setup(); + + await user.click(screen.getByRole("button", { name: "Enable LAN" })); + await user.click(screen.getByRole("button", { name: "Cancel" })); + expect(props.onClose).toHaveBeenCalledTimes(1); + // App answers onClose by closing: the modal unmounts its content while + // the flow keeps running (same component instance, open false). + props.rerender(); + + gate.resolve(sys); + await waitFor(() => expect(props.onConfirmed).toHaveBeenCalledWith(sys)); + expect(props.showToast).toHaveBeenCalledWith( + "ProFiles is now reachable on the local network.", + "info" + ); + }); +}); diff --git a/src/profiles/web/src/components/LanModal.tsx b/src/profiles/web/src/components/LanModal.tsx new file mode 100644 index 0000000..f97fe0b --- /dev/null +++ b/src/profiles/web/src/components/LanModal.tsx @@ -0,0 +1,327 @@ +import { useEffect, useRef, useState } from "react"; +import { Check, ExternalLink, Wifi, WifiOff, X } from "lucide-react"; + +import { + fetchSystemInfo, + generateBarcode, + setLanEnabled, + waitForLanState, +} from "../api/client"; +import type { SystemInfo } from "../api/types"; +import { CopyableUrl } from "./CopyableUrl"; +import { useModalA11y } from "../hooks/useModalA11y"; + +export interface LanModalProps { + /** Whether the modal is shown; the flow keeps running after a close. */ + open: boolean; + systemInfo: SystemInfo | null; + showToast: (msg: string, kind?: "info" | "error") => void; + /** Called with the observed SystemInfo on both success and refetch paths. */ + onConfirmed: (sys: SystemInfo) => void; + onClose: () => void; +} + +/** Direction of an in-flight bind change. */ +type Busy = "enable" | "disable" | null; + +/** + * LAN access modal (issues #197/#198/#199) — ONE modal for both directions, + * same UX for enabling and disabling (user decision on PR #200): it reflects + * the live `systemInfo.lan_enabled` and offers the opposite action in the + * footer ("Enable LAN" / "Disable LAN"), which runs in place — the modal + * stays open through the rebind and reports the outcome inline (busy status + * or failure box) instead of closing first. No direction is passed in: the + * modal derives everything from the observed state. + * + * Layout: the QR of the IP URL sits on the LEFT and is always displayed, + * even while LAN is disabled (user decision overriding #198's original + * gating) — it reuses `generateBarcode` / `POST /api/actions/barcode` like + * the files' "Generate QR Code", no client-side dependency. The right side + * carries the live status, the "on another device" instruction (while + * enabled), the copyable hostname + IP URLs and the clickable loopback link + * (#199). ❌ (header) and Escape close at any time; footer buttons never + * disappear — the action disables while a rebind is in flight. + * + * Closing mid-flow falls back to the toast channel: the async flow keeps + * running and reports via `onConfirmed(sys)` + toasts, so App state stays in + * sync. A stale flow can never paint over a reopened modal (BarcodeModal's + * issue-#140 seq pattern). The api client is imported directly + * (ConfigEditorModal precedent); toasts flow through the injected + * `showToast` and observed state is reported via `onConfirmed(sys)`. + */ +export function LanModal({ + open, + systemInfo, + showToast, + onConfirmed, + onClose, +}: LanModalProps) { + const [busy, setBusy] = useState(null); + const [failureMessage, setFailureMessage] = useState(null); + const [qrImage, setQrImage] = useState(null); + const [qrError, setQrError] = useState(null); + const dialogRef = useRef(null); + const cancelRef = useRef(null); + /** Monotonic tag per action click — a slow stale flow must never paint + * over a reopened modal (BarcodeModal's issue-#140 pattern). */ + const seqRef = useRef(0); + /** Mirror of `open`, read by async completions to pick between inline + * state (open) and toasts (closed mid-flow). */ + const openRef = useRef(false); + + useEffect(() => { + openRef.current = open; + }, [open]); + + // A reopened modal clears transient state and invalidates any flow still + // in flight from a previous open. + useEffect(() => { + if (open) { + seqRef.current += 1; + setBusy(null); + setFailureMessage(null); + } + }, [open]); + + const port = window.location.port; + const hostnameUrl = systemInfo ? `http://${systemInfo.hostname}:${port}` : null; + const ipUrl = systemInfo ? `http://${systemInfo.ip}:${port}` : null; + const loopbackUrl = `http://127.0.0.1:${port}`; + const liveEnabled = systemInfo?.lan_enabled === true; + + // QR of the IP URL (#198): always displayed, so generate while open and + // the IP is known — the content does not depend on the bind state. + useEffect(() => { + if (!open || !ipUrl) return; + let cancelled = false; + setQrImage(null); + setQrError(null); + generateBarcode({ content: ipUrl }) + .then((res) => { + if (!cancelled) setQrImage(res.image); + }) + .catch((err) => { + if (!cancelled) + setQrError( + err instanceof Error ? err.message : "Failed to generate the QR code" + ); + }); + return () => { + cancelled = true; + }; + }, [open, ipUrl]); + + const handleDialogKeyDown = useModalA11y({ + isOpen: open, + onClose, + dialogRef, + initialFocusRef: cancelRef, + }); + + if (!open) return null; + + /** Toggle the bind in place — same UX for both directions. */ + const runToggleFlow = async (next: boolean) => { + const seq = ++seqRef.current; + setFailureMessage(null); + setBusy(next ? "enable" : "disable"); + try { + await setLanEnabled(next); + // The rebind runs after the response; observe the real outcome. + const sys = await waitForLanState(next); + if (sys) onConfirmed(sys); + if (seq !== seqRef.current) return; // modal was reopened meanwhile + setBusy(null); + if (sys?.lan_enabled === next) { + if (!openRef.current) { + showToast( + next + ? "ProFiles is now reachable on the local network." + : "ProFiles is restricted to this machine.", + "info" + ); + } + } else { + setFailureMessage( + "Failed to update LAN binding — the previous address is still active." + ); + if (!openRef.current) { + showToast( + "Failed to update LAN binding — the previous address is still active.", + "error" + ); + } + } + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to update LAN binding"; + if (seq !== seqRef.current) return; + setBusy(null); + setFailureMessage(`Failed to update LAN binding: ${msg}`); + // Refetch to restore the actual state + const sys = await fetchSystemInfo(); + onConfirmed(sys); + if (!openRef.current) { + showToast(`Failed to update LAN binding: ${msg}`, "error"); + } + } + }; + + return ( +
+
e.stopPropagation()} + className="animate-modal-in w-[480px] max-w-full rounded-2xl border border-frame-line glass-panel p-5" + > +
+ + + +

+ LAN access +

+ +
+ +
+ {/* QR column — always displayed (user decision on PR #200). */} +
+
+ {qrImage ? ( + QR code of the LAN address + ) : qrError ? ( + + {qrError} + + ) : ( + + )} +
+

+ Scan to connect from a phone. +

+
+ + {/* Status + addresses column. */} +
+ {busy !== null ? ( +

+

+ ) : failureMessage ? ( +
+ {failureMessage} +
+ ) : ( +

+ {liveEnabled ? ( + <> +

+ )} + {liveEnabled && busy === null && !failureMessage && ( +

On another device on this network, open one of these addresses:

+ )} + {hostnameUrl && ( + showToast("URL copied to clipboard.")} + onCopyError={() => showToast("Failed to copy URL.", "error")} + /> + )} + {ipUrl && ( + showToast("URL copied to clipboard.")} + onCopyError={() => showToast("Failed to copy URL.", "error")} + /> + )} + + +
+
+ + {/* Footer buttons never disappear (#197 override): the action flips + with the live state and disables while a rebind is in flight. */} +
+ + +
+
+
+ ); +} From 6820a1e993f1d29ab71da647ef88dd2c61e4c2ec Mon Sep 17 00:00:00 2001 From: falbany Date: Thu, 19 Nov 2026 00:14:26 +0100 Subject: [PATCH 3/6] =?UTF-8?q?style(web):=20LAN=20modal=20=E2=80=94=20sta?= =?UTF-8?q?tus=20moves=20to=20the=20header,=20tighter=20address=20column?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit User review on PR #200: the header now carries the live state at a glance — icon chip (Wifi on success-green when exposed, WifiOff neutral when restricted) plus "LAN Access — Reachable on this network." / "LAN Access — Restricted to the host machine." The body status line and the "On another device…" instruction are removed (that information lives in the header), and the loopback row gets its own margin so it no longer hugs the IP address row (8px → 16px). 391 web tests pass; both states verified in the real browser with the rebuilt dist. --- .../web/src/components/LanModal.test.tsx | 23 +++++-- src/profiles/web/src/components/LanModal.tsx | 67 +++++++++---------- 2 files changed, 51 insertions(+), 39 deletions(-) diff --git a/src/profiles/web/src/components/LanModal.test.tsx b/src/profiles/web/src/components/LanModal.test.tsx index e0e906e..b38c158 100644 --- a/src/profiles/web/src/components/LanModal.test.tsx +++ b/src/profiles/web/src/components/LanModal.test.tsx @@ -92,8 +92,11 @@ describe("LanModal — visibility & state display", () => { it("shows the restricted state with an Enable LAN footer button", () => { renderModal({ systemInfo: makeSystemInfo({ lan_enabled: false }) }); - expect(screen.getByText("LAN access")).toBeInTheDocument(); - expect(screen.getByText(/restricted to this machine/)).toBeInTheDocument(); + // Status lives in the header now (icon chip + full sentence). + expect( + screen.getByText("LAN Access — Restricted to the host machine.") + ).toBeInTheDocument(); + expect(screen.queryByText(/ProFiles is restricted/)).toBeNull(); expect(screen.getByRole("button", { name: "Enable LAN" })).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Cancel" })).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Close" })).toBeInTheDocument(); @@ -106,7 +109,13 @@ describe("LanModal — visibility & state display", () => { it("shows the enabled state with a Disable LAN footer button", () => { renderModal({ systemInfo: makeSystemInfo({ lan_enabled: true }) }); - expect(screen.getByText(/reachable on this network/)).toBeInTheDocument(); + expect( + screen.getByText("LAN Access — Reachable on this network.") + ).toBeInTheDocument(); + expect(screen.queryByText(/ProFiles is reachable/)).toBeNull(); + // The instruction line was removed (user review): the header + QR speak + // for themselves. + expect(screen.queryByText(/On another device on this network/)).toBeNull(); expect(screen.getByRole("button", { name: "Disable LAN" })).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Cancel" })).toBeInTheDocument(); }); @@ -152,7 +161,9 @@ describe("LanModal — enable flow (stays open)", () => { await waitFor(() => expect(props.onConfirmed).toHaveBeenCalledWith(sys)); // App answers onConfirmed by updating systemInfo → the modal reflects it. props.rerender(); - expect(screen.getByText(/reachable on this network/)).toBeInTheDocument(); + expect( + screen.getByText("LAN Access — Reachable on this network.") + ).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Disable LAN" })).toBeEnabled(); // Inline outcome replaces toasts while the modal is open. expect(props.showToast).not.toHaveBeenCalled(); @@ -204,7 +215,9 @@ describe("LanModal — disable flow (same UX, issue #197 override)", () => { gate.resolve(sys); await waitFor(() => expect(props.onConfirmed).toHaveBeenCalledWith(sys)); props.rerender(); - expect(screen.getByText(/restricted to this machine/)).toBeInTheDocument(); + expect( + screen.getByText("LAN Access — Restricted to the host machine.") + ).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Enable LAN" })).toBeEnabled(); expect(props.showToast).not.toHaveBeenCalled(); }); diff --git a/src/profiles/web/src/components/LanModal.tsx b/src/profiles/web/src/components/LanModal.tsx index f97fe0b..65ef6a4 100644 --- a/src/profiles/web/src/components/LanModal.tsx +++ b/src/profiles/web/src/components/LanModal.tsx @@ -1,5 +1,5 @@ import { useEffect, useRef, useState } from "react"; -import { Check, ExternalLink, Wifi, WifiOff, X } from "lucide-react"; +import { ExternalLink, Wifi, WifiOff, X } from "lucide-react"; import { fetchSystemInfo, @@ -36,10 +36,12 @@ type Busy = "enable" | "disable" | null; * Layout: the QR of the IP URL sits on the LEFT and is always displayed, * even while LAN is disabled (user decision overriding #198's original * gating) — it reuses `generateBarcode` / `POST /api/actions/barcode` like - * the files' "Generate QR Code", no client-side dependency. The right side - * carries the live status, the "on another device" instruction (while - * enabled), the copyable hostname + IP URLs and the clickable loopback link - * (#199). ❌ (header) and Escape close at any time; footer buttons never + * the files' "Generate QR Code", no client-side dependency. The header + * carries the live status — icon chip (Wifi / WifiOff) plus "LAN Access — + * Reachable on this network." / "LAN Access — Restricted to the host + * machine." — so the body holds only the addresses: the copyable hostname + * + IP URLs and the clickable loopback link (#199), spaced clear of the IP + * row. ❌ (header) and Escape close at any time; footer buttons never * disappear — the action disables while a rebind is in flight. * * Closing mid-flow falls back to the toast channel: the async flow keeps @@ -181,11 +183,24 @@ export function LanModal({ className="animate-modal-in w-[480px] max-w-full rounded-2xl border border-frame-line glass-panel p-5" >
- - + + {liveEnabled ? ( + + ) : ( + + )}

- LAN access + LAN Access —{" "} + {liveEnabled + ? "Reachable on this network." + : "Restricted to the host machine."}

-
+
{/* QR column — always displayed (user decision on PR #200). */}
@@ -229,9 +244,10 @@ export function LanModal({

- {/* Status + addresses column. */} -
- {busy !== null ? ( + {/* Addresses column — status lives in the header now; explicit + margins keep the loopback row clear of the IP row. */} +
+ {busy !== null && (

Updating the LAN binding…

- ) : failureMessage ? ( + )} + {busy === null && failureMessage && (
{failureMessage}
- ) : ( -

- {liveEnabled ? ( - <> -

- )} - {liveEnabled && busy === null && !failureMessage && ( -

On another device on this network, open one of these addresses:

)} {hostnameUrl && ( showToast("URL copied to clipboard.")} onCopyError={() => showToast("Failed to copy URL.", "error")} /> @@ -279,11 +277,12 @@ export function LanModal({ showToast("URL copied to clipboard.")} onCopyError={() => showToast("Failed to copy URL.", "error")} /> )} - +
From 011e60e20c08bac31882bb56b2604f52f269ee90 Mon Sep 17 00:00:00 2001 From: falbany Date: Thu, 19 Nov 2026 01:25:04 +0100 Subject: [PATCH 6/6] feat(web): Ctrl+K opens the LAN access modal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ctrl+N — the requested mnemonic — is reserved by browsers for "new window": a page handler never fires and the WebView2 accelerator table does the same on Windows, so the LAN modal lands on Ctrl+K instead (free in this shortcut table, browser-overridable like the GitHub palette). Wired in useGlobalShortcuts next to the other surface openers, guarded by the inert-while-modal rule (#55); ShortcutsModal lists it; the second deps fixture (useBarcodeMode cross-hook harness) gains the new setter. 391 web tests pass; the handler was exercised in the real browser via the page's keydown path (real-key automation was inconclusive — the review tab runs backgrounded and Chrome suppresses input to hidden tabs — same mechanism as the table's existing shortcuts). --- src/profiles/web/src/App.tsx | 3 ++- src/profiles/web/src/components/ShortcutsModal.tsx | 1 + src/profiles/web/src/hooks/useBarcodeMode.test.tsx | 1 + .../web/src/hooks/useGlobalShortcuts.test.tsx | 9 +++++++++ src/profiles/web/src/hooks/useGlobalShortcuts.ts | 11 +++++++++++ 5 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/profiles/web/src/App.tsx b/src/profiles/web/src/App.tsx index e82c169..e2ee50f 100644 --- a/src/profiles/web/src/App.tsx +++ b/src/profiles/web/src/App.tsx @@ -850,7 +850,8 @@ export default function App() { onProperties: handleProperties, onToggleTheme: () => toggleTheme({ persist: true }), setShowLogViewer, setShowShortcuts, setShowTimerModal, - setShowConfigEditor, setBarcodeMode, setShowCameraScanner, + setShowConfigEditor, setShowLanModal: setLanModalOpen, + setBarcodeMode, setShowCameraScanner, moveSelection, }); diff --git a/src/profiles/web/src/components/ShortcutsModal.tsx b/src/profiles/web/src/components/ShortcutsModal.tsx index 8a5403e..bcbbbf4 100644 --- a/src/profiles/web/src/components/ShortcutsModal.tsx +++ b/src/profiles/web/src/components/ShortcutsModal.tsx @@ -27,6 +27,7 @@ export function ShortcutsModal({ isOpen, onClose }: ShortcutsModalProps) { { key: "Ctrl + F", desc: "Focus Filter / Search field" }, { key: "Ctrl + L", desc: "Focus File List" }, { key: "Ctrl + Shift + L", desc: "Open the log viewer" }, + { key: "Ctrl + K", desc: "Open the LAN access modal" }, { key: "Ctrl + ,", desc: "Open the config editor" }, { key: "Ctrl + Shift + T", desc: "Toggle theme (Dark / Light)" }, { key: "Ctrl + B", desc: "Toggle barcode scanner mode" }, diff --git a/src/profiles/web/src/hooks/useBarcodeMode.test.tsx b/src/profiles/web/src/hooks/useBarcodeMode.test.tsx index 3bd13cf..daebc15 100644 --- a/src/profiles/web/src/hooks/useBarcodeMode.test.tsx +++ b/src/profiles/web/src/hooks/useBarcodeMode.test.tsx @@ -395,6 +395,7 @@ describe("wedge/shortcuts isolation (issue #187)", () => { setShowShortcuts: vi.fn(), setShowTimerModal: vi.fn(), setShowConfigEditor: vi.fn(), + setShowLanModal: vi.fn(), setBarcodeMode: vi.fn(), setShowCameraScanner: vi.fn(), moveSelection: vi.fn(), diff --git a/src/profiles/web/src/hooks/useGlobalShortcuts.test.tsx b/src/profiles/web/src/hooks/useGlobalShortcuts.test.tsx index 98b05f5..1c857bd 100644 --- a/src/profiles/web/src/hooks/useGlobalShortcuts.test.tsx +++ b/src/profiles/web/src/hooks/useGlobalShortcuts.test.tsx @@ -57,6 +57,7 @@ function makeDeps(overrides: Partial = {}): GlobalShortcuts setShowShortcuts: vi.fn(), setShowTimerModal: vi.fn(), setShowConfigEditor: vi.fn(), + setShowLanModal: vi.fn(), setBarcodeMode: vi.fn(), setShowCameraScanner: vi.fn(), moveSelection: vi.fn(), @@ -264,6 +265,14 @@ describe("useGlobalShortcuts", () => { expect(deps.setShowConfigEditor).toHaveBeenCalledTimes(1); expect(deps.setShowConfigEditor).toHaveBeenCalledWith(true); + press("k", { ctrlKey: true }); + expect(deps.setShowLanModal).toHaveBeenCalledTimes(1); + expect(deps.setShowLanModal).toHaveBeenCalledWith(true); + + // Ctrl+Shift+K stays free (the disambiguation convention of this table). + press("k", { ctrlKey: true, shiftKey: true }); + expect(deps.setShowLanModal).toHaveBeenCalledTimes(1); + press("?"); expect(deps.setShowShortcuts).toHaveBeenCalledTimes(1); expect(deps.setShowShortcuts).toHaveBeenCalledWith(expect.any(Function)); diff --git a/src/profiles/web/src/hooks/useGlobalShortcuts.ts b/src/profiles/web/src/hooks/useGlobalShortcuts.ts index 27de8b9..5dfa90c 100644 --- a/src/profiles/web/src/hooks/useGlobalShortcuts.ts +++ b/src/profiles/web/src/hooks/useGlobalShortcuts.ts @@ -30,6 +30,7 @@ export interface GlobalShortcutsDeps { setShowShortcuts: Dispatch>; setShowTimerModal: Dispatch>; setShowConfigEditor: Dispatch>; + setShowLanModal: Dispatch>; setBarcodeMode: Dispatch>; setShowCameraScanner: Dispatch>; // Selection — functional-updater style; App writes selectedPathRef inside the updater. @@ -154,6 +155,16 @@ export function useGlobalShortcuts(deps: GlobalShortcutsDeps): void { return; } + // Ctrl + K: Open the LAN access modal (issues #197/#198/#199) — same + // entry point as the status-bar LAN button. Ctrl+N was the requested + // mnemonic, but browsers reserve it for "new window" and a page can + // never intercept it, so the LAN modal lands on Ctrl + K. + if (e.ctrlKey && !e.shiftKey && e.key.toLowerCase() === "k") { + e.preventDefault(); + d.setShowLanModal(true); + return; + } + // Ctrl + Shift + T: Cycle theme if (e.ctrlKey && e.shiftKey && e.key.toLowerCase() === "t") { e.preventDefault();