diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e042ef2..26232e1 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -15,9 +15,9 @@ repos: - id: check-toml - id: check-added-large-files args: ['--maxkb=1024'] - # dist/ is committed on purpose (see src/profiles/web/.gitignore): - # the built frontend ships with the package, and the minified - # bundle legitimately exceeds 1 MB. + # The tracked web build output (src/profiles/web/dist/) is a + # bundled artifact regenerated by `npm run build`; its minified + # JS bundle crossed the 1 MB source-size line (issue #192 PR). exclude: ^src/profiles/web/dist/ # Ruff - Linter et formatter diff --git a/AGENTS.md b/AGENTS.md index 2f7ce2f..2a2d4d6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -47,6 +47,7 @@ Ce document définit les standards d'architecture, les principes de conception e src/profiles/ ├── core/ # Logique métier — indépendante de toute UI │ ├── actions.py # Actions domaine (lancement, ouverture, ActionResult) +│ ├── paths.py # Politique de chemins utilisateur (~/.profiles, CWD non informatifs, #191) │ ├── config/ # Sous-système configuration │ │ ├── models.py # AppConfig, MachineConfiguration, ColumnConfiguration │ │ ├── loader.py # load_config, propose_config_creation diff --git a/CHANGELOG.md b/CHANGELOG.md index de5848e..68bdaab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Per-user configuration path policy** (issue #191): launcher-style + launches (Start Menu, pinned taskbar, `.desktop` entries — any process + whose CWD is System32, the home folder, or an install/runtime directory) + no longer propose creating `.profiles` in a system directory. The + proposal targets `~/.profiles/.profiles` (next to `profiles.log`), every + later launch loads that per-user default automatically, terminal/project + launches keep their current behavior, and no code path ever proposes an + existing directory as the configuration file. New + `profiles.core.paths` module is the single source of truth for these + user-level locations. - **Windows installer polish**: the MSI now creates a desktop shortcut, asks per-user vs per-machine at install time, and shows a proper finish page ("Launch ProFiles" checkbox plus Documentation / What's new links). @@ -20,6 +30,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Branded installer**: the welcome dialog and page banners now use the ProFiles brand art (indigo-violet gradient) instead of the stock WiX look. +### Fixed + +- **Config picker mode follows the entry point** (issue #192): with no + active configuration, the editor's **Load config file…** and the file + list's **Choose configuration** buttons now open the picker in Load + mode; only the first-run auto-prompt still opens Create mode. + ### Changed - **Loopback-only by default**: the web server now binds `127.0.0.1` on launch diff --git a/README.fr.md b/README.fr.md index 6b5db7f..e57087b 100644 --- a/README.fr.md +++ b/README.fr.md @@ -220,7 +220,7 @@ ProFiles --config "/path/to/.profiles" ## 🛠 Configuration -ProFiles est piloté par un fichier **YAML** `.profiles`, recherché en remontant l'arborescence du système de fichiers. +ProFiles est piloté par un fichier **YAML** `.profiles`, recherché en remontant l'arborescence du système de fichiers. Les lancements par lanceur (menu Démarrer, dock, entrées `.desktop`) ignorent la recherche dans l'arborescence et chargent le défaut par utilisateur `~/.profiles/.profiles` s'il existe ; sans fichier trouvé, la proposition de création cible le dossier du projet — ou `~/.profiles` pour un lancement par lanceur — afin de ne jamais écrire dans un répertoire système. ```yaml # ProFiles Configuration — Format YAML diff --git a/README.md b/README.md index 4db9e1b..c658c96 100644 --- a/README.md +++ b/README.md @@ -219,7 +219,7 @@ ProFiles --config "/path/to/.profiles" ## 🛠 Configuration -ProFiles is driven by a `.profiles` **YAML** file, walking up the filesystem tree to locate it. +ProFiles is driven by a `.profiles` **YAML** file, walking up the filesystem tree to locate it. Launcher-style starts (Start Menu, dock, `.desktop` entries) skip the tree search and load the per-user default `~/.profiles/.profiles` when it exists; when nothing is found, the creation proposal targets the project folder — or `~/.profiles` for launcher starts — so nothing is ever written into a system directory. ```yaml # ProFiles Configuration — YAML Format diff --git a/docs/configuration-profile.en.md b/docs/configuration-profile.en.md index 6975f9e..27ecec2 100644 --- a/docs/configuration-profile.en.md +++ b/docs/configuration-profile.en.md @@ -12,18 +12,18 @@ ## Overview -The `.profiles` file is a **YAML-format** configuration file that customizes ProFiles's behavior. This file is searched for starting from the current working directory (CWD) and descending into subdirectories. The first match found is used. +The `.profiles` file is a **YAML-format** configuration file that customizes ProFiles's behavior. This file is searched for starting from the current working directory (CWD) and descending into subdirectories. The first match found is used. The CWD tree is skipped when the CWD carries no launch information — a Start-Menu/launcher start inherits `System32`, the home folder, or the interpreter/app install directory — and the per-user default `~/.profiles/.profiles` is loaded when it exists instead. If no `.profiles` file is found: -- In interactive mode (web UI, desktop or browser): ProFiles proposes to create a default configuration file +- In interactive mode (web UI, desktop or browser): ProFiles proposes to create a default configuration file — in the project folder for a terminal launch, in `~/.profiles` for a launcher-style launch - In headless mode: ProFiles uses default values identical to those presented in this document ## Creating the Configuration File ### Method 1: Automatic Proposal (Interactive Mode) -On first launch in interactive mode (web UI in the PyWebView shell or browser), if no `.profiles` file is found, ProFiles proposes to create a default configuration file in the current working directory. +On first launch in interactive mode (web UI in the PyWebView shell or browser), if no `.profiles` file is found, ProFiles proposes to create a default configuration file in the current working directory. When that directory carries no launch information (a Start-Menu shortcut, a launcher with an empty "Start in" field, a Finder/dock launch), the proposal targets `~/.profiles/.profiles` instead — the same folder as `profiles.log` — so nothing is ever written into a system directory, and every later launch loads that per-user default automatically. ### Method 2: Command Line diff --git a/docs/configuration-profile.fr.md b/docs/configuration-profile.fr.md index 9cc7c90..7bbdaf0 100644 --- a/docs/configuration-profile.fr.md +++ b/docs/configuration-profile.fr.md @@ -12,17 +12,17 @@ ## Vue d'ensemble -Le fichier `.profiles` est un fichier de configuration au format **YAML** qui personnalise le comportement de ProFiles. Ce fichier est recherché en commençant depuis le répertoire courant (CWD) et en descendant dans les sous-répertoires. Le premier fichier trouvé est utilisé. +Le fichier `.profiles` est un fichier de configuration au format **YAML** qui personnalise le comportement de ProFiles. Ce fichier est recherché en commençant depuis le répertoire courant (CWD) et en descendant dans les sous-répertoires. Le premier fichier trouvé est utilisé. La recherche dans l'arborescence du CWD est ignorée lorsque le CWD ne porte aucune information de lancement — un démarrage via le menu Démarrer/ lanceur hérite de `System32`, du dossier personnel ou du répertoire d'installation de l'interpréteur/application — et le défaut par utilisateur `~/.profiles/.profiles` est chargé s'il existe. Si aucun fichier `.profiles` n'est trouvé : -- En mode interactif (interface web, bureau ou navigateur) : ProFiles propose de créer un fichier de configuration par défaut +- En mode interactif (interface web, bureau ou navigateur) : ProFiles propose de créer un fichier de configuration par défaut — dans le dossier du projet pour un lancement en terminal, dans `~/.profiles` pour un lancement par lanceur - En mode headless : ProFiles utilise des valeurs par défaut identiques à celles présentées dans ce document ## Création du fichier de configuration ### Méthode 1 : Proposition automatique (mode interactif) -Au premier lancement en mode interactif (interface web dans la fenêtre PyWebView ou dans le navigateur), si aucun fichier `.profiles` n'est trouvé, ProFiles propose de créer un fichier de configuration par défaut dans le répertoire courant. +Au premier lancement en mode interactif (interface web dans la fenêtre PyWebView ou dans le navigateur), si aucun fichier `.profiles` n'est trouvé, ProFiles propose de créer un fichier de configuration par défaut dans le répertoire courant. Lorsque ce répertoire ne porte aucune information de lancement (raccourci du menu Démarrer, lanceur avec un champ « Démarrer dans » vide, lancement depuis le Finder/dock), la proposition cible `~/.profiles/.profiles` — le même dossier que `profiles.log` — afin de ne jamais écrire dans un répertoire système ; chaque lancement suivant charge automatiquement ce défaut par utilisateur. ### Méthode 2 : Commande ligne de commande diff --git a/docs/installation-guide.en.md b/docs/installation-guide.en.md index fe4babd..7e3937f 100644 --- a/docs/installation-guide.en.md +++ b/docs/installation-guide.en.md @@ -256,6 +256,13 @@ python -m profiles --init This creates a `.profiles` file in the current directory with default settings. +You can also skip this step: on the **first launch from the Start Menu** (or +any launcher that runs without a project folder), ProFiles proposes to create +the configuration at `~/.profiles/.profiles` — the same folder as +`profiles.log` — and every later launch loads that per-user default +automatically. Launches from a terminal inside a project keep proposing the +project-local `.profiles`. + ### 2. Customize configuration Edit the `.profiles` file to adapt: diff --git a/src/profiles/app.py b/src/profiles/app.py index f09ac9e..53bbc4c 100644 --- a/src/profiles/app.py +++ b/src/profiles/app.py @@ -17,6 +17,7 @@ from profiles.core import AppConfig, actions, load_config from profiles.core.config.io.yaml_io import PRIMARY_CONFIG_NAME from profiles.core.environment.system import format_user_host +from profiles.core.paths import default_config_path from profiles.core.processing.scanner import scan_and_process from profiles.core.telemetry import events from profiles.core.telemetry.diagnostics import ( @@ -172,8 +173,8 @@ def _setup_logging(self, level: int | str = logging.INFO) -> logging.Logger: def _resolve_startup_config( self, explicit: Path | None, - ) -> tuple[Path | None, bool]: - """Return (config_path, config_is_missing). + ) -> tuple[Path | None, bool, Path]: + """Return (config_path, config_is_missing, launch_default). Uses the launch resolution logic to determine which config file should be used for this launch. On macOS a double-clicked @@ -182,11 +183,20 @@ def _resolve_startup_config( context (issue #188). The context source is remembered for the busy-port handoff decision. + The third element is the launch-default target from + :func:`profiles.core.paths.default_config_path` — where a + missing configuration would be proposed (``~/.profiles/.profiles`` + for launcher-style launches, the project folder for terminal + launches; issue #191). The defaults AppConfig carries it when + nothing was resolved, so the server and UI pre-fill the right + path without any server-specific override. + Args: explicit: Value of --config flag, if any. Returns: - Tuple of (resolved config path or None, whether it's missing). + Tuple of (resolved config path or None, whether it's missing, + default proposal target). """ documents: tuple[Path, ...] = () if not self._headless: @@ -198,12 +208,15 @@ def _resolve_startup_config( self._launch_source = ctx.source resolved = resolve_config_path(ctx) is_missing = resolved is not None and not resolved.exists() - return resolved, is_missing + launch_default = default_config_path(ctx.working_directory) + return resolved, is_missing, launch_default def _load_configuration(self, logger: logging.Logger) -> AppConfig: """Load the application configuration. Uses launch-time resolution to determine which config file to use. + When nothing resolves, the defaults are bound to the launch-default + target (``~/.profiles/.profiles`` for launcher starts, issue #191). If no config is found and not in server-only mode, offers to create a starter configuration. @@ -217,22 +230,23 @@ def _load_configuration(self, logger: logging.Logger) -> AppConfig: SystemExit(1) if configuration is invalid. """ # Use launch resolution instead of bare self._config_path - resolved, is_missing = self._resolve_startup_config(self._config_path) + resolved, is_missing, launch_default = self._resolve_startup_config(self._config_path) if is_missing: events.config_invalid(logger, error=f"Config file not found: {resolved}") print(f"ERROR: Configuration file not found: {resolved}", file=sys.stderr) sys.exit(1) + effective_path = resolved if resolved is not None else launch_default try: - config = load_config(resolved) + config = load_config(effective_path) events.config_loaded( logger, path=str(resolved) if resolved else "auto", mode="launch resolution" if resolved else "auto", release=config.release, ) - self._config_path = resolved # Update for later use + self._config_path = effective_path # Update for later use return config except (OSError, ValueError) as exc: events.config_invalid(logger, error=str(exc)) diff --git a/src/profiles/core/AGENTS.md b/src/profiles/core/AGENTS.md index ebf8076..5a45097 100644 --- a/src/profiles/core/AGENTS.md +++ b/src/profiles/core/AGENTS.md @@ -15,6 +15,7 @@ owns a single responsibility: | Sub-package / file | Responsibility (SRP) | | ------------------------ | ------------------------------------------------------------------------------------ | +| `paths.py` | Per-user path policy: `~/.profiles` data dir, config default, uninformative-directory tests (issue #191) | | `config/__init__.py` | Single point of egress for the configuration subsystem (high-level API) | | `config/models.py` | Pure dataclasses (`AppConfig`, `MachineConfiguration`, `ColumnConfiguration`, `HookSpec`, `WorkflowStep`) | | `config/service.py` | Domain operations over `AppConfig` — find, merge, auto-select directories | diff --git a/src/profiles/core/__init__.py b/src/profiles/core/__init__.py index 808e1d6..e6d83ea 100644 --- a/src/profiles/core/__init__.py +++ b/src/profiles/core/__init__.py @@ -46,6 +46,14 @@ parse_hook_entries, run_hooks_for_file, ) +from profiles.core.paths import ( + default_config_path, + default_search_directory, + find_user_config, + is_uninformative_directory, + user_config_path, + user_data_dir, +) from profiles.core.processing import ( ScannedFile, ScannedFileDynamic, @@ -90,6 +98,13 @@ "scan_and_process", # Template "STARTER_CONFIG_TEMPLATE", + # Per-user path policy (issue #191) + "default_config_path", + "default_search_directory", + "find_user_config", + "is_uninformative_directory", + "user_config_path", + "user_data_dir", # System "SystemInfo", "collect_system_info", diff --git a/src/profiles/core/config/io/yaml_io.py b/src/profiles/core/config/io/yaml_io.py index ac1734c..6c6239c 100644 --- a/src/profiles/core/config/io/yaml_io.py +++ b/src/profiles/core/config/io/yaml_io.py @@ -23,6 +23,18 @@ #: Every accepted configuration file name, primary first. CONFIG_FILE_NAMES: tuple[str, ...] = (PRIMARY_CONFIG_NAME, *FALLBACK_CONFIG_NAMES) + +def is_config_file_name(name: str) -> bool: + """True when a file *name* matches the accepted config whitelist. + + Case-insensitive on purpose: the save-as endpoint accepts + ``BACKUP.PROFILES`` (issue #95 wave), so every apply-path gate must + re-accept what it wrote. Shared by the server's config-name check and + the desktop odoc applier's skip guard (issue #193). + """ + return name.lower().endswith(CONFIG_FILE_NAMES) + + _yaml = YAML() _yaml.preserve_quotes = True @@ -268,6 +280,7 @@ def find_config_file( "PRIMARY_CONFIG_NAME", "content_hash", "find_config_file", + "is_config_file_name", "read_yaml", "write_text_atomic", "write_value", diff --git a/src/profiles/core/config/loader.py b/src/profiles/core/config/loader.py index 2fc29b3..c065069 100644 --- a/src/profiles/core/config/loader.py +++ b/src/profiles/core/config/loader.py @@ -11,21 +11,32 @@ from pathlib import Path from profiles.core.config.io.yaml_io import ( - PRIMARY_CONFIG_NAME, find_config_file, ) from profiles.core.config.models import AppConfig from profiles.core.config.reader import ConfigReader +from profiles.core.paths import ( + default_config_path, + default_search_directory, + find_user_config, + is_uninformative_directory, + user_data_dir, +) def load_config(config_path: Path | str | None = None) -> AppConfig: """Load the application configuration. - Searches the folder tree for a configuration file starting from - the working directory (canonical ``.profiles`` names first, then any - ``*.profiles``-style file, ascending). If *config_path* is provided, - uses that directly. Falls back to ``.profiles.yaml`` (backward - compatibility) when no ``.profiles`` file is found, then to defaults. + With *config_path*, uses that directly. Otherwise searches the folder + tree for a configuration file starting from the working directory + (canonical ``.profiles`` names first, then any ``*.profiles``-style + file, ascending) — skipping the search when the working directory is + uninformative (``System32``, home, interpreter/app install roots; + issue #191). When no project config is found, the per-user default + ``~/.profiles/.profiles`` is loaded when it exists; failing that, + defaults are returned bound to :func:`default_config_path` (the + per-user path for launcher-style launches, the project folder for + terminal launches). Args: config_path: Optional explicit path to the configuration file. @@ -36,19 +47,32 @@ def load_config(config_path: Path | str | None = None) -> AppConfig: if config_path is not None: return ConfigReader(config_path).load() - found = find_config_file() - if found is not None: - return ConfigReader(found).load() + try: + start = Path.cwd() + except OSError: + start = None + + if not is_uninformative_directory(start): + found = find_config_file() + if found is not None: + return ConfigReader(found).load() - # No .profiles found anywhere — use defaults from the primary path - return ConfigReader(Path.cwd() / PRIMARY_CONFIG_NAME).load() + user_config = find_user_config() + if user_config is not None: + return ConfigReader(user_config).load() + + # No .profiles found anywhere — use defaults bound to the policy-chosen + # default path (~/.profiles/.profiles for launcher starts). + return ConfigReader(default_config_path(start)).load() def propose_config_creation() -> bool: """Propose to create a default ``.profiles`` configuration file. Prompts the user in CLI mode to create a default configuration - file in the current working directory. + file at :func:`default_config_path` (the project folder for a + terminal launch, ``~/.profiles/.profiles`` for launcher-style + launches; issue #191). Returns: ``True`` if user accepts and the file is created, ``False`` otherwise. @@ -68,14 +92,28 @@ def propose_config_creation() -> bool: return False if response in ("y", "yes"): - target = Path.cwd() / PRIMARY_CONFIG_NAME + target = default_config_path() if target.exists(): print(f"Warning: {target} already exists. Creation skipped.") return False + try: + # The per-user data directory may not exist yet on a fresh + # install; write_starter_config requires an existing parent. + target.parent.mkdir(parents=True, exist_ok=True) + except OSError as exc: + print(f"\n✗ Error creating configuration directory: {exc}", file=sys.stderr) + return False + from profiles.core.actions import ActionStatus, write_starter_config - result = write_starter_config(target) + # Same rule as profiles.launch.creation (#191): a normal project + # target scans itself; the per-user data directory only holds logs + # and configs, so the template falls back to the policy default. + search_dir = ( + default_search_directory() if target.parent == user_data_dir() else target.parent + ) + result = write_starter_config(target, cwd=search_dir) if result.status is ActionStatus.SUCCESS: print(f"\n✓ Default configuration created: {target}") print("\nYou can now customize this file to suit your needs.") diff --git a/src/profiles/core/config/template.py b/src/profiles/core/config/template.py index cb99744..a9ad446 100644 --- a/src/profiles/core/config/template.py +++ b/src/profiles/core/config/template.py @@ -32,9 +32,15 @@ # names win first (".profiles", then ".profiles.yaml"/".profiles.yml"); # when none of them exists anywhere, any "*.profiles"-style file (e.g. # "a.profiles", "b.profiles") is accepted — several matches are sorted -# ascending and the first one is launched. If nothing is found at all, -# defaults are used (identical to this starter). An explicit file can -# be passed with --config (see CLI FLAGS). +# ascending and the first one is launched. The CWD tree is skipped when +# the CWD carries no launch information (System32, the home folder or +# the interpreter/app install root — Start-Menu and launcher starts); +# in that case, and whenever the tree search finds nothing, the +# per-user default "~/.profiles/.profiles" is loaded when it exists +# (issue #191). If nothing is found at all, defaults are used and a +# starter is proposed at the project folder, or at +# "~/.profiles/.profiles" for launcher-style starts. An explicit file +# can be passed with --config (see CLI FLAGS). # # SYNTAX # * YAML format; all keys are case-insensitive. diff --git a/src/profiles/core/paths.py b/src/profiles/core/paths.py new file mode 100644 index 0000000..0b0b51c --- /dev/null +++ b/src/profiles/core/paths.py @@ -0,0 +1,222 @@ +"""Per-user path policy — one source of truth for user-level locations. + +Single Responsibility: decide where ProFiles keeps per-user data (the +``~/.profiles`` folder shared by logs and the default configuration) and +which directories carry no information about the user's launch location. + +Pure functions only: nothing here touches the filesystem beyond +existence/metadata checks, and nothing mutates state. + +Why this module exists (issue #191): a Start-Menu shortcut with an empty +"Start in" field runs the process with ``CWD = %SystemRoot%\\System32``, +and a launcher whose CWD is the home folder collides with the +``~/.profiles`` **log directory**. Both facts are path-policy concerns, +so every consumer (launch resolution, config loader, server state, +logger defaults) asks here instead of re-deriving them. +""" + +from __future__ import annotations + +import os +import sys +from pathlib import Path + +from profiles.core.config.io.yaml_io import CONFIG_FILE_NAMES + +#: Name of the per-user data directory (logs + default config). +USER_DATA_DIRNAME = ".profiles" + + +def user_data_dir() -> Path: + """Return the per-user data directory: ``~/.profiles``. + + Holds ``profiles.log`` and the per-user default configuration, so + both can never drift apart. + + Returns: + Absolute path under the user's home folder. + + Raises: + RuntimeError: When the home directory cannot be determined + (same failure mode as :meth:`pathlib.Path.home`, which the + logger already accepted before this module existed). + """ + return Path.home() / USER_DATA_DIRNAME + + +def user_config_path() -> Path: + """Return the per-user default configuration path: ``~/.profiles/.profiles``. + + Returns: + Absolute path to the canonical primary config name inside + :func:`user_data_dir`. + """ + return user_data_dir() / CONFIG_FILE_NAMES[0] + + +def find_user_config() -> Path | None: + """Return the per-user default configuration file, when one exists. + + Only the canonical names are checked, in priority order, directly + inside :func:`user_data_dir` (depth 0, no wildcard search) — the + per-user folder is not a project tree to walk. + + Returns: + The first existing config **file**, or ``None``. + """ + data_dir = user_data_dir() + for name in CONFIG_FILE_NAMES: + candidate = data_dir / name + try: + if candidate.is_file(): + return candidate + except OSError: + continue + return None + + +def is_uninformative_directory(path: Path | None) -> bool: + """True when *path* says nothing about the user's launch location. + + A directory is uninformative when it was chosen by the OS or the + runtime rather than by the user: + + * ``None`` or an unresolvable path; + * a filesystem/drive root (``/``, ``C:\\``); + * the home folder itself (a launcher CWD, and colliding with the + ``~/.profiles`` data directory); + * anything inside the Python runtime prefix (idle interpreter + launches); + * anything inside the running executable's directory (packaged-app + install root); + * on Windows-style environments: anything inside + ``%SystemRoot%``/``%windir%`` (covers ``System32``, ``SysWOW64``) + or ``%ProgramFiles%``/``%ProgramFiles(x86)%``. The variables are + consulted whenever they are set, so tests can monkeypatch them on + any platform and real non-Windows environments (where they are + unset) are unaffected. + + Args: + path: Candidate directory (``None`` allowed). + + Returns: + ``True`` when the directory must not be used to infer a project + location or to host a proposed configuration file. + """ + if path is None: + return True + + try: + resolved = path.resolve() + except OSError: + return True + + # Filesystem / drive root. + if resolved.parent == resolved: + return True + + # Home folder itself (launchers often start there; it also hosts the + # ~/.profiles data directory, so it can never host a config file). + try: + if resolved == Path.home().resolve(): + return True + except (OSError, RuntimeError): + pass + + # Python runtime prefix (venv / system interpreter locations). + try: + if resolved.is_relative_to(Path(sys.prefix).resolve()): + return True + except OSError: + return True + + # Running executable's directory (packaged-app install root). + try: + exe_dir = Path(sys.executable).resolve().parent + if resolved.is_relative_to(exe_dir): + return True + except OSError: + pass + + # Windows system / program locations, via env vars (see docstring). + for var in ("SystemRoot", "windir", "ProgramFiles", "ProgramFiles(x86)"): + value = os.environ.get(var) + if not value: + continue + try: + base = Path(value).resolve() + except OSError: + continue + if resolved.is_relative_to(base): + return True + + return False + + +def _effective_start(start: Path | None) -> Path | None: + """Resolve the effective start directory: *start*, or the process CWD. + + Returns ``None`` when both are unavailable (exotic service + environments where even ``Path.cwd()`` raises). + """ + if start is not None: + return start + try: + return Path.cwd() + except OSError: + return None + + +def default_config_path(start: Path | None = None) -> Path: + """Return the path a missing configuration should be proposed at. + + Args: + start: Directory the launch happened in (default: the process + CWD). May be ``None`` when the CWD is unreadable. + + Returns: + ``start / ".profiles"`` for an informative *start*, otherwise the + per-user :func:`user_config_path`. When the project candidate + exists and is a **directory** (the ``CWD == home`` collision with + the ``~/.profiles`` data folder), the per-user path is returned + instead: the app never proposes a directory as its config file. + """ + start = _effective_start(start) + if start is None or is_uninformative_directory(start): + return user_config_path() + + candidate = start / CONFIG_FILE_NAMES[0] + try: + if candidate.exists() and candidate.is_dir(): + return user_config_path() + except OSError: + pass + return candidate + + +def default_search_directory(start: Path | None = None) -> Path: + """Return the directory a starter configuration should scan. + + Args: + start: Directory the launch happened in (default: the process + CWD). May be ``None`` when the CWD is unreadable. + + Returns: + *start* when informative; the home folder otherwise (a launcher + start must never scan ``System32`` or the interpreter's folder). + """ + start = _effective_start(start) + if start is None or is_uninformative_directory(start): + return Path.home() + return start + + +__all__ = [ + "USER_DATA_DIRNAME", + "default_config_path", + "default_search_directory", + "find_user_config", + "is_uninformative_directory", + "user_config_path", + "user_data_dir", +] diff --git a/src/profiles/core/telemetry/diagnostics.py b/src/profiles/core/telemetry/diagnostics.py index e2638ce..358039b 100644 --- a/src/profiles/core/telemetry/diagnostics.py +++ b/src/profiles/core/telemetry/diagnostics.py @@ -270,11 +270,17 @@ def default_log_path() -> Path: ``CWD=/`` (read-only on macOS), so a CWD-relative log path crashes with ``OSError: [Errno 30]`` at the first log write. + Delegates to :func:`profiles.core.paths.user_data_dir` so the log + location and the per-user default configuration (issue #191) share + one source of truth and cannot drift apart. + Returns: Absolute path under the user folder in a dedicated ``.profiles`` directory (matching the ``.profiles`` config-file convention). """ - return Path.home() / ".profiles" / "profiles.log" + from profiles.core.paths import user_data_dir + + return user_data_dir() / "profiles.log" def configure_logger( diff --git a/src/profiles/desktop/launcher.py b/src/profiles/desktop/launcher.py index ea65b4c..d2bec11 100644 --- a/src/profiles/desktop/launcher.py +++ b/src/profiles/desktop/launcher.py @@ -70,14 +70,24 @@ def _make_document_applier(state: ServerState) -> Callable[[Sequence[str]], None Shares :func:`apply_config_from_disk` with ``POST /api/instance/handoff`` so a double-click landing on the running window is launch-equivalent, and buffers the same UI event the frontend toast poll renders - (issue #188). A rejected file degrades to a failure notification — - the callback must never raise into the GUI event loop. + (issue #188). Documents whose name is not a config name are skipped + exactly like launch resolution skips them (issue #193): macOS also + delivers the opened *folder* — or any non-config document — as an + odoc path, and reporting it as a failed config apply produced a + spurious failure toast while the launch had already resolved the + folder's ``a.profiles``-style config. A rejected config-named file + still degrades to a failure notification — the callback must never + raise into the GUI event loop. """ + from profiles.core.config.io.yaml_io import is_config_file_name from profiles.server.routes.config import apply_config_from_disk def apply_documents(paths: Sequence[str]) -> None: for raw in paths: config_path = Path(raw).expanduser().resolve() + if not is_config_file_name(config_path.name): + logger.debug("Skipping non-config odoc document: %s", config_path) + continue try: apply_config_from_disk(state, config_path) except HTTPException as exc: diff --git a/src/profiles/launch/context.py b/src/profiles/launch/context.py index 5d40e46..c535b69 100644 --- a/src/profiles/launch/context.py +++ b/src/profiles/launch/context.py @@ -34,6 +34,7 @@ FALLBACK_CONFIG_NAMES, PRIMARY_CONFIG_NAME, ) +from profiles.core.paths import is_uninformative_directory #: Canonical primary configuration file name (``.profiles``). CONFIG_SUFFIX = PRIMARY_CONFIG_NAME @@ -57,18 +58,18 @@ def cwd_is_uninformative(cwd: Path | None) -> bool: """True when *cwd* says nothing about the user's launch location. + Delegates to + :func:`profiles.core.paths.is_uninformative_directory` so launch + detection and the per-user path policy cannot drift (issue #191): GUI-style launches (double-click / Finder) typically inherit - ``CWD == "/"`` or an idle Python-runtime directory; only then is the - Finder probe worth consulting for the real launch folder, and only - then is the macOS odoc capture (:mod:`profiles.desktop.appkit_events`) + ``CWD == "/"`` or an idle Python-runtime directory, and launcher + shortcuts (Start Menu, ``.desktop``) inherit ``System32`` or the + home folder — in all those cases the CWD is discarded, the Finder + probe (macOS) is worth consulting for the real launch folder, and + the macOS odoc capture (:mod:`profiles.desktop.appkit_events`) is worth its bounded wait. """ - if cwd is None or cwd == Path("/"): - return True - try: - return cwd.resolve().is_relative_to(Path(sys.prefix).resolve()) - except OSError: - return True + return is_uninformative_directory(cwd) @dataclass(frozen=True) diff --git a/src/profiles/launch/creation.py b/src/profiles/launch/creation.py index fbdc984..e50ecf4 100644 --- a/src/profiles/launch/creation.py +++ b/src/profiles/launch/creation.py @@ -17,6 +17,7 @@ from profiles.core.actions import ActionStatus from profiles.core.actions import write_starter_config as _write_starter +from profiles.core.paths import default_search_directory, user_data_dir @dataclass(frozen=True) @@ -28,12 +29,38 @@ class CreationResult: message: str -def propose_creation(target: Path) -> CreationResult: +def _resolve_search_dir(target: Path, search_dir: Path | str | None) -> Path: + """Return the directory the starter's ``search_dir`` should point at. + + Explicit *search_dir* wins. Otherwise a normal project directory + scans itself, while the per-user data directory falls back to + :func:`default_search_directory` — that folder only holds logs and + configs, so scanning it is useless (issue #191). + """ + if search_dir is not None: + return Path(search_dir) + try: + if target.resolve() == user_data_dir().resolve(): + return default_search_directory() + except OSError: + return target + return target + + +def propose_creation( + target: Path, + *, + search_dir: Path | str | None = None, +) -> CreationResult: """Offer to write a starter ``.profiles`` at *target*. Args: target: Directory where the starter should be written. The file will be created as ``target / ".profiles"``. + search_dir: Directory the starter's ``search_dir`` template + placeholder points at. Defaults to *target* itself, except + when *target* is the per-user data directory (``~/.profiles``), + which scans :func:`default_search_directory` instead. Returns: A :class:`CreationResult` with the outcome. Never raises: every @@ -64,8 +91,9 @@ def propose_creation(target: Path) -> CreationResult: message=f"Could not create directory {config_path.parent}: {exc}", ) - # Delegate to the existing domain action. - result = _write_starter(config_path) + # Delegate to the existing domain action, carrying the resolved + # search_dir so a launcher-created starter never scans System32. + result = _write_starter(config_path, cwd=_resolve_search_dir(target, search_dir)) if result.status == ActionStatus.SUCCESS: return CreationResult( diff --git a/src/profiles/launch/resolution.py b/src/profiles/launch/resolution.py index a54a39b..561862f 100644 --- a/src/profiles/launch/resolution.py +++ b/src/profiles/launch/resolution.py @@ -7,11 +7,15 @@ returns a path (or ``None``). It never reads a file, never prompts, and never writes — those are :mod:`profiles.launch.creation`'s jobs. -Resolution order (spec §1): +Resolution order (spec §1, issue #191): 1. ``--config`` when supplied — explicit always wins 2. a ``*.profiles`` document opened by the user - 3. a ``.profiles`` found by searching the working directory, 5 deep - 4. ``None`` — the caller decides whether to propose creating one + 3. a ``.profiles`` found by searching the working directory, 5 deep — + only when the working directory is informative (System32, the + home folder, the interpreter/app install root are skipped: they + say nothing about the user's project) + 4. the per-user default ``~/.profiles/.profiles`` when it exists + 5. ``None`` — the caller decides whether to propose creating one """ from __future__ import annotations @@ -19,6 +23,7 @@ from pathlib import Path from profiles.core.config.io.yaml_io import CONFIG_FILE_NAMES, find_config_file +from profiles.core.paths import find_user_config, is_uninformative_directory from profiles.launch.context import LaunchContext #: How many directory levels to search. Matches ``find_config_file``'s @@ -46,6 +51,13 @@ def resolve_config_path(ctx: LaunchContext) -> Path | None: an existence check: reporting a typo'd path is the reader's job, and silently substituting a different file would be worse than the error the user is about to see. + + The working-directory tree search is skipped for uninformative + directories (issue #191): a Start-Menu launch must not walk + ``System32`` looking for a config, and a home-CWD launch must not + walk the whole user profile. The per-user default + (``~/.profiles/.profiles``) is the final fallback, so a launcher + start picks up the config created by an earlier session. """ if ctx.explicit_config is not None: return ctx.explicit_config @@ -55,10 +67,15 @@ def resolve_config_path(ctx: LaunchContext) -> Path | None: return document start = ctx.working_directory or Path.cwd() - try: - return find_config_file(start, max_depth=_CONFIG_SEARCH_DEPTH) - except OSError: - return None + if not is_uninformative_directory(start): + try: + found = find_config_file(start, max_depth=_CONFIG_SEARCH_DEPTH) + except OSError: + found = None + if found is not None: + return found + + return find_user_config() __all__ = ["resolve_config_path"] diff --git a/src/profiles/server/routes/config.py b/src/profiles/server/routes/config.py index ee92749..421a9c4 100644 --- a/src/profiles/server/routes/config.py +++ b/src/profiles/server/routes/config.py @@ -8,10 +8,11 @@ from pydantic import BaseModel from profiles.core.config.diagnostics import collect_config_issues -from profiles.core.config.io.yaml_io import CONFIG_FILE_NAMES, content_hash, write_text_atomic +from profiles.core.config.io.yaml_io import content_hash, is_config_file_name, write_text_atomic from profiles.core.config.models import AppConfig from profiles.core.config.reader import ConfigReader from profiles.core.config.template import STARTER_CONFIG_TEMPLATE +from profiles.core.paths import default_search_directory from profiles.launch.creation import propose_creation from profiles.server.state import ServerState from profiles.utils.path_utils import normalize_user_path @@ -68,9 +69,11 @@ def _is_config_path(path: Path) -> bool: ``BACKUP.PROFILES`` (its whitelist checks ``filename.lower()``), so the apply step that re-reads what was just written must accept it too — a case-sensitive comparison here turned a successful save-as into a 400 - with the file already on disk (branch review, issue #95 wave). + with the file already on disk (branch review, issue #95 wave). The + predicate lives in the core so the desktop odoc applier's skip guard + (issue #193) stays in lockstep with what this apply step accepts. """ - return path.name.lower().endswith(CONFIG_FILE_NAMES) + return is_config_file_name(path.name) def _is_safe_filename(filename: str) -> bool: @@ -105,7 +108,10 @@ def _config_response(state: ServerState) -> dict: elif available_dirs: state.active_directory = Path(available_dirs[0]) else: - state.active_directory = Path.cwd() + # Empty-config fallback (issue #191): a launcher-style start + # must pre-fill the picker with the home folder, never + # System32 or the interpreter directory the CWD happens to be. + state.active_directory = default_search_directory() if not available_dirs: available_dirs = [str(state.active_directory)] @@ -290,7 +296,13 @@ async def create_config_endpoint(payload: CreateConfigRequest, request: Request) status_code=400, detail=f"Configuration already exists at {target_config}" ) - result = propose_creation(target_dir) + result = propose_creation( + target_dir, + # The starter's search_dir: the session's active directory, or the + # policy default (home for launcher-style starts) — never the + # process CWD, which a Start-Menu launch puts in System32 (#191). + search_dir=state.active_directory or default_search_directory(), + ) if result.status in {"SKIPPED", "FAILED"}: raise HTTPException(status_code=400, detail=result.message) @@ -313,7 +325,10 @@ async def template_config_endpoint(request: Request) -> dict: directory so the rendered draft scans where the session points. """ state: ServerState = request.app.state.server_state - cwd = str(state.active_directory) if state.active_directory else str(Path.cwd()) + # default_search_directory over a bare CWD (issue #191): an unset + # active directory under a launcher start resolves to the home folder + # instead of System32 / the interpreter directory. + cwd = str(default_search_directory(state.active_directory)) return { "content": STARTER_CONFIG_TEMPLATE.format(cwd=cwd), "filename": ".profiles", diff --git a/src/profiles/server/state.py b/src/profiles/server/state.py index 1d7870c..02d47f9 100644 --- a/src/profiles/server/state.py +++ b/src/profiles/server/state.py @@ -7,8 +7,9 @@ from pathlib import Path from typing import Any, Protocol -from profiles.core.config.io.yaml_io import PRIMARY_CONFIG_NAME, find_config_file +from profiles.core.config.io.yaml_io import find_config_file from profiles.core.config.models import AppConfig +from profiles.core.paths import default_config_path from profiles.core.telemetry import events _MAX_EXTERNAL_EVENTS = 50 @@ -68,12 +69,23 @@ def active_config_path(self) -> Path: Resolution order mirrors launch-time resolution: any explicit ``config_path`` recorded after loading, then the path carried by the loaded :class:`AppConfig`, then a core search of the CWD - subtree, and finally the canonical primary name in the CWD. + subtree, and finally :func:`default_config_path` (the per-user + ``~/.profiles/.profiles`` for launcher-style launches, the + project folder otherwise; issue #191). An existing **directory** + is never returned as the config file — the ``CWD == home`` + collision with the ``~/.profiles`` log directory falls through to + :func:`default_config_path` instead. """ config_path = self.config_path or getattr(self.config, "config_path", None) if config_path is None: - config_path = find_config_file() or Path.cwd() / PRIMARY_CONFIG_NAME - return Path(config_path) + config_path = find_config_file() or default_config_path() + resolved = Path(config_path) + try: + if resolved.is_dir(): + return default_config_path() + except OSError: + pass + return resolved def record_external_event( self, kind: str, message: str, *, config_applied: bool = False diff --git a/src/profiles/web/dist/assets/index-Dsvw1NQU.js b/src/profiles/web/dist/assets/index-DbQBfiWD.js similarity index 97% rename from src/profiles/web/dist/assets/index-Dsvw1NQU.js rename to src/profiles/web/dist/assets/index-DbQBfiWD.js index cdbbcb7..5fb4834 100644 --- a/src/profiles/web/dist/assets/index-Dsvw1NQU.js +++ b/src/profiles/web/dist/assets/index-DbQBfiWD.js @@ -416,7 +416,7 @@ Loading the starter template will discard them.`,confirmLabel:"Replace",cancelLa Reload disk version: discard your edits and load the file as it is on disk. Overwrite anyway: save your edits and replace the file's current content.`,confirmLabel:"Overwrite anyway",cancelLabel:"Reload disk version",onConfirm:()=>F==null?void 0:F.resolve(!0),onCancel:()=>F==null?void 0:F.resolve(!1)}),y.jsx(r8,{open:Z!==null,onCancel:()=>Z==null?void 0:Z.resolve(null),onConfirm:ce=>Z==null?void 0:Z.resolve(ce)})]})}function u8({position:n,onClose:e,onLaunch:t,onLaunchWithArgs:i,onReveal:l,onOpenFolder:o,onOpenTerminal:a,onScanDirectory:c,onFilterFolder:f,onFilterExtension:d,onCopyPath:m,onCopyFilename:g,onCopyUri:b,onComputeHash:v,onVerifyHash:w,onProperties:S,onClearFile:C,onGenerateBarcode:O,showToast:_}){const[M,P]=E.useState(!1),[L,D]=E.useState(""),j=E.useRef(null),H=E.useRef(null),Z=E.useRef(null),[I,F]=E.useState(null);if(E.useEffect(()=>{var Y;M&&((Y=H.current)==null||Y.showModal())},[M]),E.useLayoutEffect(()=>{if(!n){F(null);return}const Y=()=>{const T=j.current;if(!T)return;const he=T.getBoundingClientRect(),ye=8;F({left:Math.max(ye,Math.min(n.x,window.innerWidth-he.width-ye)),top:Math.max(ye,Math.min(n.y,window.innerHeight-he.height-ye))})};return Y(),window.addEventListener("resize",Y),()=>window.removeEventListener("resize",Y)},[n]),E.useEffect(()=>{if(!n)return;Z.current=document.activeElement instanceof HTMLElement?document.activeElement:null;const Y=window.requestAnimationFrame(()=>{var T,he;(he=(T=j.current)==null?void 0:T.querySelector("[role='menuitem']"))==null||he.focus()});return()=>{var T;window.cancelAnimationFrame(Y),(T=Z.current)==null||T.focus()}},[n]),!n)return null;const{file:A,x:ne,y:ae}=n,ie=()=>{i(A,L),P(!1),e()},$=Y=>{const T=Y.lastIndexOf(".");return T!==-1?Y.slice(T):""},oe=Y=>{const T=Math.max(Y.lastIndexOf("/"),Y.lastIndexOf("\\"));return T!==-1?Y.slice(0,T):Y},J=Y=>{const T=Math.max(Y.lastIndexOf("/"),Y.lastIndexOf("\\"));return T!==-1?Y.slice(0,T):""};return y.jsxs(y.Fragment,{children:[y.jsx("div",{className:"fixed inset-0 z-[calc(var(--z-context-menu)-1)]",onClick:e,onContextMenu:Y=>{Y.preventDefault(),e()},"aria-hidden":"true"}),y.jsxs("div",{ref:j,role:"menu","aria-label":`Actions for ${A.filename}`,tabIndex:0,onKeyDown:Y=>{var ye,B,R,V;["Escape","ArrowDown","ArrowUp","Home","End"].includes(Y.key)&&Y.stopPropagation();const T=Array.from(((ye=j.current)==null?void 0:ye.querySelectorAll("[role='menuitem']"))??[]),he=T.indexOf(document.activeElement);if(Y.key==="Escape")Y.preventDefault(),e();else if(Y.key==="ArrowDown"||Y.key==="ArrowUp"){Y.preventDefault();const ue=Y.key==="ArrowDown"?1:-1;(B=T[(he+ue+T.length)%T.length])==null||B.focus()}else Y.key==="Home"?(Y.preventDefault(),(R=T[0])==null||R.focus()):Y.key==="End"&&(Y.preventDefault(),(V=T.at(-1))==null||V.focus())},className:"animate-modal-in fixed z-[var(--z-context-menu)] max-h-[calc(100dvh-16px)] w-56 max-w-[calc(100vw-16px)] overflow-y-auto rounded-lg border border-line bg-surface-glass py-1 text-xs text-ink shadow-2xl backdrop-blur-md",style:I??{left:ne,top:ae,visibility:"hidden"},children:[y.jsx("div",{className:"border-b border-line px-3 py-2 font-medium text-ink-muted truncate",children:A.filename}),y.jsxs("button",{role:"menuitem",onClick:()=>{t(A),e()},className:"flex w-full items-center gap-2 px-3 py-3 min-h-[44px] hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Launch ${A.filename}`,children:[y.jsx(Fl,{className:"h-3.5 w-3.5 fill-current text-status-success-text group-hover:text-white"}),y.jsx("span",{children:"Launch"})]}),y.jsxs("button",{role:"menuitem",onClick:()=>{P(!0)},className:"flex w-full items-center gap-2 px-3 py-3 min-h-[44px] hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Launch ${A.filename} with arguments`,children:[y.jsx(Fl,{className:"h-3.5 w-3.5 text-chip-indigo-text group-hover:text-white"}),y.jsx("span",{children:"Launch with arguments..."})]}),y.jsx("div",{className:"my-1 border-t border-line"}),y.jsxs("button",{role:"menuitem",onClick:()=>{l(A),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Reveal ${A.filename} in file manager`,children:[y.jsx(zx,{className:"h-3.5 w-3.5 text-chip-sky-text group-hover:text-white"}),y.jsx("span",{children:"Reveal in File Manager"})]}),y.jsxs("button",{role:"menuitem",onClick:()=>{o(A),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Open folder containing ${A.filename}`,children:[y.jsx(Il,{className:"h-3.5 w-3.5 text-chip-amber-text group-hover:text-white"}),y.jsx("span",{children:"Open Folder"})]}),y.jsxs("button",{role:"menuitem",onClick:()=>{a(A),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Open terminal in directory containing ${A.filename}`,children:[y.jsx(eO,{className:"h-3.5 w-3.5 text-status-success-text group-hover:text-white"}),y.jsx("span",{children:"Open Terminal in Directory"})]}),y.jsxs("button",{role:"menuitem",onClick:()=>{O(A),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":"Generate QR Code",children:[y.jsx(ly,{className:"h-3.5 w-3.5 text-chip-fuchsia-text group-hover:text-white"}),y.jsx("span",{children:"Generate QR Code"})]}),y.jsx("div",{className:"my-1 border-t border-line"}),y.jsxs("button",{role:"menuitem",onClick:()=>{const Y=oe(A.path);c(Y),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":"Scan to Directory",children:[y.jsx(Il,{className:"h-3.5 w-3.5 text-chip-indigo-text group-hover:text-white"}),y.jsx("span",{children:"Scan to Directory"})]}),y.jsxs("button",{role:"menuitem",onClick:()=>{const Y=J(A.rel_path);Y&&f(Y),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Filter view to folder ${A.filename} is in`,children:[y.jsx(Bx,{className:"h-3.5 w-3.5 text-chip-indigo-text group-hover:text-white"}),y.jsx("span",{children:"Filter to Folder"})]}),y.jsxs("button",{role:"menuitem",onClick:()=>{const Y=$(A.filename);Y&&d(Y),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Filter view by extension ${$(A.filename)}`,children:[y.jsx(Bx,{className:"h-3.5 w-3.5 text-chip-indigo-text group-hover:text-white"}),y.jsx("span",{children:"Filter by Extension"})]}),y.jsx("div",{className:"my-1 border-t border-line"}),y.jsxs("button",{role:"menuitem",onClick:()=>{m(A,!1),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Copy full path of ${A.filename}`,children:[y.jsx(Fn,{className:"h-3.5 w-3.5 text-ink-muted group-hover:text-white"}),y.jsx("span",{className:"truncate",children:"Copy Full Path"})]}),y.jsxs("button",{role:"menuitem",onClick:()=>{m(A,!0),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Copy path of ${A.filename} with forward slashes`,children:[y.jsx(Fn,{className:"h-3.5 w-3.5 text-ink-muted group-hover:text-white"}),y.jsx("span",{className:"truncate",children:"Copy Path (Forward Slashes)"})]}),y.jsxs("button",{role:"menuitem",onClick:()=>{g(A,!1),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Copy filename of ${A.filename}`,children:[y.jsx(Fn,{className:"h-3.5 w-3.5 text-ink-muted group-hover:text-white"}),y.jsx("span",{className:"truncate",children:"Copy Filename"})]}),y.jsxs("button",{role:"menuitem",onClick:()=>{g(A,!0),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Copy filename of ${A.filename} without extension`,children:[y.jsx(Fn,{className:"h-3.5 w-3.5 text-ink-muted group-hover:text-white"}),y.jsx("span",{className:"truncate",children:"Copy Filename (no ext)"})]}),y.jsxs("button",{role:"menuitem",onClick:async()=>{const Y=oe(A.path);e();try{await navigator.clipboard.writeText(Y),_==null||_(`Copied: ${Y}`)}catch(T){_==null||_(`Copy failed: ${(T==null?void 0:T.message)??T}`,"error")}},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":"Copy Directory",children:[y.jsx(Fn,{className:"h-3.5 w-3.5 text-ink-muted group-hover:text-white"}),y.jsx("span",{className:"truncate",children:"Copy Directory"})]}),y.jsxs("button",{role:"menuitem",onClick:()=>{b(A),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Copy URI of ${A.filename}`,children:[y.jsx(Fn,{className:"h-3.5 w-3.5 text-ink-muted group-hover:text-white"}),y.jsx("span",{className:"truncate",children:"Copy URI"})]}),y.jsx("div",{className:"my-1 border-t border-line"}),y.jsxs("button",{role:"menuitem",onClick:()=>{v(A,"md5"),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Compute MD5 hash of ${A.filename}`,children:[y.jsx(Qo,{className:"h-3.5 w-3.5 text-chip-purple-text group-hover:text-white"}),y.jsx("span",{children:"Compute MD5 Hash"})]}),y.jsxs("button",{role:"menuitem",onClick:()=>{v(A,"sha256"),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Compute SHA256 hash of ${A.filename}`,children:[y.jsx(Qo,{className:"h-3.5 w-3.5 text-chip-purple-text group-hover:text-white"}),y.jsx("span",{children:"Compute SHA256 Hash"})]}),y.jsxs("button",{role:"menuitem",onClick:()=>{w(A,"md5"),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Verify MD5 hash of ${A.filename}`,children:[y.jsx(Qo,{className:"h-3.5 w-3.5 text-chip-purple-text group-hover:text-white"}),y.jsx("span",{children:"Verify MD5 Hash"})]}),y.jsxs("button",{role:"menuitem",onClick:()=>{w(A,"sha256"),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Verify SHA256 hash of ${A.filename}`,children:[y.jsx(Qo,{className:"h-3.5 w-3.5 text-chip-purple-text group-hover:text-white"}),y.jsx("span",{children:"Verify SHA256 Hash"})]}),y.jsx("div",{className:"my-1 border-t border-line"}),y.jsxs("button",{role:"menuitem",onClick:()=>{S(A),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`View properties of ${A.filename}`,children:[y.jsx(zx,{className:"h-3.5 w-3.5 text-chip-sky-text group-hover:text-white"}),y.jsx("span",{children:"Properties"})]}),y.jsxs("button",{role:"menuitem",onClick:()=>{C(A),e()},className:"flex w-full items-center gap-2 px-3 py-1.5 hover:bg-indigo-600 hover:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 active:scale-95 transition-transform group","aria-label":`Remove ${A.filename} from list`,children:[y.jsx(nO,{className:"h-3.5 w-3.5 text-status-danger-text group-hover:text-white"}),y.jsx("span",{children:"Delete"})]})]}),M&&y.jsx("dialog",{ref:H,className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 p-4 rounded-xl","aria-labelledby":"args-modal-title",onClick:Y=>{Y.target===H.current&&P(!1)},onCancel:Y=>{Y.preventDefault(),P(!1)},children:y.jsxs("div",{className:"animate-modal-in w-96 rounded-xl border border-frame-line glass-panel p-4",children:[y.jsx("h3",{id:"args-modal-title",className:"mb-2 text-sm font-semibold text-ink",children:"Launch with Arguments"}),y.jsx("p",{className:"mb-3 text-xs text-ink-muted truncate",children:A.filename}),y.jsx("input",{type:"text",autoFocus:!0,placeholder:"Arguments (e.g. --verbose --port 80)",value:L,onChange:Y=>D(Y.target.value),onKeyDown:Y=>{Y.key==="Enter"&&ie(),Y.key==="Escape"&&P(!1)},className:"mb-4 w-full rounded-md border border-line bg-elevated px-3 py-2 text-xs text-ink outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500","aria-label":"Command line arguments"}),y.jsxs("div",{className:"flex justify-end gap-2",children:[y.jsx("button",{onClick:()=>P(!1),className:"rounded-md px-3 py-1.5 text-xs text-ink-muted hover:bg-elevated hover:text-ink focus:outline-none focus:ring-2 focus:ring-indigo-500","aria-label":"Cancel launch",children:"Cancel"}),y.jsx("button",{onClick:ie,className:"btn btn-primary px-3 py-1.5","aria-label":`Launch ${A.filename} with arguments`,children:"Launch"})]})]})})]})}function f8({isOpen:n,initialPath:e,onClose:t,onSelect:i}){const[l,o]=E.useState(null),[a,c]=E.useState(null),[f,d]=E.useState(""),[m,g]=E.useState(!1),[b,v]=E.useState(null),w=E.useRef(null),S=E.useRef(null),C=E.useRef(null);E.useEffect(()=>{var L;if(!n){(L=C.current)==null||L.focus();return}C.current=document.activeElement instanceof HTMLElement?document.activeElement:null,v(null),O(e||"");const P=requestAnimationFrame(()=>{var D;return(D=S.current)==null?void 0:D.focus()});return()=>{var D;cancelAnimationFrame(P),(D=C.current)==null||D.focus()}},[n]);const O=async P=>{g(!0),v(null);try{const L=await fetch(`/api/fs/browse?path=${encodeURIComponent(P)}`);if(!L.ok)throw new Error("Failed to browse directory");const D=await L.json();o(D),c(D.current_path),d(D.current_path)}catch(L){v(L.message||"Navigation failed")}finally{g(!1)}},_=()=>{const P=f.trim()||a;P&&(i(P),t())},M=P=>{var H;if(P.key==="Escape"){P.preventDefault(),t();return}if(P.key!=="Tab")return;const L=(H=w.current)==null?void 0:H.querySelectorAll('button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])');if(!(L!=null&&L.length))return;const D=L[0],j=L[L.length-1];P.shiftKey&&document.activeElement===D?(P.preventDefault(),j.focus()):!P.shiftKey&&document.activeElement===j&&(P.preventDefault(),D.focus())};return n?y.jsx("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/65 p-3 backdrop-blur-sm sm:p-6",onClick:t,children:y.jsxs("div",{ref:w,role:"dialog","aria-modal":"true","aria-labelledby":"directory-picker-title",onKeyDown:M,className:"animate-modal-in flex h-[min(84dvh,760px)] max-h-[calc(100dvh-1.5rem)] w-[min(94vw,960px)] min-h-0 flex-col overflow-hidden rounded-xl border border-frame-line glass-panel sm:rounded-2xl",onClick:P=>P.stopPropagation(),children:[y.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-line px-4 py-3 sm:px-5",children:[y.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[y.jsx("span",{className:"grid h-9 w-9 shrink-0 place-items-center rounded-lg bg-chip-indigo-bg",children:y.jsx(Il,{className:"h-5 w-5 text-chip-indigo-text"})}),y.jsxs("div",{className:"min-w-0",children:[y.jsx("h2",{id:"directory-picker-title",className:"text-sm font-semibold text-ink",children:"Select a directory"}),y.jsx("p",{className:"truncate font-mono text-xs text-ink-muted",children:(l==null?void 0:l.current_path)||""})]})]}),y.jsx(Xe,{text:"Close",block:!1,children:y.jsx("button",{type:"button",onClick:t,"aria-label":"Close directory picker",className:"grid h-9 w-9 shrink-0 place-items-center rounded-lg text-ink-muted transition-colors hover:bg-elevated hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(ri,{className:"h-4 w-4"})})})]}),y.jsxs("div",{className:"border-b border-line px-4 py-3 sm:px-5",children:[y.jsx("label",{htmlFor:"directory-picker-path",className:"mb-1.5 block text-xs font-medium text-ink-secondary",children:"Location"}),y.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[y.jsx("input",{ref:S,id:"directory-picker-path",type:"text",value:f,onChange:P=>d(P.target.value),onKeyDown:P=>{P.key==="Enter"&&O(f.trim())},placeholder:"/path/to/directory",className:"h-10 min-w-0 flex-1 rounded-lg border border-line bg-elevated px-2.5 font-mono text-sm text-ink outline-none placeholder:text-ink-faint transition-colors hover:bg-surface-strong focus-visible:border-indigo-500 focus-visible:ring-2 focus-visible:ring-indigo-500/30"}),y.jsx("button",{type:"button",onClick:()=>O(f.trim()),className:"inline-flex h-10 shrink-0 items-center gap-1.5 rounded-lg border border-line bg-elevated px-3.5 text-sm font-medium text-ink-secondary transition-colors hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:"Go"}),y.jsx(Xe,{text:"Home directory",block:!1,children:y.jsx("button",{type:"button",onClick:()=>O(""),"aria-label":"Home directory",className:"grid h-10 w-10 shrink-0 place-items-center rounded-lg border border-line bg-elevated text-ink-secondary transition-colors hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(Ed,{className:"h-4 w-4"})})}),(l==null?void 0:l.parent_path)&&y.jsx(Xe,{text:"Parent directory",block:!1,children:y.jsx("button",{type:"button",onClick:()=>O(l.parent_path),"aria-label":"Parent directory",className:"grid h-10 w-10 shrink-0 place-items-center rounded-lg border border-line bg-elevated text-ink-secondary transition-colors hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(Ad,{className:"h-4 w-4 rotate-180"})})})]})]}),y.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-2 py-2 sm:px-3 sm:py-3","aria-busy":m,children:m?y.jsxs("div",{className:"flex h-full items-center justify-center gap-2.5 text-sm text-ink-muted",children:[y.jsx(Yr,{className:"h-5 w-5 animate-spin text-chip-indigo-text"}),y.jsx("span",{role:"status",children:"Loading directories…"})]}):b?y.jsxs("div",{role:"alert",className:"flex h-full flex-col items-center justify-center gap-2.5 text-center",children:[y.jsx("p",{className:"text-sm text-status-danger-text",children:b}),y.jsx("button",{type:"button",onClick:()=>O(f||(l==null?void 0:l.current_path)||""),className:"min-h-10 rounded-lg border border-line bg-elevated px-3.5 text-sm text-ink-secondary hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:"Retry"})]}):y.jsxs("ul",{className:"space-y-0.5",children:[l==null?void 0:l.items.filter(P=>P.is_dir).map(P=>y.jsx("li",{children:y.jsxs("button",{type:"button",onClick:()=>O(P.path),onDoubleClick:()=>{d(P.path),i(P.path),t()},className:`flex min-h-10 w-full items-center justify-between rounded-lg px-3 py-1.5 text-left text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-indigo-400 ${a===P.path?"bg-chip-indigo-bg text-chip-indigo-text":"text-ink-secondary hover:bg-elevated hover:text-ink"}`,children:[y.jsxs("span",{className:"flex min-w-0 items-center gap-2.5",children:[y.jsx(lu,{className:"h-5 w-5 shrink-0 text-chip-indigo-text"}),y.jsx("span",{className:"truncate",children:P.name})]}),a===P.path&&y.jsx(Sr,{className:"h-4 w-4 shrink-0 text-chip-indigo-text"})]})},P.path)),(l==null?void 0:l.items.filter(P=>P.is_dir).length)===0&&y.jsxs("li",{className:"flex h-full min-h-36 flex-col items-center justify-center gap-2.5 text-center text-sm text-ink-muted",children:[y.jsx(Il,{className:"h-7 w-7 text-ink-faint"}),"No subdirectories found"]})]})}),y.jsxs("div",{className:"flex flex-col gap-2 border-t border-line px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-5",children:[y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsx("p",{className:"mb-0.5 text-xs font-medium text-ink-muted",children:"Selected folder"}),y.jsx("p",{className:"truncate font-mono text-sm text-ink",title:a||f,children:a||f||"—"})]}),y.jsxs("div",{className:"flex shrink-0 justify-end gap-1.5",children:[y.jsx("button",{type:"button",onClick:t,className:"min-h-10 rounded-lg border border-line bg-elevated px-3.5 text-sm text-ink-secondary transition-colors hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:"Cancel"}),y.jsxs("button",{type:"button",onClick:_,disabled:!f.trim(),className:"btn btn-primary min-h-10 rounded-lg px-4 text-sm font-semibold",children:[y.jsx(Il,{className:"h-4 w-4"}),"Select folder"]})]})]})]})}):null}function h8({visible:n,onFileSelected:e}){const t=E.useRef(null);return n?y.jsxs("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-drop-overlay)] flex items-center justify-center bg-black/65 backdrop-blur-sm",onClick:()=>{var i;return(i=t.current)==null?void 0:i.click()},"data-testid":"drop-config-overlay",children:[y.jsx("input",{ref:t,type:"file",accept:".profiles,.profiles.yaml,.profiles.yml,.yaml,.yml",className:"hidden",onChange:i=>{var o;const l=(o=i.target.files)==null?void 0:o[0];l&&e(l),i.target.value=""}}),y.jsxs("div",{className:"rounded-xl border-2 border-dashed border-chip-indigo-border bg-surface px-8 py-6 text-center shadow-2xl",children:[y.jsx("span",{className:"mx-auto mb-3 grid h-9 w-9 place-items-center rounded-lg bg-chip-indigo-bg",children:y.jsx(Vo,{className:"h-5 w-5 text-chip-indigo-text"})}),y.jsx("p",{className:"text-sm font-semibold text-ink",children:"Drop configuration file"}),y.jsx("p",{className:"mt-1 text-xs text-ink-muted",children:".profiles, .profiles.yaml, .yml, .yaml — session-only preview"})]})]}):null}function P0({id:n,ariaLabel:e,value:t,options:i,onChange:l,placeholder:o,className:a="",inputClassName:c="",optionLabel:f=g=>g,onOpenChange:d,commitOn:m="change"}){const g=E.useId(),b=E.useRef(null),[v,w]=E.useState(!1),[S,C]=E.useState(""),[O,_]=E.useState(-1),[M,P]=E.useState(null),L=i.filter(F=>f(F).toLocaleLowerCase().includes(S.toLocaleLowerCase())),D=O>=0&&L[O]?`${g}-option-${O}`:void 0;E.useEffect(()=>{const F=A=>{var ne;(ne=b.current)!=null&&ne.contains(A.target)||w(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[]),E.useEffect(()=>{d==null||d(v)},[v,d]),E.useEffect(()=>{var F;O<0||(F=document.getElementById(`${g}-option-${O}`))==null||F.scrollIntoView({block:"nearest"})},[O,g]);const j=()=>{C(""),_(-1),w(!0)},H=F=>{P(null),l(F)},Z=F=>{H(F),C(""),_(-1),w(!1)},I=F=>{if(F.key==="ArrowDown"){if(F.preventDefault(),!v){j(),_(0);return}_(A=>Math.min(A+1,L.length-1))}else if(F.key==="ArrowUp"){if(F.preventDefault(),!v){j(),_(L.length-1);return}_(A=>A<=0?L.length-1:A-1)}else F.key==="Enter"&&v&&L[O]!==void 0?(F.preventDefault(),F.stopPropagation(),Z(L[O])):F.key==="Enter"&&m==="deferred"&&M!==null&&M!==t?(F.preventDefault(),F.stopPropagation(),H(M)):F.key==="Escape"&&w(!1)};return y.jsxs("div",{ref:b,onBlur:F=>{var A;(A=b.current)!=null&&A.contains(F.relatedTarget)||(w(!1),m==="deferred"&&M!==null&&M!==t&&H(M))},className:`relative flex min-w-0 ${a}`,children:[y.jsx("input",{id:n,type:"text",role:"combobox","aria-label":e,"aria-autocomplete":"list","aria-expanded":v,"aria-controls":g,"aria-activedescendant":D,value:m==="deferred"&&M!==null?M:t,placeholder:o,onChange:F=>{const A=F.target.value;C(A),_(-1),w(!0),m==="deferred"?P(A):l(A)},onKeyDown:I,className:`min-w-0 flex-1 rounded-l-md border border-line bg-elevated px-3 py-1.5 text-ink outline-none transition-colors hover:bg-surface-strong focus:border-indigo-500 ${c}`}),y.jsx("button",{type:"button","aria-label":`Show ${e.toLowerCase()} options`,"aria-expanded":v,title:`Show ${e.toLowerCase()} options`,onMouseDown:F=>F.preventDefault(),onClick:()=>v?w(!1):j(),className:"shrink-0 rounded-r-md border border-l-0 border-line bg-elevated px-2 text-ink-muted hover:bg-surface-strong hover:text-ink focus-visible:z-10 focus-visible:outline focus-visible:outline-2 focus-visible:outline-indigo-500 transition-colors",children:y.jsx(o4,{className:`h-3.5 w-3.5 transition-transform ${v?"rotate-180":""}`})}),v&&y.jsx("ul",{id:g,role:"listbox","aria-label":`${e} options`,className:"absolute left-0 top-full z-[var(--z-combobox-list)] mt-1 max-h-60 w-full min-w-48 overflow-y-auto rounded-md border border-line bg-surface py-1 text-ink shadow-xl",children:L.length>0?L.map((F,A)=>{const ne=f(F),ae=A===O,ie=F===t;return y.jsx("li",{id:`${g}-option-${A}`,role:"option","aria-selected":ie,title:ne||void 0,onMouseEnter:()=>_(A),onMouseDown:$=>$.preventDefault(),onClick:()=>Z(F),className:`cursor-pointer truncate px-3 py-1.5 ${ae?"bg-elevated text-ink":"text-ink-secondary"} ${ie?"font-semibold":""}`,children:ne||"(No filter)"},`${F}-${A}`)}):y.jsx("li",{className:"px-3 py-1.5 text-ink-muted",children:"No matching presets"})})]})}function d8(n){const e=n.match(/^(.*?)\.(?:dev|post)\d+/);if(e)return e[1];const t=n.indexOf("+");return t>-1?n.slice(0,t):n}function m8({title:n,release:e,directories:t,activeDirectory:i,onDirectoryChange:l,onBrowseDirectory:o,onGoToParentDirectory:a,onGoToHomeDirectory:c,onOpenActiveDirectory:f,onOpenTerminal:d}){const[m,g]=E.useState(!1),b=e||"0.0.0-dev",[v,w]=E.useState(!1),S=E.useRef(null),C=async()=>{try{await navigator.clipboard.writeText(b),w(!0),S.current!==null&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>w(!1),1500)}catch{}};return E.useEffect(()=>()=>{S.current!==null&&window.clearTimeout(S.current)},[]),y.jsxs("header",{className:"relative z-30 flex flex-wrap items-center gap-3 border-b border-line bg-app/90 px-5 py-2 text-xs backdrop-blur-xl shadow-xs transition-all duration-200",children:[y.jsx("div",{className:"flex shrink-0 items-center gap-3",children:y.jsxs("div",{className:"flex items-center gap-3.5",children:[y.jsxs("div",{className:"relative flex h-9 w-9 items-center justify-center rounded-xl border border-chip-indigo-border shadow-xs",children:[y.jsx("img",{src:"/profiles-128.png",alt:"ProFiles logo",className:"h-9 w-9 rounded-xl object-cover"}),y.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 flex h-2.5 w-2.5 items-center justify-center rounded-full bg-emerald-500 ring-2 ring-app"})]}),y.jsxs("div",{children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("h1",{className:"text-sm font-bold tracking-tight text-ink font-heading",children:"ProFiles"}),n&&y.jsxs(y.Fragment,{children:[y.jsx("span",{className:"text-ink-faint",children:"/"}),y.jsx("span",{className:"text-xs font-medium text-chip-indigo-text bg-chip-indigo-bg px-2 py-0.5 rounded-md border border-chip-indigo-border/50",children:n})]})]}),y.jsxs("p",{className:"text-[11px] font-medium text-ink-muted tracking-wide mt-0.5",children:["Crafted by ",y.jsx("span",{className:"text-ink font-semibold",children:"Florent ALBANY"})," •"," ",y.jsx(Xe,{text:v?"Copied!":`v${b}`,block:!1,placement:"bottom",children:y.jsxs("button",{type:"button",onClick:()=>void C(),"aria-label":`Copy full version ${b}`,className:"cursor-pointer font-mono text-chip-indigo-text hover:text-chip-indigo-text/80",children:["v",d8(b)]})})]})]})]})}),y.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[y.jsxs("label",{className:"flex shrink-0 items-center gap-1.5 font-medium text-ink-secondary text-xs",children:[y.jsx(lu,{className:"h-3.5 w-3.5 text-chip-indigo-text"}),y.jsx("span",{children:"Directory:"})]}),y.jsx(Xe,{text:"Select or type a directory path to scan files from.",suppress:m,children:y.jsx(P0,{id:"directory-combobox",ariaLabel:"Directory",value:i,options:t,onChange:l,commitOn:"deferred",onOpenChange:g,placeholder:"/path/to/directory",className:"w-full",inputClassName:"font-mono"})}),f&&y.jsx(Xe,{text:"Open the active directory in the OS file manager",block:!1,children:y.jsx("button",{type:"button",onClick:f,"aria-label":"Open active directory",className:"btn btn-secondary shrink-0 p-1.5",children:y.jsx(KM,{className:"h-3.5 w-3.5"})})}),a&&y.jsx(Xe,{text:"Go to parent directory",block:!1,children:y.jsx("button",{type:"button",onClick:a,"aria-label":"Go to parent directory",className:"btn btn-secondary shrink-0 p-1.5",children:y.jsx(Ad,{className:"h-3.5 w-3.5 rotate-180"})})}),o&&y.jsx(Xe,{text:"Browse for a folder on this system",block:!1,children:y.jsx("button",{type:"button",onClick:o,"aria-label":"Browse directory",className:"btn btn-secondary shrink-0 p-1.5",children:y.jsx(Il,{className:"h-3.5 w-3.5"})})}),d&&y.jsx(Xe,{text:"Open the active directory in a terminal",block:!1,children:y.jsx("button",{type:"button",onClick:()=>d(i),"aria-label":"Open directory in terminal",className:"btn btn-secondary shrink-0 p-1.5",children:y.jsx(eO,{className:"h-3.5 w-3.5"})})}),c&&y.jsx(Xe,{text:"Set directory to your home folder",block:!1,children:y.jsx("button",{type:"button",onClick:c,"aria-label":"Go to home directory",className:"btn btn-secondary shrink-0 p-1.5",children:y.jsx(Ed,{className:"h-3.5 w-3.5"})})})]})]})}function p8({message:n,onRetry:e,retrying:t=!1}){return y.jsx("div",{className:"flex flex-1 items-center justify-center p-8",role:"alert","data-testid":"init-error-panel",children:y.jsxs("div",{className:"w-full max-w-sm rounded-xl border border-line bg-surface p-6 text-center shadow-xl",children:[y.jsx("div",{className:"mx-auto mb-3 flex h-10 w-10 items-center justify-center rounded-full border border-status-danger-border bg-status-danger-bg",children:y.jsx(Ec,{className:"h-5 w-5 text-status-danger-text/80"})}),y.jsx("h3",{className:"text-sm font-semibold text-ink",children:"Couldn't load the app"}),y.jsx("p",{className:"mt-1 break-words text-xs text-ink-secondary",children:n}),y.jsxs("button",{type:"button",onClick:e,disabled:t,className:"btn btn-primary mx-auto mt-4 px-3.5 py-1.5 font-semibold shadow-sm",children:[y.jsx(Md,{className:`h-3.5 w-3.5 ${t?"animate-spin motion-reduce:animate-none":""}`}),y.jsx("span",{children:t?"Retrying...":"Retry"})]})]})})}function V2({url:n,label:e,className:t="",onCopied:i,onCopyError:l}){const o=async()=>{try{await navigator.clipboard.writeText(n),i==null||i(n)}catch{l==null||l(n)}};return y.jsxs("span",{className:`flex items-center justify-between gap-2 ${t}`.trim(),children:[y.jsx("code",{className:"truncate font-mono text-[11px] text-ink",children:n}),y.jsx("button",{type:"button",onClick:o,"aria-label":e??`Copy ${n}`,title:e??"Copy",className:"focus-ring shrink-0 rounded p-1 text-ink-faint transition-colors hover:bg-elevated hover:text-ink",children:y.jsx(Fn,{className:"h-3.5 w-3.5"})})]})}function g8({open:n,systemInfo:e,showToast:t,onConfirmed:i,onClose:l}){const[o,a]=E.useState(null),[c,f]=E.useState(null),[d,m]=E.useState(null),[g,b]=E.useState(null),v=E.useRef(null),w=E.useRef(null),S=E.useRef(0),C=E.useRef(!1);E.useEffect(()=>{C.current=n},[n]),E.useEffect(()=>{n&&(S.current+=1,a(null),f(null))},[n]);const O=window.location.port,_=e?`http://${e.hostname}:${O}`:null,M=e?`http://${e.ip}:${O}`:null,P=`http://127.0.0.1:${O}`,L=(e==null?void 0:e.lan_enabled)===!0;E.useEffect(()=>{if(!n||!M)return;let Z=!1;return m(null),b(null),Lx({content:M}).then(I=>{Z||m(I.image)}).catch(I=>{Z||b(I instanceof Error?I.message:"Failed to generate the QR code")}),()=>{Z=!0}},[n,M]);const D=tl({isOpen:n,onClose:l,dialogRef:v,initialFocusRef:w});if(!n)return null;const j=async()=>{try{await navigator.clipboard.writeText(P),t("URL copied to clipboard.")}catch{t("Failed to copy URL.","error")}},H=async Z=>{const I=++S.current;f(null),a(Z?"enable":"disable");try{await CM(Z);const F=await OM(Z);if(F&&i(F),I!==S.current)return;a(null),(F==null?void 0:F.lan_enabled)===Z?C.current||t(Z?"ProFiles is now reachable on the local network.":"ProFiles is restricted to this machine.","info"):(f("Failed to update LAN binding — the previous address is still active."),C.current||t("Failed to update LAN binding — the previous address is still active.","error"))}catch(F){const A=F instanceof Error?F.message:"Failed to update LAN binding";if(I!==S.current)return;a(null),f(`Failed to update LAN binding: ${A}`);const ne=await Qh();i(ne),C.current||t(`Failed to update LAN binding: ${A}`,"error")}};return y.jsx("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm",onClick:l,children:y.jsxs("div",{ref:v,role:"dialog","aria-modal":"true","aria-labelledby":"lan-modal-title",onKeyDown:D,onClick:Z=>Z.stopPropagation(),className:"animate-modal-in w-[480px] max-w-full rounded-2xl border border-frame-line glass-panel p-5",children:[y.jsxs("div",{className:"mb-4 flex items-center gap-2.5",children:[y.jsx("span",{className:`grid h-9 w-9 shrink-0 place-items-center rounded-lg ${o!==null?"bg-status-warning-bg text-status-warning-text":L?"bg-status-success-bg text-status-success-text":"bg-elevated text-ink-muted"}`,children:o==="disable"||!L&&o===null?y.jsx(AD,{className:"h-5 w-5"}):y.jsx(MD,{className:"h-5 w-5"})}),y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsx("h2",{id:"lan-modal-title",className:"text-sm font-semibold tracking-tight text-ink",children:"LAN Access"}),y.jsx("p",{role:"status",className:`mt-0.5 flex items-center gap-1.5 text-xs font-medium ${o!==null?"text-status-warning-text":L?"text-status-success-text":"text-ink-muted"}`,children:o!==null?y.jsxs(y.Fragment,{children:[y.jsx("span",{className:"h-2.5 w-2.5 shrink-0 animate-spin rounded-full border-2 border-current border-t-transparent","aria-hidden":"true"}),"Updating the LAN binding…"]}):L?y.jsxs(y.Fragment,{children:[y.jsx("span",{className:"h-[7px] w-[7px] shrink-0 rounded-full bg-current","aria-hidden":"true"}),"Reachable on this network"]}):y.jsxs(y.Fragment,{children:[y.jsx("span",{className:"h-[7px] w-[7px] shrink-0 rounded-full bg-current","aria-hidden":"true"}),"Restricted to the host machine"]})})]}),y.jsx("button",{type:"button",onClick:l,"aria-label":"Close",title:"Close",className:"focus-ring rounded-md p-1 text-ink-muted hover:bg-elevated hover:text-ink",children:y.jsx(ri,{className:"h-4 w-4"})})]}),y.jsxs("div",{className:"flex items-start gap-4",children:[y.jsxs("div",{className:"flex w-40 shrink-0 flex-col items-center gap-1.5",children:[y.jsx("div",{className:"h-40 w-40 overflow-hidden rounded-lg border border-line bg-white p-2",children:d?y.jsx("img",{src:d,alt:"QR code of the LAN address",className:"h-full w-full object-contain"}):g?y.jsx("span",{role:"alert",className:"flex h-full items-center justify-center px-1 text-center text-[10px] text-status-danger-text",children:g}):y.jsx("span",{className:"flex h-full items-center justify-center text-[10px] text-ink-faint","aria-hidden":"true",children:"…"})}),y.jsx("p",{className:"text-center text-[10px] text-ink-faint",children:"Scans the IP address"})]}),y.jsxs("div",{className:"min-w-0 flex-1 text-xs text-ink-secondary",children:[o===null&&c&&y.jsx("div",{role:"alert",className:"mb-2.5 rounded-md border border-status-danger-border bg-status-danger-bg p-2.5 text-status-danger-text",children:c}),y.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-ink-muted",children:"For other devices"}),M&&y.jsx(V2,{url:M,label:"Copy IP URL",className:"mt-1.5 rounded-lg bg-elevated/40 px-2 py-1.5",onCopied:()=>t("URL copied to clipboard."),onCopyError:()=>t("Failed to copy URL.","error")}),_&&y.jsx(V2,{url:_,label:"Copy hostname URL",className:"mt-1.5 rounded-lg bg-elevated/40 px-2 py-1.5",onCopied:()=>t("URL copied to clipboard."),onCopyError:()=>t("Failed to copy URL.","error")}),y.jsx("p",{className:"mt-3 text-[10px] font-semibold uppercase tracking-wider text-ink-muted",children:"This machine"}),y.jsxs("span",{className:"mt-1.5 flex items-center gap-1.5 rounded-lg bg-elevated/40 px-2 py-1.5",children:[y.jsx(iy,{className:"h-3.5 w-3.5 shrink-0 text-ink-faint","aria-hidden":"true"}),y.jsx("a",{href:P,target:"_blank",rel:"noopener noreferrer",className:"min-w-0 flex-1 break-all font-mono text-[11px] text-ink underline decoration-line underline-offset-2 hover:text-indigo-400",children:P}),y.jsx("button",{type:"button","aria-label":"Copy loopback URL",title:"Copy loopback URL",onClick:()=>void j(),className:"focus-ring shrink-0 rounded p-1 text-ink-faint transition-colors hover:bg-elevated hover:text-ink",children:y.jsx(Fn,{className:"h-3.5 w-3.5"})})]})]})]}),!L&&o===null&&y.jsxs("div",{className:"mt-3.5 flex items-center gap-2 rounded-lg border border-status-warning-border bg-status-warning-bg p-2.5 text-[11.5px] font-medium text-status-warning-text",children:[y.jsx(Dd,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":"true"}),"If Enabled, ProFiles will be reachable by anyone on this network."]}),y.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[y.jsx("button",{ref:w,type:"button",onClick:l,className:"min-h-9 rounded-lg border border-line bg-elevated px-3.5 text-sm text-ink-secondary transition-colors hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:"Cancel"}),y.jsx("button",{type:"button",disabled:o!==null,onClick:()=>void H(!L),className:`min-h-9 rounded-lg border px-4 text-sm font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400 disabled:cursor-not-allowed disabled:opacity-50 ${L?"border-status-danger-border bg-status-danger-bg/30 text-status-danger-text hover:bg-status-danger-bg/60":"btn-primary border-transparent bg-indigo-600 text-white hover:bg-indigo-500"}`,children:L?"Disable LAN":"Enable LAN"})]})]})})}const Q2=/"([^"]*)"|(\S+)/g,X2=/"([^"]*)"/g,x8="Unmatched quote";function y8(n){const e=[];let t;for(Q2.lastIndex=0;(t=Q2.exec(n))!==null;){const a=t[1]!==void 0?t[1]:t[2];a&&a.trim()&&e.push(a)}let i="",l=0;X2.lastIndex=0;let o;for(;(o=X2.exec(n))!==null;)i+=n.slice(l,o.index),l=o.index+o[0].length;return i+=n.slice(l),{terms:e,error:i.includes('"')?x8:null}}function hA(n){const e=n.trim();if(!e)return{error:null,groups:[]};const{terms:t,error:i}=y8(e);if(t.length===0)return{error:i,groups:[]};const l=[];let o={includes:[],excludes:[]};for(const a of t){if(a.toUpperCase()==="OR"){l.push(o),o={includes:[],excludes:[]};continue}a==="-"||a==="+"||(a.startsWith("-")&&a.length>1?o.excludes.push(a.slice(1)):a.startsWith("+")&&a.length>1?o.includes.push(a.slice(1)):o.includes.push(a))}return l.push(o),{error:i,groups:l}}const b8=256,Ss=new Map;function $2(n){return n.toLowerCase()}function v8(n){const e=Ss.get(n);if(e)return Ss.delete(n),Ss.set(n,e),e;const{groups:t}=hA(n),i={groups:t.map(l=>({includes:l.includes.map($2),excludes:l.excludes.map($2)}))};if(Ss.size>=b8){const l=Ss.keys().next().value;l!==void 0&&Ss.delete(l)}return Ss.set(n,i),i}function w8(n,e){return e.includes.every(t=>n.includes(t))&&!e.excludes.some(t=>n.includes(t))}function k8(n,e){const{groups:t}=v8(e);if(t.length===0)return!0;const i=n.toLowerCase();return t.some(l=>w8(i,l))}function S8({query:n,visible:e}){if(!e)return null;const t=hA(n);return t.error?y.jsx("div",{"data-testid":"filter-syntax-helper",className:"pointer-events-none absolute left-0 right-0 top-full z-[var(--z-syntax-helper)] mt-1 rounded-md border border-status-danger-border bg-surface-strong px-3 py-2 text-[11px] leading-5 text-status-danger-text/90 shadow-xl",children:t.error}):t.groups.length===0?null:y.jsxs("div",{"data-testid":"filter-syntax-helper",className:"pointer-events-none absolute left-0 right-0 top-full z-[var(--z-syntax-helper)] mt-1 rounded-md border border-line bg-surface-strong px-3 py-2 text-[11px] leading-5 text-ink-secondary shadow-xl",children:[y.jsx("span",{className:"mr-1.5 align-[1px] text-[10px] uppercase tracking-wide text-ink-muted",children:"reads as"}),t.groups.map((i,l)=>y.jsxs("span",{"data-testid":"filter-syntax-group",children:[l>0&&y.jsx("span",{className:"mx-1 font-mono text-chip-indigo-text",children:"OR"}),i.includes.map((o,a)=>y.jsxs("span",{children:[a>0&&y.jsx("span",{className:"text-ink-muted",children:" · "}),y.jsx("span",{className:"font-mono text-chip-indigo-text",children:o})]},`i-${a}`)),i.includes.length>0&&i.excludes.length>0&&y.jsx("span",{className:"text-ink-muted",children:" · "}),i.excludes.map((o,a)=>y.jsxs("span",{children:[a>0&&y.jsx("span",{className:"text-ink-muted",children:" · "}),y.jsx("span",{className:"text-ink-muted",children:"✕ "}),y.jsx("span",{className:"font-mono text-status-danger-text/70 line-through",children:o})]},`x-${a}`))]},l))]})}const G2=y.jsxs("span",{className:"flex flex-col gap-1 whitespace-nowrap text-left",children:[y.jsx("span",{className:"font-semibold",children:"Supported operators"}),y.jsxs("span",{children:[y.jsx("code",{className:"font-mono text-chip-indigo-text",children:"a b"})," — AND (both terms)"]}),y.jsxs("span",{children:[y.jsx("code",{className:"font-mono text-chip-indigo-text",children:"a OR b"})," — either term"]}),y.jsxs("span",{children:[y.jsx("code",{className:"font-mono text-chip-indigo-text",children:"-a"})," — NOT (exclude)"]}),y.jsxs("span",{children:[y.jsx("code",{className:"font-mono text-chip-indigo-text",children:"+a"})," — force include"]}),y.jsxs("span",{children:[y.jsx("code",{className:"font-mono text-chip-indigo-text",children:'"a b"'})," — exact phrase"]})]});function C8({extensions:n,activeExtension:e,onExtensionChange:t,filterOptions:i,filterText:l,onFilterTextChange:o,recursive:a,onRecursiveChange:c,onScan:f,scanning:d,barcodeMode:m,onBarcodeToggle:g,onCameraBarcodeClick:b,autoRescanActive:v,onTimerClick:w}){const[S,C]=E.useState(!1),[O,_]=E.useState(!1),[M,P]=E.useState(!1);return y.jsxs("div",{className:"flex w-full flex-wrap items-center gap-3 border-b border-line bg-surface-glass p-3 text-xs",children:[y.jsx(Xe,{text:G2,suppress:O,children:y.jsxs("div",{className:"relative min-w-0 flex-1 basis-64",onFocusCapture:L=>{L.target.tagName==="INPUT"&&C(!0)},onBlurCapture:L=>{L.target.tagName==="INPUT"&&C(!1)},children:[y.jsx(JC,{className:"pointer-events-none absolute left-3 top-1/2 z-10 h-4 w-4 -translate-y-1/2 text-ink-secondary"}),y.jsx(P0,{id:"filter-combobox",ariaLabel:"File filter",value:l,options:i||[],onChange:o,onOpenChange:_,placeholder:"Filter files: keyword, a OR b, -tag, exact phrase...",className:"w-full",inputClassName:"pl-9 pr-3",optionLabel:L=>L||"(No filter)"}),y.jsx(S8,{query:l,visible:S&&!O&&l.trim().length>0})]})}),y.jsx(Xe,{text:G2,block:!1,suppress:M,children:y.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[y.jsx("span",{className:"text-ink-muted",children:"Ext:"}),y.jsx(P0,{id:"extension-combobox",ariaLabel:"Extension filter",value:e,options:n,onChange:t,commitOn:"deferred",onOpenChange:P,placeholder:".py OR .toml",className:"w-44",inputClassName:"font-mono px-2.5"})]})}),y.jsx(Xe,{text:"Include subdirectories when scanning",block:!1,children:y.jsxs("label",{className:"flex shrink-0 cursor-pointer select-none items-center gap-1.5 text-ink-secondary",children:[y.jsx("input",{type:"checkbox",checked:a,onChange:L=>c(L.target.checked),className:"rounded border-line text-chip-indigo-text focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 focus-visible:ring-offset-1 focus-visible:ring-offset-app"}),y.jsx("span",{children:"Recursive"})]})}),y.jsx(Xe,{text:"Run the scan with the current criteria (Enter)",block:!1,children:y.jsxs("button",{onClick:f,disabled:d,className:"btn btn-primary shrink-0 px-3.5 py-1.5 font-semibold shadow-sm",children:[d?y.jsx(Md,{className:"h-3.5 w-3.5 animate-spin motion-reduce:animate-none"}):y.jsx(Fl,{className:"h-3.5 w-3.5 fill-current"}),y.jsx("span",{children:d?"Scanning...":"Scan"})]})}),y.jsx(Xe,{text:v?"Auto-rescan is active. Click to configure.":"Configure periodic auto-rescan (hot-folder mode)",block:!1,children:y.jsx("button",{type:"button",onClick:w,"aria-label":"Configure timer / auto-rescan",className:`flex shrink-0 items-center justify-center rounded-md border p-1.5 text-ink-secondary hover:border-indigo-500 hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 transition-colors ${v?"border-chip-indigo-border bg-chip-indigo-bg text-chip-indigo-text":"border-line bg-elevated"}`,children:y.jsx(tO,{className:`h-3.5 w-3.5 ${v?"animate-pulse":""}`})})}),y.jsx(Xe,{text:"Toggle barcode scanner mode (USB HID). When active, scan a barcode to auto-fill controls and trigger a scan.",block:!1,children:y.jsx("button",{type:"button",onClick:g,"aria-label":m?"Disable barcode mode":"Enable barcode mode",className:`flex shrink-0 items-center justify-center rounded-md border p-1.5 text-ink-secondary hover:border-indigo-500 hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 transition-colors ${m?"border-chip-indigo-border bg-chip-indigo-bg text-chip-indigo-text":"border-line bg-elevated"}`,children:y.jsx(ly,{className:`h-3.5 w-3.5 ${m?"animate-pulse":""}`})})}),b&&y.jsx(Xe,{text:"Scan barcode or QR code using webcam / camera (Ctrl + Shift + B)",block:!1,children:y.jsx("button",{type:"button",onClick:b,"aria-label":"Scan barcode with camera",className:"btn btn-secondary shrink-0 p-1.5",children:y.jsx(YC,{className:"h-3.5 w-3.5"})})})]})}const O8=2e3,N8=500,T8=[{value:null,label:"ALL"},{value:"DEBUG",label:"DEBUG"},{value:"INFO",label:"INFO"},{value:"WARNING",label:"WARNING"},{value:"ERROR",label:"ERROR"},{value:"CRITICAL",label:"CRITICAL"}],Y2={DEBUG:{icon:t4,className:"text-chip-sky-text"},INFO:{icon:ry,className:"text-status-success-text"},WARNING:{icon:Dd,className:"text-status-warning-text"},ERROR:{icon:Uc,className:"text-status-danger-text"},CRITICAL:{icon:Uc,className:"text-status-danger-text"},UNKNOWN:{icon:sa,className:"text-ink-faint"}};function A8({isOpen:n,onClose:e,onOpenExternally:t}){const[i,l]=E.useState([]),[o,a]=E.useState("profiles.log"),[c,f]=E.useState(0),[d,m]=E.useState(null),[g,b]=E.useState(""),[v,w]=E.useState(!1),[S,C]=E.useState(!0),[O,_]=E.useState(null),[M,P]=E.useState(!0),L=E.useRef(null),D=E.useRef(null),j=E.useRef(null),H=E.useRef(null),Z=E.useRef(S),I=E.useRef({level:d,search:g}),F=E.useRef(0),A=E.useRef(!0);Z.current=S,I.current={level:d,search:g};const ne=E.useCallback(async()=>{const J=++F.current,{level:Y,search:T}=I.current;w(!0);try{const he=await SM({limit:N8,level:Y,search:T});if(F.current!==J)return;l(he.entries),a(he.path),f(he.size_bytes),_(null)}catch(he){if(F.current!==J)return;_((he==null?void 0:he.message)||"Failed to read the log file")}finally{F.current===J&&w(!1)}},[]);E.useEffect(()=>{n&&ne()},[n,ne]),E.useEffect(()=>{if(!n||!S)return;const J=window.setInterval(()=>{ne()},O8);return()=>window.clearInterval(J)},[n,S,ne]),E.useEffect(()=>{if(!n){A.current=!0;return}if(A.current){A.current=!1;return}const J=window.setTimeout(()=>void ne(),250);return()=>window.clearTimeout(J)},[n,d,g,ne]),E.useEffect(()=>{if(!M)return;const J=j.current;J&&(J.scrollTop=J.scrollHeight)},[i,M]),E.useEffect(()=>{if(!n)return;const J=document.activeElement instanceof HTMLElement?document.activeElement:null,Y=requestAnimationFrame(()=>{var T;return(T=D.current)==null?void 0:T.focus()});return()=>{cancelAnimationFrame(Y),J==null||J.focus()}},[n]);const ae=J=>{var ye;if(J.key==="Escape"){J.preventDefault(),e();return}if(J.key!=="Tab")return;const Y=(ye=L.current)==null?void 0:ye.querySelectorAll('button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])');if(!(Y!=null&&Y.length))return;const T=Y[0],he=Y[Y.length-1];J.shiftKey&&document.activeElement===T?(J.preventDefault(),he.focus()):!J.shiftKey&&document.activeElement===he&&(J.preventDefault(),T.focus())},ie=()=>{const J=j.current;if(!J)return;const Y=J.scrollHeight-J.scrollTop-J.clientHeight<24;P(Y)},$=async()=>{try{await navigator.clipboard.writeText(i.map(J=>J.raw).join(` -`))}catch{}},oe=E.useMemo(()=>{const J=new Map;for(const Y of i)J.set(Y.level,(J.get(Y.level)??0)+1);return J},[i]);return n?y.jsx("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/65 p-3 backdrop-blur-sm sm:p-6",onClick:e,children:y.jsxs("div",{ref:L,role:"dialog","aria-modal":"true","aria-labelledby":"log-viewer-title",onKeyDown:ae,className:"animate-modal-in flex h-[min(84dvh,760px)] w-[clamp(560px,85vw,1500px)] min-h-0 flex-col overflow-hidden rounded-xl border border-frame-line glass-panel sm:rounded-2xl",onClick:J=>J.stopPropagation(),children:[y.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-b border-line px-5 py-4 sm:px-6",children:[y.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[y.jsx("span",{className:"grid h-10 w-10 shrink-0 place-items-center rounded-lg bg-chip-indigo-bg",children:y.jsx(sa,{className:"h-5 w-5 text-chip-indigo-text","aria-hidden":"true"})}),y.jsxs("div",{className:"min-w-0",children:[y.jsx("h2",{id:"log-viewer-title",className:"text-base font-semibold text-ink",children:"Application logs"}),y.jsxs("p",{className:"truncate font-mono text-xs text-ink-muted",children:[o,y.jsxs("span",{className:"text-ink-faint",children:[" · ",K2(c)]})]})]})]}),y.jsxs("div",{className:"relative min-w-[220px] flex-1",children:[y.jsx(JC,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-ink-faint","aria-hidden":"true"}),y.jsx("input",{ref:H,type:"search",value:g,onChange:J=>b(J.target.value),placeholder:"Filter log lines…","aria-label":"Filter log lines",className:"w-full rounded-lg border border-line bg-elevated py-1.5 pl-8 pr-2.5 font-mono text-xs text-ink placeholder:text-ink-faint focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400"})]}),y.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[y.jsx(Xe,{text:S?"Pause live tail":"Resume live tail",block:!1,children:y.jsxs("button",{type:"button",onClick:()=>C(J=>!J),"aria-pressed":S,className:`flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400 ${S?"border-status-success-border bg-status-success-bg text-status-success-text":"border-line bg-elevated text-ink-muted hover:text-ink"}`,children:[y.jsx("span",{className:`h-2 w-2 rounded-full ${S?"bg-emerald-400":"bg-ink-faint"}`,"aria-hidden":"true"}),S?"Live":"Paused"]})}),y.jsx(Xe,{text:"Refresh now",block:!1,children:y.jsx("button",{type:"button",onClick:()=>void ne(),disabled:v,className:"rounded-lg border border-line bg-elevated p-2 text-ink-muted hover:text-ink disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(Md,{className:`h-4 w-4 ${v?"animate-spin":""}`,"aria-hidden":"true"})})}),y.jsx(Xe,{text:"Copy visible lines",block:!1,children:y.jsx("button",{type:"button",onClick:()=>void $(),disabled:i.length===0,className:"rounded-lg border border-line bg-elevated p-2 text-ink-muted hover:text-ink disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(Fn,{className:"h-4 w-4","aria-hidden":"true"})})}),y.jsx(Xe,{text:"Open log file in the default application",block:!1,children:y.jsx("button",{type:"button",onClick:()=>{t==null||t(),e()},className:"rounded-lg border border-line bg-elevated p-2 text-ink-muted hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(iy,{className:"h-4 w-4","aria-hidden":"true"})})}),y.jsx(Xe,{text:"Close",block:!1,children:y.jsx("button",{ref:D,type:"button",onClick:e,className:"rounded-lg p-2 text-ink-muted hover:bg-hover-surface hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(ri,{className:"h-4 w-4","aria-hidden":"true"})})})]})]}),y.jsxs("div",{ref:j,onScroll:ie,className:"min-h-0 flex-1 overflow-y-auto overscroll-contain bg-app px-2 py-2 font-mono text-xs leading-relaxed sm:px-3",children:[y.jsxs("div",{className:"sticky top-0 z-10 mb-1 flex items-center gap-2 rounded-md border border-line/40 bg-surface/60 px-2 py-1 text-[10px] font-bold uppercase tracking-wider text-ink-muted shadow-sm backdrop-blur-md",role:"row",children:[y.jsx("span",{className:"h-3.5 w-3.5 shrink-0","aria-hidden":"true"}),y.jsx("span",{className:"w-[138px] shrink-0 text-ink/70",children:"Time"}),y.jsx("span",{className:"w-[52px] shrink-0 text-ink/70",children:"Level"}),y.jsx("span",{className:"w-[150px] shrink-0 text-ink/70",children:"Source"}),y.jsx("span",{className:"min-w-0 flex-1 text-ink/70",children:"Message"})]}),O&&y.jsx("p",{role:"alert",className:"px-3 py-6 text-center text-xs text-status-danger-text",children:O}),!O&&i.length===0&&!v&&y.jsx("p",{className:"px-3 py-6 text-center text-xs text-ink-faint",children:"No log entries match the current filters."}),y.jsx("ul",{className:"space-y-0.5",children:i.map((J,Y)=>{const T=Y2[J.level]??Y2.UNKNOWN,he=T.icon,ye=J.level==="ERROR"||J.level==="CRITICAL";return y.jsxs("li",{className:`group flex items-start gap-2 rounded px-2 py-1 ${ye?"bg-status-danger-bg/40":"hover:bg-elevated/50"}`,children:[y.jsx("span",{className:T.className,children:y.jsx(he,{className:"mt-0.5 h-3.5 w-3.5","aria-hidden":"true"})}),y.jsx("span",{className:"w-[138px] shrink-0 text-ink-faint",children:J.timestamp}),y.jsx("span",{className:`w-[52px] shrink-0 text-[10px] font-semibold ${T.className}`,children:J.level}),y.jsx("span",{className:"w-[150px] shrink-0 truncate text-ink-faint",title:J.source,children:J.source}),y.jsx("span",{className:"min-w-0 flex-1 break-words text-ink-secondary",children:J.message})]},`${Y}-${J.raw}`)})})]}),y.jsx("div",{className:"border-t border-line/60 bg-elevated/50 px-5 py-2.5 text-[11px] text-ink-faint shadow-sm backdrop-blur-md sm:px-6",children:y.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[y.jsx("span",{className:"mr-auto min-w-0 max-w-full basis-full truncate sm:basis-auto",role:"status","aria-atomic":"true",children:v&&i.length===0?"Loading log entries…":`${i.length} of ${K2(c)} shown`}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("div",{className:"flex overflow-hidden rounded-lg border border-line/60 text-[11px] backdrop-blur-sm",role:"group","aria-label":"Filter by log level",children:T8.map(J=>{const Y=d===J.value,T=J.value?oe.get(J.value)??0:i.length;return y.jsxs("button",{type:"button",onClick:()=>m(J.value),"aria-pressed":Y,title:J.value?`Show ${J.value} and above`:"Show all levels",className:`flex items-center gap-1 px-2.5 py-1 font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-indigo-400 ${Y?"bg-indigo-600 text-white":"text-ink-muted hover:bg-elevated hover:text-ink"}`,children:[J.label,y.jsx("span",{className:Y?"text-chip-indigo-text":"text-ink-faint",children:T})]},J.label)})}),y.jsx(Xe,{text:"Scroll to the newest entry",block:!1,children:y.jsxs("button",{type:"button",onClick:()=>P(!0),"aria-pressed":M,className:`flex items-center gap-1.5 rounded-lg border px-2.5 py-1 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400 ${M?"border-chip-indigo-border bg-chip-indigo-bg text-chip-indigo-text":"border-line bg-elevated text-ink-muted hover:text-ink"}`,children:[y.jsx(GC,{className:"h-3.5 w-3.5","aria-hidden":"true"}),y.jsx("span",{className:"hidden sm:inline",children:"Follow tail"})]})})]}),y.jsxs("span",{className:"hidden items-center gap-1.5 lg:flex",children:[y.jsx("span",{className:"hidden sm:inline",children:"Ctrl + Shift + L"}),y.jsx("span",{children:"toggles this viewer"})]})]})})]})}):null}function K2(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function E8({isOpen:n,onClose:e}){const t=E.useRef(null),i=tl({isOpen:n,onClose:e,dialogRef:t});if(!n)return null;const l=[{key:"F5",desc:"Refresh / re-scan file list"},{key:"Ctrl + R",desc:"Reload configuration & scan"},{key:"Enter",desc:"Execute / launch selected file"},{key:"P",desc:"Open properties for selected file"},{key:"↑ / ↓",desc:"Navigate file list"},{key:"Home / End",desc:"Jump to first / last file"},{key:"PageUp / PageDown",desc:"Page through the file list"},{key:"Ctrl + D",desc:"Focus Directory field"},{key:"Ctrl + E",desc:"Focus Extension field"},{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"},{key:"Ctrl + Shift + B",desc:"Open webcam / camera barcode scanner"},{key:"Ctrl + T",desc:"Open auto-rescan timer modal"},{key:"Ctrl + H",desc:"Set directory to home folder"},{key:"? or Ctrl + /",desc:"Show keyboard shortcuts"},{key:"Y / S / N",desc:"Answer workflow guard: Yes / Skip / No (prompt open)"},{key:"Enter",desc:"Confirm active workflow prompt (prompt open)"},{key:"Escape",desc:"Close dialogs / context menu"}];return y.jsx("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm",children:y.jsxs("div",{ref:t,role:"dialog","aria-modal":"true","aria-label":"Keyboard Shortcuts",onKeyDown:i,className:"animate-modal-in w-[450px] max-w-full rounded-2xl border border-frame-line glass-panel p-5",children:[y.jsxs("div",{className:"mb-4 flex items-center justify-between border-b border-line pb-3",children:[y.jsxs("div",{className:"flex items-center gap-2 font-semibold text-ink",children:[y.jsx(WC,{className:"h-5 w-5 text-chip-indigo-text"}),y.jsx("span",{children:"Keyboard Shortcuts"})]}),y.jsx("button",{onClick:e,className:"focus-ring rounded-lg p-1 text-ink-muted hover:bg-elevated hover:text-ink",children:y.jsx(ri,{className:"h-4 w-4"})})]}),y.jsx("div",{className:"max-h-[60vh] space-y-2 overflow-y-auto pr-1 text-xs",children:l.map(({key:o,desc:a})=>y.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-elevated/50 px-3 py-2",children:[y.jsx("span",{className:"text-ink-secondary",children:a}),y.jsx("kbd",{className:"rounded bg-app px-2 py-0.5 font-mono text-[11px] font-semibold text-chip-indigo-text border border-line",children:o})]},o))}),y.jsx("div",{className:"mt-5 flex justify-end",children:y.jsx("button",{onClick:e,className:"btn btn-primary rounded-lg px-4 py-2 font-semibold",children:"Close"})})]})})}function M8({isOpen:n,activeConfigPath:e,configExists:t=!0,onClose:i,onLoaded:l}){const[o,a]=E.useState(null),[c,f]=E.useState(""),[d,m]=E.useState(null),[g,b]=E.useState(!1),[v,w]=E.useState(null),S=E.useRef(null),C=E.useRef(null),O=E.useRef(null),_=t===!1;E.useEffect(()=>{var F;if(!n){(F=O.current)==null||F.focus();return}O.current=document.activeElement instanceof HTMLElement?document.activeElement:null,w(null);const j=e??"",H=Math.max(j.lastIndexOf("/"),j.lastIndexOf("\\")),Z=H>0?j.slice(0,H):"";M(Z);const I=requestAnimationFrame(()=>{var A;return(A=C.current)==null?void 0:A.focus()});return()=>{var A;cancelAnimationFrame(I),(A=O.current)==null||A.focus()}},[n,e]);const M=async j=>{b(!0),w(null);try{const H=await DM(j);a(H),f(H.current_path),e&&H.items.some(Z=>Z.path===e)?m(e):m(null)}catch(H){w(H.message||"Navigation failed")}finally{b(!1)}},P=j=>{var F;if(j.key==="Escape"){j.preventDefault(),i();return}if(j.key!=="Tab")return;const H=(F=S.current)==null?void 0:F.querySelectorAll('button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])');if(!(H!=null&&H.length))return;const Z=H[0],I=H[H.length-1];j.shiftKey&&document.activeElement===Z?(j.preventDefault(),I.focus()):!j.shiftKey&&document.activeElement===I&&(j.preventDefault(),Z.focus())},L=async()=>{var H;const j=d||(((H=o==null?void 0:o.items.find(Z=>Z.is_config))==null?void 0:H.path)??null);if(!j){w("Select a configuration file to load.");return}try{b(!0);const Z=await NM(j);l(Z),i()}catch(Z){w(Z.message||"Unable to load configuration")}finally{b(!1)}},D=async()=>{const j=(c||(o==null?void 0:o.current_path)||"").trim();if(!j){w("Choose a directory before creating a configuration.");return}try{b(!0);const H=await AM(j);l(H),i()}catch(H){w(H.message||"Unable to create configuration")}finally{b(!1)}};return n?y.jsx("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/65 p-3 backdrop-blur-sm sm:p-6",onClick:i,children:y.jsxs("div",{ref:S,role:"dialog","aria-modal":"true","aria-labelledby":"load-config-title",onKeyDown:P,className:"animate-modal-in flex h-[min(84dvh,760px)] max-h-[calc(100dvh-1.5rem)] w-[min(94vw,960px)] min-h-0 flex-col overflow-hidden rounded-xl border border-frame-line glass-panel sm:rounded-2xl",onClick:j=>j.stopPropagation(),children:[y.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-line px-4 py-3 sm:px-5",children:[y.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[y.jsx("span",{className:"grid h-9 w-9 shrink-0 place-items-center rounded-lg bg-chip-indigo-bg",children:y.jsx(Vo,{className:"h-5 w-5 text-chip-indigo-text"})}),y.jsxs("div",{className:"min-w-0",children:[y.jsx("h2",{id:"load-config-title",className:"text-sm font-semibold text-ink",children:_?"Create configuration":"Load configuration"}),y.jsx("p",{className:"truncate font-mono text-xs text-ink-muted",children:(o==null?void 0:o.current_path)||""})]})]}),y.jsx(Xe,{text:"Close",block:!1,children:y.jsx("button",{type:"button",onClick:i,"aria-label":"Close configuration modal",className:"grid h-9 w-9 shrink-0 place-items-center rounded-lg text-ink-muted transition-colors hover:bg-elevated hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(ri,{className:"h-4 w-4"})})})]}),_&&y.jsx("div",{className:"border-b border-line bg-chip-indigo-bg/20 px-4 py-3 text-xs text-ink-secondary",children:"No configuration file was found. Create one here?"}),y.jsxs("div",{className:"border-b border-line px-4 py-3 sm:px-5",children:[y.jsx("label",{htmlFor:"config-path-input",className:"mb-1.5 block text-xs font-medium text-ink-secondary",children:"Configuration directory"}),y.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[y.jsx("input",{ref:C,id:"config-path-input",type:"text",value:c,onChange:j=>f(j.target.value),onKeyDown:j=>{j.key==="Enter"&&M(c.trim())},placeholder:"/path/to/directory",className:"h-10 min-w-0 flex-1 rounded-lg border border-line bg-elevated px-2.5 font-mono text-sm text-ink outline-none placeholder:text-ink-faint transition-colors hover:bg-surface-strong focus-visible:border-indigo-500 focus-visible:ring-2 focus-visible:ring-indigo-500/30"}),y.jsx("button",{type:"button",onClick:()=>M(c.trim()),className:"inline-flex h-10 shrink-0 items-center gap-1.5 rounded-lg border border-line bg-elevated px-3.5 text-sm font-medium text-ink-secondary transition-colors hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:"Go"}),y.jsx(Xe,{text:"Home directory",block:!1,children:y.jsx("button",{type:"button",onClick:()=>M(""),"aria-label":"Home directory",className:"grid h-10 w-10 shrink-0 place-items-center rounded-lg border border-line bg-elevated text-ink-secondary transition-colors hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(Ed,{className:"h-4 w-4"})})}),(o==null?void 0:o.parent_path)&&y.jsx(Xe,{text:"Parent directory",block:!1,children:y.jsx("button",{type:"button",onClick:()=>M(o.parent_path),"aria-label":"Parent directory",className:"grid h-10 w-10 shrink-0 place-items-center rounded-lg border border-line bg-elevated text-ink-secondary transition-colors hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(Ad,{className:"h-4 w-4 rotate-180"})})})]})]}),y.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-2 py-2 sm:px-3 sm:py-3","aria-busy":g,children:g?y.jsxs("div",{className:"flex h-full items-center justify-center gap-2.5 text-sm text-ink-muted",children:[y.jsx(Yr,{className:"h-5 w-5 animate-spin text-chip-indigo-text"}),y.jsx("span",{role:"status",children:"Loading configuration files…"})]}):v?y.jsxs("div",{role:"alert",className:"flex h-full flex-col items-center justify-center gap-2.5 text-center",children:[y.jsx("p",{className:"text-sm text-status-danger-text",children:v}),y.jsx("button",{type:"button",onClick:()=>M(c||(o==null?void 0:o.current_path)||""),className:"min-h-10 rounded-lg border border-line bg-elevated px-3.5 text-sm text-ink-secondary hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:"Retry"})]}):y.jsxs("ul",{className:"space-y-1",children:[o==null?void 0:o.items.map(j=>{if(j.is_dir)return y.jsx("li",{children:y.jsx("button",{onClick:()=>M(j.path),onDoubleClick:()=>M(j.path),className:"flex w-full items-center justify-between rounded-md px-3 py-1.5 text-left text-xs text-ink-secondary hover:bg-elevated",children:y.jsxs("span",{className:"flex items-center gap-2",children:[y.jsx(lu,{className:"h-3.5 w-3.5 text-chip-indigo-text"}),j.name]})})},j.path);const H=d===j.path;return y.jsx("li",{children:y.jsxs("button",{type:"button",onClick:()=>m(j.path),"aria-pressed":H,className:`flex w-full items-center justify-between rounded-lg px-3 py-1.5 text-left text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-indigo-400 ${H?"bg-chip-indigo-bg text-chip-indigo-text":"text-ink-secondary hover:bg-elevated hover:text-ink"}`,children:[y.jsxs("span",{className:"flex min-w-0 items-center gap-2.5",children:[y.jsx(sa,{className:"h-5 w-5 shrink-0 text-chip-amber-text"}),y.jsx("span",{className:"truncate",children:j.name})]}),j.is_config&&y.jsx(Vo,{className:"h-4 w-4 shrink-0 text-chip-indigo-text"}),H&&y.jsx(Sr,{className:"h-4 w-4 shrink-0 text-chip-indigo-text"})]})},j.path)}),(o==null?void 0:o.items.filter(j=>j.is_config).length)===0&&y.jsxs("li",{className:"flex h-full min-h-36 flex-col items-center justify-center gap-2.5 text-center text-sm text-ink-muted",children:[y.jsx(sa,{className:"h-7 w-7 text-ink-faint"}),"No configuration files found"]})]})}),y.jsxs("div",{className:"flex flex-col gap-2 border-t border-line px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-5",children:[y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsx("p",{className:"mb-0.5 text-xs font-medium text-ink-muted",children:"Selected file"}),y.jsx("p",{className:"truncate font-mono text-sm text-ink",title:d||c,children:d||c||"—"})]}),y.jsxs("div",{className:"flex shrink-0 justify-end gap-1.5",children:[y.jsx("button",{type:"button",onClick:i,className:"min-h-10 rounded-lg border border-line bg-elevated px-3.5 text-sm text-ink-secondary transition-colors hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:"Cancel"}),_?y.jsxs("button",{type:"button",onClick:D,disabled:!c.trim(),className:"btn btn-primary min-h-10 rounded-lg px-4 text-sm font-semibold",children:[y.jsx(Vo,{className:"h-4 w-4"}),"Create configuration"]}):y.jsxs("button",{type:"button",onClick:L,disabled:!d,className:"btn btn-primary min-h-10 rounded-lg px-4 text-sm font-semibold",children:[y.jsx(Vo,{className:"h-4 w-4"}),"Load configuration"]})]})]})]})}):null}function dA({isOpen:n,onClose:e,initialFilePath:t,md5:i}){const[l,o]=E.useState(null),[a,c]=E.useState(""),[f,d]=E.useState([]),[m,g]=E.useState(!1),[b,v]=E.useState(null),[w,S]=E.useState(null),[C,O]=E.useState(!1),[_,M]=E.useState(!1),[P,L]=E.useState(null),D=E.useRef(null),j=E.useRef(0),H=E.useRef(null),Z=tl({isOpen:n,onClose:e,dialogRef:D});E.useEffect(()=>{n||H.current!==null&&(window.clearTimeout(H.current),H.current=null)},[n]),E.useEffect(()=>{if(!n)return;async function T(){if(t){g(!0);try{const he=await Lx({filePath:t});o(he.image),c(he.content),I(he.content)}catch(he){v(he.message)}finally{g(!1)}}}T()},[n,t]);const I=T=>{const he=T.split(";").map(ye=>{const B=ye.split("=");return{key:B[0]||"",value:B[1]||""}}).filter(ye=>ye.key||ye.value);d(he)},F=async T=>{const he=++j.current;try{const ye=await Lx({content:T});if(j.current!==he)return;o(ye.image),S(null)}catch(ye){if(j.current!==he)return;S(ye instanceof Error?ye.message:"Failed to generate the barcode")}},A=T=>{const he=T.filter(ye=>ye.key.trim()).map(ye=>`${ye.key.trim()}=${ye.value.trim()}`).join(";");if(c(he),H.current!==null&&(window.clearTimeout(H.current),H.current=null),!he){j.current+=1,o(null),S(null);return}H.current=window.setTimeout(()=>void F(he),250)},ne=(T,he,ye)=>{const B=[...f];B[T][he]=ye,d(B),A(B)},ae=()=>{const T=[...f,{key:"",value:""}];d(T)},ie=T=>{const he=f.filter((ye,B)=>B!==T);d(he),A(he)},$=()=>{if(!i||f.some(he=>he.key.toLowerCase()==="md5"))return;const T=[...f,{key:"md5",value:i}];d(T),A(T)},oe=async()=>{if(l){L("Saving…");try{const T=await BM(l,`profiles-qr-${Date.now()}.png`);L(T.path||T.message)}catch(T){L(`Save failed: ${(T==null?void 0:T.message)??T}`)}finally{setTimeout(()=>L(null),6e3)}}},J=async()=>{try{await navigator.clipboard.writeText(a),O(!0),setTimeout(()=>O(!1),2e3)}catch(T){console.error("Copy failed",T)}},Y=async()=>{if(l)try{const he=await(await fetch(l)).blob();await navigator.clipboard.write([new ClipboardItem({[he.type]:he})]),M(!0),setTimeout(()=>M(!1),2e3)}catch(T){console.error("Image copy failed",T)}};return n?y.jsx("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 p-4",onClick:e,children:y.jsxs("div",{ref:D,role:"dialog","aria-modal":"true","aria-label":"QR Code Settings",onKeyDown:Z,className:"animate-modal-in w-full max-w-md rounded-xl border border-frame-line glass-panel p-6",onClick:T=>T.stopPropagation(),children:[y.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[y.jsx("h3",{className:"text-sm font-semibold text-ink",children:"QR Code Settings"}),y.jsx("button",{onClick:e,className:"focus-ring rounded-md p-1 text-ink-muted hover:bg-elevated hover:text-ink",children:y.jsx(ri,{className:"h-4 w-4"})})]}),m?y.jsx("div",{className:"flex h-48 items-center justify-center",children:y.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-600 border-t-transparent"})}):b?y.jsx("div",{className:"rounded-md border border-status-danger-border bg-status-danger-bg p-4 text-center text-xs text-status-danger-text",children:b}):y.jsxs("div",{className:"space-y-6",children:[y.jsxs("div",{className:"flex flex-col items-center gap-4",children:[y.jsxs("div",{className:"relative group",children:[y.jsx("div",{className:"h-48 w-48 overflow-hidden rounded-lg border border-line bg-white p-2",children:l?y.jsx("img",{src:l,alt:"QR Code",className:"h-full w-full object-contain"}):y.jsx("div",{className:"flex h-full items-center justify-center text-xs text-slate-400",children:"No content"})}),l&&y.jsx("div",{className:"absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/20 rounded-lg",children:y.jsxs("button",{onClick:Y,className:"focus-ring flex items-center gap-2 rounded-md bg-white/90 p-2 text-xs font-medium text-slate-900 shadow-sm hover:bg-white",children:[_?y.jsx(Sr,{className:"h-3.5 w-3.5"}):y.jsx(Fn,{className:"h-3.5 w-3.5"}),_?"Copied":"Copy Image"]})})]}),y.jsxs("div",{className:"flex w-full gap-2",children:[y.jsxs("button",{onClick:J,className:"btn btn-secondary flex-1 px-3 py-1.5",children:[C?y.jsx(Sr,{className:"h-3.5 w-3.5 text-status-success-text"}):y.jsx(Fn,{className:"h-3.5 w-3.5"}),"Copy Content"]}),y.jsxs("button",{onClick:oe,disabled:!l,className:"btn btn-primary flex-1 px-3 py-1.5",children:[y.jsx(KC,{className:"h-3.5 w-3.5"}),"Save Image"]})]}),P&&y.jsx("p",{className:"break-all text-center text-[11px] text-ink-muted",role:"status",children:P}),w&&y.jsx("p",{role:"alert",className:"break-all text-center text-[11px] text-status-danger-text",children:w})]}),y.jsxs("div",{className:"space-y-3",children:[y.jsxs("div",{className:"flex items-center justify-between",children:[y.jsx("label",{className:"text-xs font-medium text-ink-muted uppercase tracking-wider",children:"Payload Fields"}),y.jsxs("div",{className:"flex gap-2",children:[i&&!f.some(T=>T.key==="md5")&&y.jsxs("button",{onClick:$,className:"btn-chip flex items-center gap-1 rounded px-2 py-0.5 text-[10px] font-bold text-chip-purple-text border border-chip-purple-border",children:[y.jsx(Qo,{className:"h-3 w-3"})," Inc. MD5"]}),y.jsxs("button",{onClick:ae,className:"btn-chip flex items-center gap-1 rounded px-2 py-0.5 text-[10px] font-bold text-chip-indigo-text border border-chip-indigo-border",children:[y.jsx(lD,{className:"h-3 w-3"})," Add Field"]})]})]}),y.jsxs("div",{className:"max-h-48 space-y-2 overflow-y-auto pr-1 custom-scrollbar",children:[f.map((T,he)=>y.jsxs("div",{className:"flex gap-2 items-center slide-in",children:[y.jsx("input",{type:"text",placeholder:"key",value:T.key,onChange:ye=>ne(he,"key",ye.target.value),className:"w-1/3 rounded border border-line bg-elevated px-2 py-1 text-xs text-ink focus:border-indigo-500 focus:outline-none"}),y.jsx("input",{type:"text",placeholder:"value",value:T.value,onChange:ye=>ne(he,"value",ye.target.value),className:"flex-1 rounded border border-line bg-elevated px-2 py-1 text-xs text-ink focus:border-indigo-500 focus:outline-none"}),y.jsx("button",{onClick:()=>ie(he),className:"p-1 text-ink-muted hover:text-status-danger-text transition-colors","aria-label":"Remove field",children:y.jsx(nO,{className:"h-3.5 w-3.5"})})]},he)),f.length===0&&y.jsx("p",{className:"text-center py-4 text-xs text-ink-muted italic",children:"No fields defined"})]})]}),y.jsxs("div",{className:"pt-2 border-t border-line",children:[y.jsx("label",{className:"text-[10px] font-medium text-ink-muted uppercase tracking-wider block mb-1.5",children:"Raw Preview"}),y.jsx("div",{className:"rounded bg-elevated p-2 font-mono text-[10px] text-ink-secondary break-all border border-line",children:a||y.jsx("span",{className:"italic text-ink-muted/50",children:"empty"})})]})]})]})}):null}const W2=["Bytes","KB","MB","GB","TB"];function mA(n){if(n===0)return"0 Bytes";const e=1024,t=Math.max(0,Math.min(W2.length-1,Math.floor(Math.log(n)/Math.log(e))));return parseFloat((n/Math.pow(e,t)).toFixed(2))+" "+W2[t]}function D8(n){const e=Math.max(n.lastIndexOf("\\"),n.lastIndexOf("/"));return e===-1?"":n.slice(0,e)}function j8(n){const e=[`File Properties: ${n.name}`,`Path: ${n.path}`,`Type: ${n.type}`,`Size: ${mA(n.size_bytes)}`,`Created: ${n.created}`,`Modified: ${n.modified}`];return n.md5&&e.push(`MD5: ${n.md5}`),n.sha256&&e.push(`SHA256: ${n.sha256}`),e.join(` +`))}catch{}},oe=E.useMemo(()=>{const J=new Map;for(const Y of i)J.set(Y.level,(J.get(Y.level)??0)+1);return J},[i]);return n?y.jsx("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/65 p-3 backdrop-blur-sm sm:p-6",onClick:e,children:y.jsxs("div",{ref:L,role:"dialog","aria-modal":"true","aria-labelledby":"log-viewer-title",onKeyDown:ae,className:"animate-modal-in flex h-[min(84dvh,760px)] w-[clamp(560px,85vw,1500px)] min-h-0 flex-col overflow-hidden rounded-xl border border-frame-line glass-panel sm:rounded-2xl",onClick:J=>J.stopPropagation(),children:[y.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-b border-line px-5 py-4 sm:px-6",children:[y.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[y.jsx("span",{className:"grid h-10 w-10 shrink-0 place-items-center rounded-lg bg-chip-indigo-bg",children:y.jsx(sa,{className:"h-5 w-5 text-chip-indigo-text","aria-hidden":"true"})}),y.jsxs("div",{className:"min-w-0",children:[y.jsx("h2",{id:"log-viewer-title",className:"text-base font-semibold text-ink",children:"Application logs"}),y.jsxs("p",{className:"truncate font-mono text-xs text-ink-muted",children:[o,y.jsxs("span",{className:"text-ink-faint",children:[" · ",K2(c)]})]})]})]}),y.jsxs("div",{className:"relative min-w-[220px] flex-1",children:[y.jsx(JC,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-ink-faint","aria-hidden":"true"}),y.jsx("input",{ref:H,type:"search",value:g,onChange:J=>b(J.target.value),placeholder:"Filter log lines…","aria-label":"Filter log lines",className:"w-full rounded-lg border border-line bg-elevated py-1.5 pl-8 pr-2.5 font-mono text-xs text-ink placeholder:text-ink-faint focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400"})]}),y.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[y.jsx(Xe,{text:S?"Pause live tail":"Resume live tail",block:!1,children:y.jsxs("button",{type:"button",onClick:()=>C(J=>!J),"aria-pressed":S,className:`flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400 ${S?"border-status-success-border bg-status-success-bg text-status-success-text":"border-line bg-elevated text-ink-muted hover:text-ink"}`,children:[y.jsx("span",{className:`h-2 w-2 rounded-full ${S?"bg-emerald-400":"bg-ink-faint"}`,"aria-hidden":"true"}),S?"Live":"Paused"]})}),y.jsx(Xe,{text:"Refresh now",block:!1,children:y.jsx("button",{type:"button",onClick:()=>void ne(),disabled:v,className:"rounded-lg border border-line bg-elevated p-2 text-ink-muted hover:text-ink disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(Md,{className:`h-4 w-4 ${v?"animate-spin":""}`,"aria-hidden":"true"})})}),y.jsx(Xe,{text:"Copy visible lines",block:!1,children:y.jsx("button",{type:"button",onClick:()=>void $(),disabled:i.length===0,className:"rounded-lg border border-line bg-elevated p-2 text-ink-muted hover:text-ink disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(Fn,{className:"h-4 w-4","aria-hidden":"true"})})}),y.jsx(Xe,{text:"Open log file in the default application",block:!1,children:y.jsx("button",{type:"button",onClick:()=>{t==null||t(),e()},className:"rounded-lg border border-line bg-elevated p-2 text-ink-muted hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(iy,{className:"h-4 w-4","aria-hidden":"true"})})}),y.jsx(Xe,{text:"Close",block:!1,children:y.jsx("button",{ref:D,type:"button",onClick:e,className:"rounded-lg p-2 text-ink-muted hover:bg-hover-surface hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(ri,{className:"h-4 w-4","aria-hidden":"true"})})})]})]}),y.jsxs("div",{ref:j,onScroll:ie,className:"min-h-0 flex-1 overflow-y-auto overscroll-contain bg-app px-2 py-2 font-mono text-xs leading-relaxed sm:px-3",children:[y.jsxs("div",{className:"sticky top-0 z-10 mb-1 flex items-center gap-2 rounded-md border border-line/40 bg-surface/60 px-2 py-1 text-[10px] font-bold uppercase tracking-wider text-ink-muted shadow-sm backdrop-blur-md",role:"row",children:[y.jsx("span",{className:"h-3.5 w-3.5 shrink-0","aria-hidden":"true"}),y.jsx("span",{className:"w-[138px] shrink-0 text-ink/70",children:"Time"}),y.jsx("span",{className:"w-[52px] shrink-0 text-ink/70",children:"Level"}),y.jsx("span",{className:"w-[150px] shrink-0 text-ink/70",children:"Source"}),y.jsx("span",{className:"min-w-0 flex-1 text-ink/70",children:"Message"})]}),O&&y.jsx("p",{role:"alert",className:"px-3 py-6 text-center text-xs text-status-danger-text",children:O}),!O&&i.length===0&&!v&&y.jsx("p",{className:"px-3 py-6 text-center text-xs text-ink-faint",children:"No log entries match the current filters."}),y.jsx("ul",{className:"space-y-0.5",children:i.map((J,Y)=>{const T=Y2[J.level]??Y2.UNKNOWN,he=T.icon,ye=J.level==="ERROR"||J.level==="CRITICAL";return y.jsxs("li",{className:`group flex items-start gap-2 rounded px-2 py-1 ${ye?"bg-status-danger-bg/40":"hover:bg-elevated/50"}`,children:[y.jsx("span",{className:T.className,children:y.jsx(he,{className:"mt-0.5 h-3.5 w-3.5","aria-hidden":"true"})}),y.jsx("span",{className:"w-[138px] shrink-0 text-ink-faint",children:J.timestamp}),y.jsx("span",{className:`w-[52px] shrink-0 text-[10px] font-semibold ${T.className}`,children:J.level}),y.jsx("span",{className:"w-[150px] shrink-0 truncate text-ink-faint",title:J.source,children:J.source}),y.jsx("span",{className:"min-w-0 flex-1 break-words text-ink-secondary",children:J.message})]},`${Y}-${J.raw}`)})})]}),y.jsx("div",{className:"border-t border-line/60 bg-elevated/50 px-5 py-2.5 text-[11px] text-ink-faint shadow-sm backdrop-blur-md sm:px-6",children:y.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[y.jsx("span",{className:"mr-auto min-w-0 max-w-full basis-full truncate sm:basis-auto",role:"status","aria-atomic":"true",children:v&&i.length===0?"Loading log entries…":`${i.length} of ${K2(c)} shown`}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("div",{className:"flex overflow-hidden rounded-lg border border-line/60 text-[11px] backdrop-blur-sm",role:"group","aria-label":"Filter by log level",children:T8.map(J=>{const Y=d===J.value,T=J.value?oe.get(J.value)??0:i.length;return y.jsxs("button",{type:"button",onClick:()=>m(J.value),"aria-pressed":Y,title:J.value?`Show ${J.value} and above`:"Show all levels",className:`flex items-center gap-1 px-2.5 py-1 font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-indigo-400 ${Y?"bg-indigo-600 text-white":"text-ink-muted hover:bg-elevated hover:text-ink"}`,children:[J.label,y.jsx("span",{className:Y?"text-chip-indigo-text":"text-ink-faint",children:T})]},J.label)})}),y.jsx(Xe,{text:"Scroll to the newest entry",block:!1,children:y.jsxs("button",{type:"button",onClick:()=>P(!0),"aria-pressed":M,className:`flex items-center gap-1.5 rounded-lg border px-2.5 py-1 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400 ${M?"border-chip-indigo-border bg-chip-indigo-bg text-chip-indigo-text":"border-line bg-elevated text-ink-muted hover:text-ink"}`,children:[y.jsx(GC,{className:"h-3.5 w-3.5","aria-hidden":"true"}),y.jsx("span",{className:"hidden sm:inline",children:"Follow tail"})]})})]}),y.jsxs("span",{className:"hidden items-center gap-1.5 lg:flex",children:[y.jsx("span",{className:"hidden sm:inline",children:"Ctrl + Shift + L"}),y.jsx("span",{children:"toggles this viewer"})]})]})})]})}):null}function K2(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function E8({isOpen:n,onClose:e}){const t=E.useRef(null),i=tl({isOpen:n,onClose:e,dialogRef:t});if(!n)return null;const l=[{key:"F5",desc:"Refresh / re-scan file list"},{key:"Ctrl + R",desc:"Reload configuration & scan"},{key:"Enter",desc:"Execute / launch selected file"},{key:"P",desc:"Open properties for selected file"},{key:"↑ / ↓",desc:"Navigate file list"},{key:"Home / End",desc:"Jump to first / last file"},{key:"PageUp / PageDown",desc:"Page through the file list"},{key:"Ctrl + D",desc:"Focus Directory field"},{key:"Ctrl + E",desc:"Focus Extension field"},{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"},{key:"Ctrl + Shift + B",desc:"Open webcam / camera barcode scanner"},{key:"Ctrl + T",desc:"Open auto-rescan timer modal"},{key:"Ctrl + H",desc:"Set directory to home folder"},{key:"? or Ctrl + /",desc:"Show keyboard shortcuts"},{key:"Y / S / N",desc:"Answer workflow guard: Yes / Skip / No (prompt open)"},{key:"Enter",desc:"Confirm active workflow prompt (prompt open)"},{key:"Escape",desc:"Close dialogs / context menu"}];return y.jsx("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm",children:y.jsxs("div",{ref:t,role:"dialog","aria-modal":"true","aria-label":"Keyboard Shortcuts",onKeyDown:i,className:"animate-modal-in w-[450px] max-w-full rounded-2xl border border-frame-line glass-panel p-5",children:[y.jsxs("div",{className:"mb-4 flex items-center justify-between border-b border-line pb-3",children:[y.jsxs("div",{className:"flex items-center gap-2 font-semibold text-ink",children:[y.jsx(WC,{className:"h-5 w-5 text-chip-indigo-text"}),y.jsx("span",{children:"Keyboard Shortcuts"})]}),y.jsx("button",{onClick:e,className:"focus-ring rounded-lg p-1 text-ink-muted hover:bg-elevated hover:text-ink",children:y.jsx(ri,{className:"h-4 w-4"})})]}),y.jsx("div",{className:"max-h-[60vh] space-y-2 overflow-y-auto pr-1 text-xs",children:l.map(({key:o,desc:a})=>y.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-elevated/50 px-3 py-2",children:[y.jsx("span",{className:"text-ink-secondary",children:a}),y.jsx("kbd",{className:"rounded bg-app px-2 py-0.5 font-mono text-[11px] font-semibold text-chip-indigo-text border border-line",children:o})]},o))}),y.jsx("div",{className:"mt-5 flex justify-end",children:y.jsx("button",{onClick:e,className:"btn btn-primary rounded-lg px-4 py-2 font-semibold",children:"Close"})})]})})}function M8({isOpen:n,mode:e,activeConfigPath:t,onClose:i,onLoaded:l}){const[o,a]=E.useState(null),[c,f]=E.useState(""),[d,m]=E.useState(null),[g,b]=E.useState(!1),[v,w]=E.useState(null),S=E.useRef(null),C=E.useRef(null),O=E.useRef(null),_=e==="create";E.useEffect(()=>{var F;if(!n){(F=O.current)==null||F.focus();return}O.current=document.activeElement instanceof HTMLElement?document.activeElement:null,w(null);const j=t??"",H=Math.max(j.lastIndexOf("/"),j.lastIndexOf("\\")),Z=H>0?j.slice(0,H):"";M(Z);const I=requestAnimationFrame(()=>{var A;return(A=C.current)==null?void 0:A.focus()});return()=>{var A;cancelAnimationFrame(I),(A=O.current)==null||A.focus()}},[n,t]);const M=async j=>{b(!0),w(null);try{const H=await DM(j);a(H),f(H.current_path),t&&H.items.some(Z=>Z.path===t)?m(t):m(null)}catch(H){w(H.message||"Navigation failed")}finally{b(!1)}},P=j=>{var F;if(j.key==="Escape"){j.preventDefault(),i();return}if(j.key!=="Tab")return;const H=(F=S.current)==null?void 0:F.querySelectorAll('button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])');if(!(H!=null&&H.length))return;const Z=H[0],I=H[H.length-1];j.shiftKey&&document.activeElement===Z?(j.preventDefault(),I.focus()):!j.shiftKey&&document.activeElement===I&&(j.preventDefault(),Z.focus())},L=async()=>{var H;const j=d||(((H=o==null?void 0:o.items.find(Z=>Z.is_config))==null?void 0:H.path)??null);if(!j){w("Select a configuration file to load.");return}try{b(!0);const Z=await NM(j);l(Z),i()}catch(Z){w(Z.message||"Unable to load configuration")}finally{b(!1)}},D=async()=>{const j=(c||(o==null?void 0:o.current_path)||"").trim();if(!j){w("Choose a directory before creating a configuration.");return}try{b(!0);const H=await AM(j);l(H),i()}catch(H){w(H.message||"Unable to create configuration")}finally{b(!1)}};return n?y.jsx("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/65 p-3 backdrop-blur-sm sm:p-6",onClick:i,children:y.jsxs("div",{ref:S,role:"dialog","aria-modal":"true","aria-labelledby":"load-config-title",onKeyDown:P,className:"animate-modal-in flex h-[min(84dvh,760px)] max-h-[calc(100dvh-1.5rem)] w-[min(94vw,960px)] min-h-0 flex-col overflow-hidden rounded-xl border border-frame-line glass-panel sm:rounded-2xl",onClick:j=>j.stopPropagation(),children:[y.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-line px-4 py-3 sm:px-5",children:[y.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[y.jsx("span",{className:"grid h-9 w-9 shrink-0 place-items-center rounded-lg bg-chip-indigo-bg",children:y.jsx(Vo,{className:"h-5 w-5 text-chip-indigo-text"})}),y.jsxs("div",{className:"min-w-0",children:[y.jsx("h2",{id:"load-config-title",className:"text-sm font-semibold text-ink",children:_?"Create configuration":"Load configuration"}),y.jsx("p",{className:"truncate font-mono text-xs text-ink-muted",children:(o==null?void 0:o.current_path)||""})]})]}),y.jsx(Xe,{text:"Close",block:!1,children:y.jsx("button",{type:"button",onClick:i,"aria-label":"Close configuration modal",className:"grid h-9 w-9 shrink-0 place-items-center rounded-lg text-ink-muted transition-colors hover:bg-elevated hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(ri,{className:"h-4 w-4"})})})]}),_&&y.jsx("div",{className:"border-b border-line bg-chip-indigo-bg/20 px-4 py-3 text-xs text-ink-secondary",children:"No configuration file was found. Create one here?"}),y.jsxs("div",{className:"border-b border-line px-4 py-3 sm:px-5",children:[y.jsx("label",{htmlFor:"config-path-input",className:"mb-1.5 block text-xs font-medium text-ink-secondary",children:"Configuration directory"}),y.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[y.jsx("input",{ref:C,id:"config-path-input",type:"text",value:c,onChange:j=>f(j.target.value),onKeyDown:j=>{j.key==="Enter"&&M(c.trim())},placeholder:"/path/to/directory",className:"h-10 min-w-0 flex-1 rounded-lg border border-line bg-elevated px-2.5 font-mono text-sm text-ink outline-none placeholder:text-ink-faint transition-colors hover:bg-surface-strong focus-visible:border-indigo-500 focus-visible:ring-2 focus-visible:ring-indigo-500/30"}),y.jsx("button",{type:"button",onClick:()=>M(c.trim()),className:"inline-flex h-10 shrink-0 items-center gap-1.5 rounded-lg border border-line bg-elevated px-3.5 text-sm font-medium text-ink-secondary transition-colors hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:"Go"}),y.jsx(Xe,{text:"Home directory",block:!1,children:y.jsx("button",{type:"button",onClick:()=>M(""),"aria-label":"Home directory",className:"grid h-10 w-10 shrink-0 place-items-center rounded-lg border border-line bg-elevated text-ink-secondary transition-colors hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(Ed,{className:"h-4 w-4"})})}),(o==null?void 0:o.parent_path)&&y.jsx(Xe,{text:"Parent directory",block:!1,children:y.jsx("button",{type:"button",onClick:()=>M(o.parent_path),"aria-label":"Parent directory",className:"grid h-10 w-10 shrink-0 place-items-center rounded-lg border border-line bg-elevated text-ink-secondary transition-colors hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:y.jsx(Ad,{className:"h-4 w-4 rotate-180"})})})]})]}),y.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-2 py-2 sm:px-3 sm:py-3","aria-busy":g,children:g?y.jsxs("div",{className:"flex h-full items-center justify-center gap-2.5 text-sm text-ink-muted",children:[y.jsx(Yr,{className:"h-5 w-5 animate-spin text-chip-indigo-text"}),y.jsx("span",{role:"status",children:"Loading configuration files…"})]}):v?y.jsxs("div",{role:"alert",className:"flex h-full flex-col items-center justify-center gap-2.5 text-center",children:[y.jsx("p",{className:"text-sm text-status-danger-text",children:v}),y.jsx("button",{type:"button",onClick:()=>M(c||(o==null?void 0:o.current_path)||""),className:"min-h-10 rounded-lg border border-line bg-elevated px-3.5 text-sm text-ink-secondary hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:"Retry"})]}):y.jsxs("ul",{className:"space-y-1",children:[o==null?void 0:o.items.map(j=>{if(j.is_dir)return y.jsx("li",{children:y.jsx("button",{onClick:()=>M(j.path),onDoubleClick:()=>M(j.path),className:"flex w-full items-center justify-between rounded-md px-3 py-1.5 text-left text-xs text-ink-secondary hover:bg-elevated",children:y.jsxs("span",{className:"flex items-center gap-2",children:[y.jsx(lu,{className:"h-3.5 w-3.5 text-chip-indigo-text"}),j.name]})})},j.path);const H=d===j.path;return y.jsx("li",{children:y.jsxs("button",{type:"button",onClick:()=>m(j.path),"aria-pressed":H,className:`flex w-full items-center justify-between rounded-lg px-3 py-1.5 text-left text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-indigo-400 ${H?"bg-chip-indigo-bg text-chip-indigo-text":"text-ink-secondary hover:bg-elevated hover:text-ink"}`,children:[y.jsxs("span",{className:"flex min-w-0 items-center gap-2.5",children:[y.jsx(sa,{className:"h-5 w-5 shrink-0 text-chip-amber-text"}),y.jsx("span",{className:"truncate",children:j.name})]}),j.is_config&&y.jsx(Vo,{className:"h-4 w-4 shrink-0 text-chip-indigo-text"}),H&&y.jsx(Sr,{className:"h-4 w-4 shrink-0 text-chip-indigo-text"})]})},j.path)}),(o==null?void 0:o.items.filter(j=>j.is_config).length)===0&&y.jsxs("li",{className:"flex h-full min-h-36 flex-col items-center justify-center gap-2.5 text-center text-sm text-ink-muted",children:[y.jsx(sa,{className:"h-7 w-7 text-ink-faint"}),"No configuration files found"]})]})}),y.jsxs("div",{className:"flex flex-col gap-2 border-t border-line px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-5",children:[y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsx("p",{className:"mb-0.5 text-xs font-medium text-ink-muted",children:"Selected file"}),y.jsx("p",{className:"truncate font-mono text-sm text-ink",title:d||c,children:d||c||"—"})]}),y.jsxs("div",{className:"flex shrink-0 justify-end gap-1.5",children:[y.jsx("button",{type:"button",onClick:i,className:"min-h-10 rounded-lg border border-line bg-elevated px-3.5 text-sm text-ink-secondary transition-colors hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:"Cancel"}),_?y.jsxs("button",{type:"button",onClick:D,disabled:!c.trim(),className:"btn btn-primary min-h-10 rounded-lg px-4 text-sm font-semibold",children:[y.jsx(Vo,{className:"h-4 w-4"}),"Create configuration"]}):y.jsxs("button",{type:"button",onClick:L,disabled:!d,className:"btn btn-primary min-h-10 rounded-lg px-4 text-sm font-semibold",children:[y.jsx(Vo,{className:"h-4 w-4"}),"Load configuration"]})]})]})]})}):null}function dA({isOpen:n,onClose:e,initialFilePath:t,md5:i}){const[l,o]=E.useState(null),[a,c]=E.useState(""),[f,d]=E.useState([]),[m,g]=E.useState(!1),[b,v]=E.useState(null),[w,S]=E.useState(null),[C,O]=E.useState(!1),[_,M]=E.useState(!1),[P,L]=E.useState(null),D=E.useRef(null),j=E.useRef(0),H=E.useRef(null),Z=tl({isOpen:n,onClose:e,dialogRef:D});E.useEffect(()=>{n||H.current!==null&&(window.clearTimeout(H.current),H.current=null)},[n]),E.useEffect(()=>{if(!n)return;async function T(){if(t){g(!0);try{const he=await Lx({filePath:t});o(he.image),c(he.content),I(he.content)}catch(he){v(he.message)}finally{g(!1)}}}T()},[n,t]);const I=T=>{const he=T.split(";").map(ye=>{const B=ye.split("=");return{key:B[0]||"",value:B[1]||""}}).filter(ye=>ye.key||ye.value);d(he)},F=async T=>{const he=++j.current;try{const ye=await Lx({content:T});if(j.current!==he)return;o(ye.image),S(null)}catch(ye){if(j.current!==he)return;S(ye instanceof Error?ye.message:"Failed to generate the barcode")}},A=T=>{const he=T.filter(ye=>ye.key.trim()).map(ye=>`${ye.key.trim()}=${ye.value.trim()}`).join(";");if(c(he),H.current!==null&&(window.clearTimeout(H.current),H.current=null),!he){j.current+=1,o(null),S(null);return}H.current=window.setTimeout(()=>void F(he),250)},ne=(T,he,ye)=>{const B=[...f];B[T][he]=ye,d(B),A(B)},ae=()=>{const T=[...f,{key:"",value:""}];d(T)},ie=T=>{const he=f.filter((ye,B)=>B!==T);d(he),A(he)},$=()=>{if(!i||f.some(he=>he.key.toLowerCase()==="md5"))return;const T=[...f,{key:"md5",value:i}];d(T),A(T)},oe=async()=>{if(l){L("Saving…");try{const T=await BM(l,`profiles-qr-${Date.now()}.png`);L(T.path||T.message)}catch(T){L(`Save failed: ${(T==null?void 0:T.message)??T}`)}finally{setTimeout(()=>L(null),6e3)}}},J=async()=>{try{await navigator.clipboard.writeText(a),O(!0),setTimeout(()=>O(!1),2e3)}catch(T){console.error("Copy failed",T)}},Y=async()=>{if(l)try{const he=await(await fetch(l)).blob();await navigator.clipboard.write([new ClipboardItem({[he.type]:he})]),M(!0),setTimeout(()=>M(!1),2e3)}catch(T){console.error("Image copy failed",T)}};return n?y.jsx("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 p-4",onClick:e,children:y.jsxs("div",{ref:D,role:"dialog","aria-modal":"true","aria-label":"QR Code Settings",onKeyDown:Z,className:"animate-modal-in w-full max-w-md rounded-xl border border-frame-line glass-panel p-6",onClick:T=>T.stopPropagation(),children:[y.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[y.jsx("h3",{className:"text-sm font-semibold text-ink",children:"QR Code Settings"}),y.jsx("button",{onClick:e,className:"focus-ring rounded-md p-1 text-ink-muted hover:bg-elevated hover:text-ink",children:y.jsx(ri,{className:"h-4 w-4"})})]}),m?y.jsx("div",{className:"flex h-48 items-center justify-center",children:y.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-600 border-t-transparent"})}):b?y.jsx("div",{className:"rounded-md border border-status-danger-border bg-status-danger-bg p-4 text-center text-xs text-status-danger-text",children:b}):y.jsxs("div",{className:"space-y-6",children:[y.jsxs("div",{className:"flex flex-col items-center gap-4",children:[y.jsxs("div",{className:"relative group",children:[y.jsx("div",{className:"h-48 w-48 overflow-hidden rounded-lg border border-line bg-white p-2",children:l?y.jsx("img",{src:l,alt:"QR Code",className:"h-full w-full object-contain"}):y.jsx("div",{className:"flex h-full items-center justify-center text-xs text-slate-400",children:"No content"})}),l&&y.jsx("div",{className:"absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/20 rounded-lg",children:y.jsxs("button",{onClick:Y,className:"focus-ring flex items-center gap-2 rounded-md bg-white/90 p-2 text-xs font-medium text-slate-900 shadow-sm hover:bg-white",children:[_?y.jsx(Sr,{className:"h-3.5 w-3.5"}):y.jsx(Fn,{className:"h-3.5 w-3.5"}),_?"Copied":"Copy Image"]})})]}),y.jsxs("div",{className:"flex w-full gap-2",children:[y.jsxs("button",{onClick:J,className:"btn btn-secondary flex-1 px-3 py-1.5",children:[C?y.jsx(Sr,{className:"h-3.5 w-3.5 text-status-success-text"}):y.jsx(Fn,{className:"h-3.5 w-3.5"}),"Copy Content"]}),y.jsxs("button",{onClick:oe,disabled:!l,className:"btn btn-primary flex-1 px-3 py-1.5",children:[y.jsx(KC,{className:"h-3.5 w-3.5"}),"Save Image"]})]}),P&&y.jsx("p",{className:"break-all text-center text-[11px] text-ink-muted",role:"status",children:P}),w&&y.jsx("p",{role:"alert",className:"break-all text-center text-[11px] text-status-danger-text",children:w})]}),y.jsxs("div",{className:"space-y-3",children:[y.jsxs("div",{className:"flex items-center justify-between",children:[y.jsx("label",{className:"text-xs font-medium text-ink-muted uppercase tracking-wider",children:"Payload Fields"}),y.jsxs("div",{className:"flex gap-2",children:[i&&!f.some(T=>T.key==="md5")&&y.jsxs("button",{onClick:$,className:"btn-chip flex items-center gap-1 rounded px-2 py-0.5 text-[10px] font-bold text-chip-purple-text border border-chip-purple-border",children:[y.jsx(Qo,{className:"h-3 w-3"})," Inc. MD5"]}),y.jsxs("button",{onClick:ae,className:"btn-chip flex items-center gap-1 rounded px-2 py-0.5 text-[10px] font-bold text-chip-indigo-text border border-chip-indigo-border",children:[y.jsx(lD,{className:"h-3 w-3"})," Add Field"]})]})]}),y.jsxs("div",{className:"max-h-48 space-y-2 overflow-y-auto pr-1 custom-scrollbar",children:[f.map((T,he)=>y.jsxs("div",{className:"flex gap-2 items-center slide-in",children:[y.jsx("input",{type:"text",placeholder:"key",value:T.key,onChange:ye=>ne(he,"key",ye.target.value),className:"w-1/3 rounded border border-line bg-elevated px-2 py-1 text-xs text-ink focus:border-indigo-500 focus:outline-none"}),y.jsx("input",{type:"text",placeholder:"value",value:T.value,onChange:ye=>ne(he,"value",ye.target.value),className:"flex-1 rounded border border-line bg-elevated px-2 py-1 text-xs text-ink focus:border-indigo-500 focus:outline-none"}),y.jsx("button",{onClick:()=>ie(he),className:"p-1 text-ink-muted hover:text-status-danger-text transition-colors","aria-label":"Remove field",children:y.jsx(nO,{className:"h-3.5 w-3.5"})})]},he)),f.length===0&&y.jsx("p",{className:"text-center py-4 text-xs text-ink-muted italic",children:"No fields defined"})]})]}),y.jsxs("div",{className:"pt-2 border-t border-line",children:[y.jsx("label",{className:"text-[10px] font-medium text-ink-muted uppercase tracking-wider block mb-1.5",children:"Raw Preview"}),y.jsx("div",{className:"rounded bg-elevated p-2 font-mono text-[10px] text-ink-secondary break-all border border-line",children:a||y.jsx("span",{className:"italic text-ink-muted/50",children:"empty"})})]})]})]})}):null}const W2=["Bytes","KB","MB","GB","TB"];function mA(n){if(n===0)return"0 Bytes";const e=1024,t=Math.max(0,Math.min(W2.length-1,Math.floor(Math.log(n)/Math.log(e))));return parseFloat((n/Math.pow(e,t)).toFixed(2))+" "+W2[t]}function D8(n){const e=Math.max(n.lastIndexOf("\\"),n.lastIndexOf("/"));return e===-1?"":n.slice(0,e)}function j8(n){const e=[`File Properties: ${n.name}`,`Path: ${n.path}`,`Type: ${n.type}`,`Size: ${mA(n.size_bytes)}`,`Created: ${n.created}`,`Modified: ${n.modified}`];return n.md5&&e.push(`MD5: ${n.md5}`),n.sha256&&e.push(`SHA256: ${n.sha256}`),e.join(` `)}function xx(n,e,t){return n.length<=e+t+1?n:`${n.slice(0,e)}…${n.slice(-t)}`}function R8(n){const e=n.includes("\\")?"\\":"/",t=n.split(/[\\/]/);return t.length<=5?n:[t[0],t[1],"…",t[t.length-2],t[t.length-1]].join(e)}const _8=[{ms:1e3*60,unit:"minute"},{ms:1e3*60*60,unit:"hour"},{ms:1e3*60*60*24,unit:"day"},{ms:1e3*60*60*24*30,unit:"month"},{ms:1e3*60*60*24*365,unit:"year"}];function Z2(n,e=new Date){const t=new Date(n.replace(" ","T"));if(Number.isNaN(t.getTime()))return"just now";const i=e.getTime()-t.getTime();if(i<6e4)return"just now";let l="just now";for(const{ms:o,unit:a}of _8){if(i{var A;n||((A=M.current)==null||A.focus(),v(!1))},[n]),E.useEffect(()=>{if(!n||!e)return;const A=new AbortController;return P.current=A,o(null),O(null),c(!0),d(null),(async()=>{try{const ne=await LM(e.path,A.signal);if(P.current!==A)return;o(ne)}catch(ne){if(P.current!==A||ne instanceof DOMException&&ne.name==="AbortError")return;d(ne instanceof Error?ne.message:"Failed to load properties")}finally{P.current===A&&c(!1)}})(),()=>{P.current=null,A.abort()}},[n,e]),E.useEffect(()=>{if(!n)return;const A=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=A}},[n]),E.useEffect(()=>{if(!n)return;const A=ne=>{if(ne.key==="Escape"){if(b)return;t();return}if(ne.key!=="Tab")return;const ae=_.current;if(!ae)return;const ie=Array.from(ae.querySelectorAll('button:not([disabled]), [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')).filter(Y=>Y.offsetParent!==null);if(ie.length===0)return;const $=ie[0],oe=ie[ie.length-1],J=document.activeElement instanceof HTMLElement?document.activeElement:null;ne.shiftKey?(J===$||!ae.contains(J))&&(ne.preventDefault(),oe.focus()):J===oe&&(ne.preventDefault(),$.focus())};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[n,b,t]),E.useEffect(()=>{if(!n)return;const A=document.activeElement instanceof HTMLElement?document.activeElement:null;M.current=A;const ne=requestAnimationFrame(()=>{var ae,ie;(ie=(ae=_.current)==null?void 0:ae.querySelector("button"))==null||ie.focus()});return()=>cancelAnimationFrame(ne)},[n]);const L=async(A,ne)=>{try{await navigator.clipboard.writeText(A),g(ne),setTimeout(()=>g(null),2e3)}catch(ae){console.error("Failed to copy:",ae)}},D=async(A,ne,ae)=>{S(A),O(null);try{await ae(),O(ne)}catch{O("Action failed")}finally{S(null)}},j=A=>`btn btn-chip rounded-md border px-3 py-2 text-xs ${{reveal:"bg-chip-sky-bg text-chip-sky-text border-chip-sky-border",launch:"border-emerald-500/30 bg-emerald-600 font-semibold text-white hover:bg-emerald-500",folder:"bg-chip-amber-bg text-chip-amber-text border-chip-amber-border"}[A]??"bg-chip-indigo-bg text-chip-indigo-text border-chip-indigo-border"}`,H=(A,ne,ae,ie=!1,$)=>y.jsxs("div",{className:"flex items-start gap-2 py-1.5 group",children:[y.jsxs("span",{className:"text-ink-muted min-w-[100px] text-xs",children:[A,":"]}),y.jsx("div",{className:"flex-1 min-w-0",children:y.jsx("span",{className:`text-ink text-xs break-all ${ie?"font-mono":""}`,children:$??ne})}),y.jsx(Xe,{text:"Copy to clipboard",block:!1,children:y.jsx("button",{onClick:()=>L(ne,ae),className:"opacity-0 group-hover:opacity-100 transition-opacity p-1 rounded hover:bg-elevated","aria-label":`Copy ${A}`,children:m===ae?y.jsx(Sr,{className:"h-3.5 w-3.5 text-status-success-text"}):y.jsx(Fn,{className:"h-3.5 w-3.5 text-ink-muted"})})})]}),Z=(A,ne,ae)=>y.jsxs("div",{className:"rounded-lg border border-line bg-elevated p-4",children:[y.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[ne,y.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-ink-muted",children:A})]}),ae]}),I=()=>y.jsx(Xe,{text:"Click to copy full path",children:y.jsxs("button",{onClick:()=>void L(l.path,"path"),className:"group mb-3 flex w-full items-center gap-2 rounded-lg border border-line bg-elevated px-3 py-2 text-left hover:bg-surface",children:[y.jsx(lu,{className:"text-chip-amber-text h-4 w-4 flex-shrink-0"}),y.jsx("span",{className:"text-ink min-w-0 flex-1 truncate font-mono text-xs",children:R8(l.path)}),m==="path"?y.jsx(Sr,{className:"text-status-success-text h-3.5 w-3.5"}):y.jsx(Fn,{className:"text-ink-muted h-3.5 w-3.5"})]})});if(!n||!e)return null;const F=e;return y.jsxs("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 backdrop-blur-md p-4",role:"dialog","aria-modal":"true","aria-labelledby":"properties-modal-title",children:[y.jsx("div",{className:"absolute inset-0",onClick:t,onContextMenu:A=>{A.preventDefault(),t()}}),y.jsxs("div",{ref:_,className:"animate-modal-in relative w-full max-w-4xl max-h-[90vh] overflow-hidden rounded-xl border border-frame-line glass-panel flex flex-col",children:[y.jsx("div",{className:"flex-shrink-0 border-b border-line px-6 py-4",children:y.jsxs("div",{className:"flex items-start justify-between gap-4",children:[y.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[y.jsx("div",{className:"rounded-lg bg-indigo-600 p-2 flex-shrink-0",children:y.jsx(Pg,{className:"h-5 w-5 text-white"})}),y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsx("h3",{id:"properties-modal-title",className:"text-base font-semibold text-ink truncate",children:"File Properties"}),y.jsx("p",{className:"text-xs text-ink-muted truncate",children:e.filename})]}),y.jsx(Xe,{text:"Copy all properties to clipboard",block:!1,children:y.jsx("button",{onClick:()=>{l&&L(j8(l),"all")},disabled:!l||a||f!==null,className:"btn-chip ml-2 flex items-center gap-1 rounded-md border border-chip-indigo-border bg-chip-indigo-bg p-1.5 text-chip-indigo-text","aria-label":"Copy all properties",children:m==="all"?y.jsx(Sr,{className:"h-4 w-4 text-status-success-text"}):y.jsx(Fn,{className:"h-4 w-4"})})}),y.jsx(Xe,{text:"Generate Barcode/QR Code",block:!1,children:y.jsx("button",{onClick:()=>v(!0),className:"btn-chip rounded-md border border-chip-indigo-border bg-chip-indigo-bg p-1.5 text-chip-indigo-text",children:y.jsx(ly,{className:"h-4 w-4"})})})]}),y.jsx("button",{onClick:t,className:"focus-ring rounded-md p-1 text-ink-muted hover:bg-elevated hover:text-ink flex-shrink-0","aria-label":"Close",children:y.jsx(ri,{className:"h-4 w-4"})})]})}),y.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4",children:[a&&y.jsx("div",{className:"flex items-center justify-center py-8",children:y.jsxs("div",{className:"flex flex-col items-center gap-2",children:[y.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-600 border-t-transparent"}),y.jsx("p",{className:"text-xs text-ink-muted",children:"Loading properties..."})]})}),f&&y.jsx("div",{className:"rounded-lg border border-status-danger-border bg-status-danger-bg p-4 text-center",children:y.jsx("p",{className:"text-xs text-status-danger-text",children:f})}),l&&!a&&!f&&y.jsxs("div",{children:[y.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-x-4 gap-y-1.5 rounded-lg border border-line bg-elevated px-4 py-2.5",children:[y.jsx("span",{className:"inline-flex items-center gap-1 rounded-md border border-chip-indigo-border bg-chip-indigo-bg px-2 py-0.5 text-xs font-semibold text-chip-indigo-text",children:l.type}),l.attributes.extension&&y.jsx("span",{className:"inline-flex items-center rounded-md border border-line bg-surface px-2 py-0.5 text-xs font-medium text-ink-muted",children:l.attributes.extension}),y.jsxs("span",{className:"text-xs text-ink-muted",title:`${l.size_bytes} bytes`,children:["Size ",y.jsx("strong",{className:"text-ink font-medium",children:mA(l.size_bytes)})]}),y.jsxs("span",{className:"text-xs text-ink-muted",title:l.created,children:["Created ",y.jsx("strong",{className:"text-ink font-medium",children:Z2(l.created)})]}),y.jsxs("span",{className:"text-xs text-ink-muted",title:l.modified,children:["Modified ",y.jsx("strong",{className:"text-ink font-medium",children:Z2(l.modified)})]}),l.md5&&y.jsx("span",{className:"inline-flex items-center rounded-md border border-chip-purple-border bg-chip-purple-bg px-2 py-0.5 font-mono text-xs font-medium text-chip-purple-text",title:`MD5 ${l.md5}`,children:xx(l.md5,4,4)}),l.attributes.is_symlink&&y.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-chip-fuchsia-border bg-chip-fuchsia-bg px-2 py-0.5 text-xs font-medium text-chip-fuchsia-text",children:[y.jsx(Y4,{className:"h-3 w-3"})," Symlink"]})]}),I(),y.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[Z("Hashes",y.jsx(Qo,{className:"text-chip-purple-text h-3.5 w-3.5"}),y.jsxs("div",{className:"space-y-0.5",children:[H("MD5",l.md5,"md5",!0,xx(l.md5,10,6)),H("SHA256",l.sha256,"sha256",!0,xx(l.sha256,10,6))]})),Z("Timestamps",y.jsx(i4,{className:"text-chip-sky-text h-3.5 w-3.5"}),y.jsxs("div",{className:"space-y-0.5",children:[H("Created",l.created,"created",!0),H("Modified",l.modified,"modified",!0)]})),Z("Identity",y.jsx(Pg,{className:"text-chip-indigo-text h-3.5 w-3.5"}),y.jsxs("div",{className:"space-y-0.5",children:[H("Type",l.type,"type"),l.attributes.stem&&H("Stem",l.attributes.stem,"attrStem"),H("Extension",l.name.includes(".")?l.name.slice(l.name.lastIndexOf(".")):"None","extension"),H("Directory",D8(l.path)||"None","directory",!0)]})),Z("System",y.jsx(Pg,{className:"text-status-success-text h-3.5 w-3.5"}),y.jsxs("div",{children:[y.jsxs("div",{className:"mb-1 flex min-h-[24px] flex-wrap items-center gap-1.5",children:[l.attributes.is_readonly&&y.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-status-danger-border bg-status-danger-bg px-2 py-0.5 text-xs text-status-danger-text",children:[y.jsx(Z4,{className:"h-3 w-3"})," Read-only"]}),l.attributes.is_hidden&&y.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-line bg-elevated px-2 py-0.5 text-xs text-ink-muted",children:[y.jsx(N4,{className:"h-3 w-3"})," Hidden"]}),!l.attributes.is_readonly&&!l.attributes.is_hidden&&!l.attributes.is_symlink&&y.jsx("span",{className:"text-xs text-ink-muted",children:"No special flags"})]}),y.jsxs("div",{className:"space-y-0.5",children:[H("File Type",l.attributes.is_file?"Regular File":l.attributes.is_dir?"Directory":"Other","fileType"),l.attributes.permissions&&H("Permissions",l.attributes.permissions,"permissions",!0),l.attributes.owner_uid!==void 0&&H("Owner UID",String(l.attributes.owner_uid),"ownerUid"),l.attributes.group_gid!==void 0&&H("Group GID",String(l.attributes.group_gid),"groupGid")]})]}))]})]})]}),y.jsx("div",{className:"flex-shrink-0 border-t border-line px-6 py-3",children:y.jsxs("div",{className:"flex justify-between items-center gap-2",children:[y.jsx("p",{className:"min-w-0 text-xs text-ink-muted truncate",children:C??"Click the copy icon next to any field to copy its value"}),y.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap",children:[y.jsx(Xe,{text:"Show file in Explorer",block:!1,children:y.jsxs("button",{onClick:()=>void D("reveal","Revealed in Explorer",()=>XC(F.path)),disabled:w!==null,className:j("reveal"),children:[y.jsx(zx,{className:"h-3.5 w-3.5"})," Reveal"]})}),y.jsx(Xe,{text:"Launch file with default association",block:!1,children:y.jsxs("button",{onClick:()=>{i&&(S("launch"),Promise.resolve(i(F)).finally(()=>S(null)))},disabled:w!==null||!i,className:j("launch"),children:[y.jsx(Fl,{className:"h-3.5 w-3.5"})," Launch"]})}),y.jsx(Xe,{text:"Open containing folder",block:!1,children:y.jsxs("button",{onClick:()=>void D("folder","Opened folder",()=>_x(F.path)),disabled:w!==null,className:j("folder"),children:[y.jsx(Il,{className:"h-3.5 w-3.5"})," Open Folder"]})}),y.jsx("button",{onClick:t,className:"btn btn-primary px-4 py-2",children:"Close"})]})]})})]}),y.jsx(dA,{isOpen:b,onClose:()=>v(!1),initialFilePath:e.path,md5:l==null?void 0:l.md5})]})}const z8=["qr_code","code_128","code_39","ean_13","ean_8","upc_a","upc_e","data_matrix"],B8=250,P8=400,H8=.7;function I8(n,e=P8,t=H8){const i=n.videoWidth,l=n.videoHeight;if(!i||!l)return null;const o=Math.min(i,l),a=document.createElement("canvas");a.width=Math.min(e,o),a.height=a.width;const c=a.getContext("2d");if(!c)return null;c.drawImage(n,(i-o)/2,(l-o)/2,o,o,0,0,a.width,a.height);const f=a.toDataURL("image/jpeg",t);return f.slice(f.indexOf(",")+1)}function U8(n,e){const t=n.intervalMs??B8;let i=!1,l=!1;const o=()=>{i=!0,clearInterval(a)},a=setInterval(()=>{if(i||l)return;const c=n.capture();c&&(l=!0,n.decode(c).then(f=>{i||f.decoded&&(o(),e.onDetected(f.decoded))}).catch(f=>{i||(o(),e.onError(f instanceof Error?f.message:"Frame decoding failed"))}).finally(()=>{l=!1}))},t);return o}const F8=8e3;function q8({isOpen:n,onClose:e,onDetected:t}){const i=E.useRef(null),l=E.useRef(null),o=tl({isOpen:n,onClose:e,dialogRef:l}),a=E.useRef(null),c=E.useRef(null),f=E.useRef(null),[d,m]=E.useState(null),[g,b]=E.useState(!1),v=()=>{f.current&&(f.current(),f.current=null),c.current&&(cancelAnimationFrame(c.current),c.current=null),a.current&&(a.current.getTracks().forEach(C=>C.stop()),a.current=null),i.current&&(i.current.srcObject=null)};E.useEffect(()=>{if(!n){v(),m(null);return}let C=!0;async function O(){var M,P,L,D,j;if(m(null),b(!1),typeof window<"u"&&!window.isSecureContext&&window.location.hostname!=="localhost"&&window.location.hostname!=="127.0.0.1"){m("Camera access requires HTTPS or localhost. If connecting across a local network IP (e.g. 192.168.x.x), modern browsers disable camera access for insecure HTTP.");return}const _=((P=(M=navigator.mediaDevices)==null?void 0:M.getUserMedia)==null?void 0:P.bind(navigator.mediaDevices))||((L=navigator.getUserMedia)==null?void 0:L.bind(navigator))||((D=navigator.webkitGetUserMedia)==null?void 0:D.bind(navigator))||((j=navigator.mozGetUserMedia)==null?void 0:j.bind(navigator));if(!_){m(window.isSecureContext?"Camera access is not supported by your browser or environment.":"Camera access is blocked because the page is not served over a secure origin (HTTPS or localhost/127.0.0.1).");return}try{let H;const Z=await Promise.race([_({video:{facingMode:"environment",width:{ideal:1280},height:{ideal:720}}}),new Promise((I,F)=>{H=window.setTimeout(()=>F(new DOMException("Camera did not start in time","TimeoutError")),F8)})]).finally(()=>{H!==void 0&&window.clearTimeout(H)});if(!C){Z.getTracks().forEach(I=>I.stop());return}a.current=Z,i.current&&(i.current.srcObject=Z,await i.current.play()),"BarcodeDetector"in window?S():w()}catch(H){if(!C)return;console.error("Camera access error:",H),m(H.name==="NotAllowedError"||H.name==="PermissionDeniedError"?"Camera permission denied. Please allow camera access in your browser settings.":H.name==="TimeoutError"?"The camera did not start in time. On macOS, camera capture needs the packaged desktop app — a bare Python process cannot access the camera. Alternatively, open ProFiles in Chrome, Edge or Safari.":`Could not access camera: ${H.message||"Unknown error"}`)}}return O(),()=>{C=!1,v()}},[n]);const w=()=>{b(!0),f.current=U8({capture:()=>i.current?I8(i.current):null,decode:C=>_M({imageBase64:C,formats:[...z8]})},{onDetected:C=>{v(),t(C)},onError:C=>{v(),m(C)}})},S=()=>{const C=["qr_code","code_128","code_39","ean_13","ean_8","upc_a","upc_e","data_matrix"];let O;try{O=new window.BarcodeDetector({formats:C})}catch(M){console.warn("BarcodeDetector formats unsupported:",M),O=new window.BarcodeDetector}const _=async()=>{if(!i.current||i.current.readyState<2){c.current=requestAnimationFrame(_);return}try{const M=await O.detect(i.current);if(M&&M.length>0){const P=M[0].rawValue;if(P){v(),t(P);return}}}catch(M){console.debug("Frame detection error:",M)}c.current=requestAnimationFrame(_)};c.current=requestAnimationFrame(_)};return n?y.jsx("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/70 p-4 backdrop-blur-sm",onClick:e,children:y.jsxs("div",{ref:l,role:"dialog","aria-modal":"true","aria-label":"Camera barcode scanner",onKeyDown:o,className:"relative w-full max-w-lg rounded-2xl border border-frame-line glass-panel p-6 flex flex-col",onClick:C=>C.stopPropagation(),children:[y.jsxs("div",{className:"mb-4 flex items-center justify-between border-b border-line pb-3",children:[y.jsxs("div",{className:"flex items-center gap-2 font-semibold text-ink",children:[y.jsx(YC,{className:"h-5 w-5 text-chip-indigo-text"}),y.jsx("span",{children:"Scan with Camera"})]}),y.jsx("button",{onClick:e,className:"focus-ring rounded-lg p-1 text-ink-muted hover:bg-elevated hover:text-ink transition-colors","aria-label":"Close",children:y.jsx(ri,{className:"h-4 w-4"})})]}),d?y.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[y.jsx("div",{className:"rounded-full bg-status-danger-bg p-3 text-status-danger-text mb-3",children:y.jsx(Ec,{className:"h-6 w-6"})}),y.jsx("p",{className:"text-xs text-status-danger-text max-w-xs",children:d}),y.jsx("button",{onClick:e,className:"btn btn-secondary mt-6 px-4 py-2",children:"Close"})]}):y.jsxs("div",{className:"flex flex-col items-center",children:[y.jsxs("div",{className:"relative aspect-video w-full overflow-hidden rounded-xl bg-black border border-line flex items-center justify-center",children:[y.jsx("video",{ref:i,playsInline:!0,muted:!0,className:"h-full w-full object-cover"}),y.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:y.jsxs("div",{className:"relative h-48 w-48 rounded-lg border-2 border-dashed border-indigo-400/80 bg-indigo-500/5 shadow-[0_0_0_9999px_rgba(0,0,0,0.45)]",children:[y.jsx("div",{className:"absolute top-0 left-0 h-4 w-4 border-t-2 border-l-2 border-indigo-400"}),y.jsx("div",{className:"absolute top-0 right-0 h-4 w-4 border-t-2 border-r-2 border-indigo-400"}),y.jsx("div",{className:"absolute bottom-0 left-0 h-4 w-4 border-b-2 border-l-2 border-indigo-400"}),y.jsx("div",{className:"absolute bottom-0 right-0 h-4 w-4 border-b-2 border-r-2 border-indigo-400"})]})})]}),y.jsx("p",{className:"mt-4 text-center text-xs text-ink-muted",children:g?"Hold a QR code or barcode steady in front of your camera — frames are decoded by the local ProFiles server (no native Barcode Detector in this browser).":"Hold a QR code or barcode steady in front of your camera to auto-scan."})]})]})}):null}function V8({isOpen:n,file:e,onConfirm:t,onDismiss:i}){const l=E.useRef(null);return E.useEffect(()=>{var o;if(n){const a=c=>{c.key==="Enter"?(c.preventDefault(),t()):c.key==="Escape"&&(c.preventDefault(),i())};return window.addEventListener("keydown",a),(o=l.current)==null||o.focus(),()=>window.removeEventListener("keydown",a)}},[n,t,i]),!n||!e?null:y.jsx("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm",onClick:i,children:y.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":`1 file matched: ${e.filename}`,className:"animate-modal-in w-full max-w-sm rounded-xl border border-frame-line glass-panel p-5 flex flex-col gap-4",onClick:o=>o.stopPropagation(),children:[y.jsxs("div",{className:"flex items-center justify-between border-b border-line pb-3",children:[y.jsxs("div",{className:"flex items-center gap-2 font-semibold text-ink text-sm",children:[e.has_hook?y.jsx(jD,{className:"h-4 w-4 text-chip-purple-text"}):y.jsx(Fl,{className:"h-4 w-4 text-status-success-text"}),y.jsx("span",{children:"1 File Matched"})]}),y.jsx("button",{onClick:i,className:"focus-ring rounded p-1 text-ink-muted hover:bg-elevated hover:text-ink","aria-label":"Dismiss",children:y.jsx(ri,{className:"h-4 w-4"})})]}),y.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-line bg-elevated/50 p-3",children:[y.jsx(sa,{className:"h-5 w-5 text-chip-indigo-text shrink-0 mt-0.5"}),y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsx("h4",{className:"text-xs font-semibold text-ink truncate",children:e.filename}),y.jsx("p",{className:"text-[11px] text-ink-muted truncate mt-0.5",children:e.rel_path||e.path}),e.has_hook&&y.jsx("span",{className:"inline-block mt-1 text-[10px] text-chip-purple-text bg-chip-purple-bg px-1.5 py-0.5 rounded border border-chip-purple-border/50 font-medium",children:"Workflow Hook Configured"})]})]}),y.jsx("p",{className:"text-xs text-ink-muted text-center",children:"Launch this file now?"}),y.jsxs("div",{className:"flex gap-2",children:[y.jsx("button",{type:"button",onClick:i,className:"btn btn-secondary flex-1 px-3 py-1.5",children:"Dismiss (Esc)"}),y.jsxs("button",{ref:l,type:"button",onClick:t,className:"btn btn-primary flex-1 px-3 py-1.5 shadow-md",children:[y.jsx(Fl,{className:"h-3 w-3 fill-current"}),"Launch (Enter)"]})]})]})})}function Q8({systemInfo:n,fileCount:e,theme:t,onToggleTheme:i,onOpenLog:l,onOpenConfig:o,onShowShortcuts:a,onReloadConfig:c,onExport:f,exportDisabled:d=!1,language:m="en",onLanguageChange:g,lanEnabled:b,onToggleLan:v}){return y.jsxs("footer",{className:"flex items-center justify-between border-t border-line bg-app px-4 py-2 text-[11px] text-ink-muted transition-colors duration-200",children:[y.jsx("div",{className:"flex items-center gap-4",children:n&&y.jsxs("div",{className:"flex items-center gap-1.5 rounded-full border border-line bg-surface px-2.5 py-0.5 text-ink-secondary",children:[y.jsx(QM,{className:"h-3 w-3 text-status-success-text"}),y.jsx("a",{href:`http://${n.hostname}:${window.location.port}`,target:"_blank",rel:"noopener noreferrer","aria-label":`Open ProFiles on ${n.hostname}`,className:"font-mono hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 rounded px-1 py-0.5",children:n.hostname}),y.jsx("span",{className:"text-ink-faint",children:"|"}),y.jsx("a",{href:`http://${n.ip}:${window.location.port}`,target:"_blank",rel:"noopener noreferrer","aria-label":`Open ProFiles on ${n.ip}`,className:"font-mono hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 rounded px-1 py-0.5",children:n.ip}),y.jsx("span",{className:"text-ink-faint",children:"|"}),y.jsxs("span",{className:"flex items-center gap-1",title:"Session user",children:[y.jsx(OD,{className:"h-3 w-3 text-ink-faint"}),y.jsx("span",{children:n.username||"operator"})]}),v!==void 0&&y.jsxs(y.Fragment,{children:[y.jsx("span",{className:"text-ink-faint",children:"|"}),y.jsx(Xe,{text:"LAN access",block:!1,children:y.jsxs("button",{onClick:()=>v(b!==!0),disabled:b===null,"aria-pressed":b===!0,className:`focus-ring flex items-center gap-1 rounded px-1 py-0.5 text-[10px] ${b===null?"text-ink-faint cursor-not-allowed":b===!0?"text-status-success-text":"text-ink-muted hover:text-ink"}`,children:[y.jsx(nD,{className:"h-3 w-3"}),y.jsx("span",{children:"LAN"})]})})]})]})}),y.jsxs("div",{className:"flex items-center gap-3",children:[y.jsxs("span",{children:[y.jsx("strong",{className:"text-ink",children:e})," files found"]}),y.jsx("span",{className:"text-ink-faint",children:"|"}),y.jsx(Xe,{text:"Keyboard shortcuts (?)",block:!1,children:y.jsxs("button",{onClick:a,className:"focus-ring flex items-center gap-1 text-ink-muted hover:text-ink",children:[y.jsx(WC,{className:"h-3 w-3"}),y.jsx("span",{children:"Shortcuts"})]})}),y.jsx(Xe,{text:"Open the application log viewer",block:!1,children:y.jsxs("button",{onClick:l,className:"focus-ring flex items-center gap-1 text-ink-muted hover:text-ink",children:[y.jsx(sa,{className:"h-3 w-3"}),y.jsx("span",{children:"Logs"})]})}),y.jsx("span",{className:"text-ink-faint",children:"|"}),c&&y.jsx(Xe,{text:"Reload configuration from disk",block:!1,children:y.jsxs("button",{onClick:c,className:"focus-ring flex items-center gap-1 text-ink-muted hover:text-ink",children:[y.jsx(Md,{className:"h-3 w-3"}),y.jsx("span",{children:"Reload"})]})}),f&&y.jsx(Xe,{text:"Export the current results as CSV",block:!1,children:y.jsxs("button",{onClick:f,disabled:d,className:"focus-ring flex items-center gap-1 rounded text-ink-muted hover:text-ink disabled:opacity-40 disabled:hover:text-ink-muted",children:[y.jsx(KC,{className:"h-3 w-3"}),y.jsx("span",{children:"Export CSV"})]})}),g&&y.jsxs("div",{className:"flex items-center overflow-hidden rounded border border-line text-[10px]",children:[y.jsx(Xe,{text:"English",block:!1,children:y.jsxs("button",{onClick:()=>g("en"),className:`flex items-center gap-1 px-1.5 py-0.5 transition-colors ${m==="en"?"bg-indigo-600 text-white focus-ring":"text-ink-muted hover:text-ink focus-ring"}`,children:[y.jsx(q4,{className:"h-3 w-3"}),y.jsx("span",{children:"EN"})]})}),y.jsx(Xe,{text:"Français",block:!1,children:y.jsx("button",{onClick:()=>g("fr"),className:`flex items-center gap-1 px-1.5 py-0.5 transition-colors ${m==="fr"?"bg-indigo-600 text-white focus-ring":"text-ink-muted hover:text-ink focus-ring"}`,children:y.jsx("span",{children:"FR"})})})]}),y.jsx(Xe,{text:"Open the configuration editor",block:!1,children:y.jsxs("button",{onClick:o,className:"focus-ring flex items-center gap-1 text-ink-muted hover:text-ink",children:[y.jsx(xD,{className:"h-3 w-3"}),y.jsx("span",{children:"Config"})]})}),y.jsx(Xe,{text:`Switch to ${t==="dark"?"light":"dark"} mode`,block:!1,children:y.jsxs("button",{onClick:i,className:"focus-ring flex items-center gap-1 rounded px-1.5 py-0.5 text-ink-muted hover:bg-elevated hover:text-status-warning-text",children:[t==="dark"?y.jsx(bD,{className:"h-3 w-3 text-status-warning-text"}):y.jsx(eD,{className:"h-3 w-3 text-chip-indigo-text"}),y.jsx("span",{children:t==="dark"?"Light":"Dark"})]})})]})]})}const X8=[{label:"5 seconds",seconds:5},{label:"10 seconds",seconds:10},{label:"30 seconds",seconds:30},{label:"1 minute",seconds:60},{label:"5 minutes",seconds:300}];function $8({isOpen:n,currentInterval:e,onClose:t,onSetInterval:i}){const l=E.useRef(null),o=tl({isOpen:n,onClose:t,dialogRef:l});if(!n)return null;const a=e>0,c=m=>{i(m)},f=m=>{m.preventDefault();const b=m.currentTarget.elements.namedItem("custom-interval"),v=parseInt(b.value,10);!isNaN(v)&&v>0&&i(v)},d=()=>{i(0)};return y.jsx("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm",children:y.jsxs("div",{ref:l,role:"dialog","aria-modal":"true","aria-label":"Auto-Rescan Timer",onKeyDown:o,className:"animate-modal-in w-[420px] max-w-full rounded-2xl border border-frame-line glass-panel p-5",children:[y.jsxs("div",{className:"mb-4 flex items-center justify-between border-b border-line pb-3",children:[y.jsxs("div",{className:"flex items-center gap-2 font-semibold text-ink",children:[y.jsx(tO,{className:"h-5 w-5 text-chip-indigo-text"}),y.jsx("span",{children:"Auto-Rescan Timer"})]}),y.jsx("button",{onClick:t,className:"focus-ring rounded-lg p-1 text-ink-muted hover:bg-elevated hover:text-ink",children:y.jsx(ri,{className:"h-4 w-4"})})]}),y.jsx("div",{className:"mb-4 rounded-lg bg-elevated/50 px-3 py-2 text-xs",children:a?y.jsxs("div",{className:"flex items-center gap-2 text-status-success-text",children:[y.jsx(y4,{className:"h-4 w-4 animate-pulse"}),y.jsxs("span",{children:["Auto-rescan every ",e,"s"]})]}):y.jsxs("div",{className:"flex items-center gap-2 text-ink-secondary",children:[y.jsx(g4,{className:"h-4 w-4"}),y.jsx("span",{children:"Auto-rescan is disabled"})]})}),y.jsxs("div",{className:"mb-4 space-y-1 text-xs",children:[y.jsx("p",{className:"text-ink-muted",children:"Presets:"}),y.jsx("div",{className:"grid grid-cols-2 gap-2",children:X8.map(m=>y.jsx("button",{onClick:()=>c(m.seconds),className:"rounded-lg border border-line bg-elevated/50 px-3 py-1.5 text-left font-medium text-ink-secondary hover:border-chip-indigo-border hover:bg-chip-indigo-bg/40 hover:text-chip-indigo-text focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500",children:m.label},m.seconds))})]}),y.jsxs("form",{onSubmit:f,className:"mb-4",children:[y.jsxs("label",{className:"flex items-center gap-2 text-xs font-medium text-ink-secondary",children:[y.jsx(w4,{className:"h-3.5 w-3.5"}),y.jsx("span",{children:"Custom interval (seconds):"})]}),y.jsxs("div",{className:"mt-1 flex gap-2",children:[y.jsx("input",{type:"number",name:"custom-interval",min:"1",placeholder:"e.g. 45",className:"flex-1 rounded-lg border border-line bg-app px-2 py-1 text-xs text-ink placeholder-ink-faint focus:border-indigo-500 focus:outline-none"}),y.jsx("button",{type:"submit",className:"btn btn-primary rounded-lg px-3 py-1 font-semibold",children:"Set"})]})]}),a&&y.jsx("button",{onClick:d,className:"btn w-full rounded-lg border-line bg-elevated/50 px-3 py-2 text-status-warning-text hover:border-status-warning-border hover:bg-status-warning-bg/40",children:"Stop Auto-Rescan"}),y.jsx("div",{className:"flex justify-end gap-2 border-t border-line pt-3",children:y.jsx("button",{onClick:t,className:"rounded-lg border border-line bg-elevated px-4 py-2 text-xs font-semibold text-ink-secondary hover:bg-elevated/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500",children:"Close"})})]})})}function G8(n,e){const t={};return(n[n.length-1]===""?[...n,""]:n).join((t.padRight?" ":"")+","+(t.padLeft===!1?"":" ")).trim()}const Y8=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,K8=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,W8={};function J2(n,e){return(W8.jsx?K8:Y8).test(n)}const Z8=/[ \t\n\f\r]/g;function J8(n){return typeof n=="object"?n.type==="text"?eC(n.value):!1:eC(n)}function eC(n){return n.replace(Z8,"")===""}class du{constructor(e,t,i){this.normal=t,this.property=e,i&&(this.space=i)}}du.prototype.normal={};du.prototype.property={};du.prototype.space=void 0;function pA(n,e){const t={},i={};for(const l of n)Object.assign(t,l.property),Object.assign(i,l.normal);return new du(t,i,e)}function H0(n){return n.toLowerCase()}class si{constructor(e,t){this.attribute=t,this.property=e}}si.prototype.attribute="";si.prototype.booleanish=!1;si.prototype.boolean=!1;si.prototype.commaOrSpaceSeparated=!1;si.prototype.commaSeparated=!1;si.prototype.defined=!1;si.prototype.mustUseProperty=!1;si.prototype.number=!1;si.prototype.overloadedBoolean=!1;si.prototype.property="";si.prototype.spaceSeparated=!1;si.prototype.space=void 0;let eP=0;const Qe=Fs(),Zt=Fs(),I0=Fs(),ge=Fs(),Ct=Fs(),zs=Fs(),xi=Fs();function Fs(){return 2**++eP}const U0=Object.freeze(Object.defineProperty({__proto__:null,boolean:Qe,booleanish:Zt,commaOrSpaceSeparated:xi,commaSeparated:zs,number:ge,overloadedBoolean:I0,spaceSeparated:Ct},Symbol.toStringTag,{value:"Module"})),yx=Object.keys(U0);class Qy extends si{constructor(e,t,i,l){let o=-1;if(super(e,t),tC(this,"space",l),typeof i=="number")for(;++o4&&t.slice(0,4)==="data"&&lP.test(e)){if(e.charAt(4)==="-"){const o=e.slice(5).replace(nC,aP);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=e.slice(4);if(!nC.test(o)){let a=o.replace(rP,oP);a.charAt(0)!=="-"&&(a="-"+a),e="data"+a}}l=Qy}return new l(i,e)}function oP(n){return"-"+n.toLowerCase()}function aP(n){return n.charAt(1).toUpperCase()}const cP=pA([gA,tP,bA,vA,wA],"html"),Xy=pA([gA,nP,bA,vA,wA],"svg");function uP(n){return n.join(" ").trim()}var iC=/\/\*(?:[^*]|\*(?!\/))*\*\//g,fP=/\n/g,hP=/^\s*/,dP=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,mP=/^:\s*/,pP=/^((?:'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|url\((?:'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|[^)]*)\)|[^};])+)/,gP=/^[;\s]*/,xP=` `,rC="/",lC="*",wc="",yP="comment",bP="declaration";function vP(n,e){if(typeof n!="string")throw new TypeError("First argument must be a string");if(!n)return[];e=e||{};var t=1,i=1;function l(w){var S=w.match(fP);S&&(t+=S.length);var C=w.lastIndexOf(xP);i=~C?w.length-C:i+w.length}function o(){var w={line:t,column:i};return function(S){return S.position=new a(w),d(),S}}function a(w){this.start=w,this.end={line:t,column:i},this.source=e.source}a.prototype.content=n;function c(w){var S=new Error(e.source+":"+t+":"+i+": "+w);if(S.reason=w,S.filename=e.source,S.line=t,S.column=i,S.source=n,!e.silent)throw S}function f(w){var S=w.exec(n);if(S){var C=S[0];return l(C),n=n.slice(C.length),S}}function d(){f(hP)}function m(w){for(var S;S=g();)w.push(S);return w}function g(){var w=o();if(!(rC!=n.charAt(0)||lC!=n.charAt(1))){for(var S=2;wc!=n.charAt(S)&&(lC!=n.charAt(S)||rC!=n.charAt(S+1));)++S;if(S+=2,wc===n.charAt(S-1))return c("End of comment missing");var C=n.slice(2,S-2);return i+=2,l(C),n=n.slice(S),i+=2,w({type:yP,comment:C})}}function b(){var w=o(),S=f(dP);if(S){if(g(),!f(mP))return c("property missing ':'");var C=f(pP),O=w({type:bP,property:S[0].replace(iC,wc).trim(),value:C?C[0].replace(iC,wc).trim():wc});return f(gP),O}}function v(){var w=[];m(w);for(var S;S=b();)w.push(S),m(w);return w}return d(),v()}function wP(n,e){let t=null;if(!n||typeof n!="string")return t;const i=vP(n),l=typeof e=="function";return i.forEach(o=>{if(o.type!=="declaration")return;const{property:a,value:c}=o;l?e(a,c,o):c&&(t=t??{},t[a]=c)}),t}const kA=SA("end"),$y=SA("start");function SA(n){return e;function e(t){const i=t&&t.position&&t.position[n]||{};if(typeof i.line=="number"&&i.line>0&&typeof i.column=="number"&&i.column>0)return{line:i.line,column:i.column,offset:typeof i.offset=="number"&&i.offset>-1?i.offset:void 0}}}function kP(n){const e=$y(n),t=kA(n);if(e&&t)return{start:e,end:t}}function Pc(n){return!n||typeof n!="object"?"":"position"in n||"type"in n?sC(n.position):"start"in n||"end"in n?sC(n):"line"in n||"column"in n?F0(n):""}function F0(n){return oC(n&&n.line)+":"+oC(n&&n.column)}function sC(n){return F0(n&&n.start)+"-"+F0(n&&n.end)}function oC(n){return n&&typeof n=="number"?n:1}class _n extends Error{constructor(e,t,i){super(),typeof t=="string"&&(i=t,t=void 0);let l="",o={},a=!1;if(t&&("line"in t&&"column"in t?o={place:t}:"start"in t&&"end"in t?o={place:t}:"type"in t?o={ancestors:[t],place:t.position}:o={...t}),typeof e=="string"?l=e:!o.cause&&e&&(a=!0,l=e.message,o.cause=e),!o.ruleId&&!o.source&&typeof i=="string"){const f=i.indexOf(":");f===-1?o.ruleId=i:(o.source=i.slice(0,f),o.ruleId=i.slice(f+1))}if(!o.place&&o.ancestors&&o.ancestors){const f=o.ancestors[o.ancestors.length-1];f&&(o.place=f.position)}const c=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file="",this.message=l,this.line=c?c.line:void 0,this.name=Pc(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=a&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}_n.prototype.file="";_n.prototype.name="";_n.prototype.reason="";_n.prototype.message="";_n.prototype.stack="";_n.prototype.column=void 0;_n.prototype.line=void 0;_n.prototype.ancestors=void 0;_n.prototype.cause=void 0;_n.prototype.fatal=void 0;_n.prototype.place=void 0;_n.prototype.ruleId=void 0;_n.prototype.source=void 0;const Gy={}.hasOwnProperty,SP=new Map,CP=/[A-Z]/g,OP=/-([a-z])/g,NP=new Set(["table","tbody","thead","tfoot","tr"]),TP=new Set(["td","th"]),CA="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function AP(n,e){if(!e||e.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const t=e.filePath||void 0;let i;if(e.development){if(typeof e.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");i=zP(t,e.jsxDEV)}else{if(typeof e.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof e.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");i=LP(t,e.jsx,e.jsxs)}const l={Fragment:e.Fragment,ancestors:[],components:e.components||{},create:i,elementAttributeNameCase:e.elementAttributeNameCase||"react",evaluater:e.createEvaluater?e.createEvaluater():void 0,filePath:t,ignoreInvalidStyle:e.ignoreInvalidStyle||!1,passKeys:e.passKeys!==!1,passNode:e.passNode||!1,schema:e.space==="svg"?Xy:cP,stylePropertyNameCase:e.stylePropertyNameCase||"dom",tableCellAlignToStyle:e.tableCellAlignToStyle!==!1},o=OA(l,n,void 0);return o&&typeof o!="string"?o:l.create(n,l.Fragment,{children:o||void 0},void 0)}function OA(n,e,t){if(e.type==="element")return EP(n,e,t);if(e.type==="mdxFlowExpression"||e.type==="mdxTextExpression")return MP(n,e);if(e.type==="mdxJsxFlowElement"||e.type==="mdxJsxTextElement")return jP(n,e,t);if(e.type==="mdxjsEsm")return DP(n,e);if(e.type==="root")return RP(n,e,t);if(e.type==="text")return _P(n,e)}function EP(n,e,t){const i=n.schema;let l=i;e.tagName.toLowerCase()==="svg"&&i.space==="html"&&(l=Xy,n.schema=l),n.ancestors.push(e);const o=TA(n,e.tagName,!1),a=BP(n,e);let c=Ky(n,e);return NP.has(e.tagName)&&(c=c.filter(function(f){return typeof f=="string"?!J8(f):!0})),NA(n,a,o,e),Yy(a,c),n.ancestors.pop(),n.schema=i,n.create(e,o,a,t)}function MP(n,e){if(e.data&&e.data.estree&&n.evaluater){const i=e.data.estree.body[0];return i.type,n.evaluater.evaluateExpression(i.expression)}ru(n,e.position)}function DP(n,e){if(e.data&&e.data.estree&&n.evaluater)return n.evaluater.evaluateProgram(e.data.estree);ru(n,e.position)}function jP(n,e,t){const i=n.schema;let l=i;e.name==="svg"&&i.space==="html"&&(l=Xy,n.schema=l),n.ancestors.push(e);const o=e.name===null?n.Fragment:TA(n,e.name,!0),a=PP(n,e),c=Ky(n,e);return NA(n,a,o,e),Yy(a,c),n.ancestors.pop(),n.schema=i,n.create(e,o,a,t)}function RP(n,e,t){const i={};return Yy(i,Ky(n,e)),n.create(e,n.Fragment,i,t)}function _P(n,e){return e.value}function NA(n,e,t,i){typeof t!="string"&&t!==n.Fragment&&n.passNode&&(e.node=i)}function Yy(n,e){if(e.length>0){const t=e.length>1?e:e[0];t&&(n.children=t)}}function LP(n,e,t){return i;function i(l,o,a,c){const d=Array.isArray(a.children)?t:e;return c?d(o,a,c):d(o,a)}}function zP(n,e){return t;function t(i,l,o,a){const c=Array.isArray(o.children),f=$y(i);return e(l,o,a,c,{columnNumber:f?f.column-1:void 0,fileName:n,lineNumber:f?f.line:void 0},void 0)}}function BP(n,e){const t={};let i,l;for(l in e.properties)if(l!=="children"&&Gy.call(e.properties,l)){const o=HP(n,l,e.properties[l]);if(o){const[a,c]=o;n.tableCellAlignToStyle&&a==="align"&&typeof c=="string"&&TP.has(e.tagName)?i=c:t[a]=c}}if(i){const o=t.style||(t.style={});o[n.stylePropertyNameCase==="css"?"text-align":"textAlign"]=i}return t}function PP(n,e){const t={};for(const i of e.attributes)if(i.type==="mdxJsxExpressionAttribute")if(i.data&&i.data.estree&&n.evaluater){const o=i.data.estree.body[0];o.type;const a=o.expression;a.type;const c=a.properties[0];c.type,Object.assign(t,n.evaluater.evaluateExpression(c.argument))}else ru(n,e.position);else{const{name:l}=i;let o;if(i.value&&typeof i.value=="object")if(i.value.data&&i.value.data.estree&&n.evaluater){const c=i.value.data.estree.body[0];c.type,o=n.evaluater.evaluateExpression(c.expression)}else ru(n,e.position);else o=i.value===null?!0:i.value;t[l]=o}return t}function Ky(n,e){const t=[];let i=-1;const l=n.passKeys?new Map:SP;for(;++il?0:l+e:e=e>l?l:e,t=t>0?t:0,i.length<1e4)a=Array.from(i),a.unshift(e,t),n.splice(...a);else for(t&&n.splice(e,t);o0?(Yi(n,n.length,0,e),n):e}const uC={}.hasOwnProperty;function EA(n){const e={};let t=-1;for(;++t13&&t<32||t>126&&t<160||t>55295&&t<57344||t>64975&&t<65008||(t&65535)===65535||(t&65535)===65534||t>1114111?"�":String.fromCodePoint(t)}function Ki(n){return n.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Cn=Zl(/[A-Za-z]/),On=Zl(/[\dA-Za-z]/),YP=Zl(/[#-'*+\--9=?A-Z^-~]/);function Sd(n){return n!==null&&(n<32||n===127)}const q0=Zl(/\d/),KP=Zl(/[\dA-Fa-f]/),DA=Zl(/[!-/:-@[-`{-~]/);function He(n){return n!==null&&n<-2}function Nt(n){return n!==null&&(n<0||n===32)}function Je(n){return n===-2||n===-1||n===32}const Gd=Zl(new RegExp("\\p{P}|\\p{S}","u")),Is=Zl(/\s/);function Zl(n){return e;function e(t){return t!==null&&t>-1&&n.test(String.fromCharCode(t))}}function wa(n){const e=[];let t=-1,i=0,l=0;for(;++t55295&&o<57344){const c=n.charCodeAt(t+1);o<56320&&c>56319&&c<57344?(a=String.fromCharCode(o,c),l=1):a="�"}else a=String.fromCharCode(o);a&&(e.push(n.slice(i,t),encodeURIComponent(a)),i=t+l+1,a=""),l&&(t+=l,l=0)}return e.join("")+n.slice(i)}function ft(n,e,t,i){const l=i?i-1:1/0;let o=0;return a;function a(f){return Je(f)?(n.enter(t),c(f)):e(f)}function c(f){return Je(f)&&o++=l?e(m):t(m)}}const WP={tokenize:ZP};function ZP(n){const e=n.attempt(this.parser.constructs.contentInitial,i,l);let t;return e;function i(c){if(c===null){n.consume(c);return}return n.enter("lineEnding"),n.consume(c),n.exit("lineEnding"),ft(n,e,"linePrefix")}function l(c){return n.enter("paragraph"),o(c)}function o(c){const f=n.enter("chunkText",{contentType:"text",previous:t});return t&&(t.next=f),t=f,a(c)}function a(c){if(c===null){n.exit("chunkText"),n.exit("paragraph"),n.consume(c);return}return He(c)?(n.consume(c),n.exit("chunkText"),o):(n.consume(c),a)}}let Cd=class{constructor(){this.index=new Map,this.map=[]}add(e,t,i){fC(this,e,t,i,!1)}addBefore(e,t,i){fC(this,e,t,i,!0)}consume(e){if(this.map.sort(function(o,a){return o[0]-a[0]}),this.map.length===0)return;let t=this.map.length;const i=[];for(;t>0;)t-=1,i.push(e.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),e.length=this.map[t][0];i.push(e.slice()),e.length=0;let l=i.pop();for(;l;){for(const o of l)e.push(o);l=i.pop()}this.map.length=0,this.index.clear()}};function fC(n,e,t,i,l){if(t===0&&i.length===0)return;const o=n.index.get(e);if(o){o[1]+=t,l?(i.push(...o[2]),o[2]=i):o[2].push(...i);return}const a=[e,t,i];n.map.push(a),n.index.set(e,a)}const JP={tokenize:eH},hC={tokenize:tH};function eH(n){const e=this,t=[];let i=0,l,o,a;return c;function c(M){if(ia))return;const j=e.events.length;let H=j,Z,I;for(;H--;)if(e.events[H][0]==="exit"&&e.events[H][1].type==="chunkFlow"){if(Z){I=e.events[H][1].end;break}Z=!0}for(O(i),D=j;DM;){const L=t[P];e.containerState=L[1],L[0].exit.call(e,n)}t.length=M}function _(){l.write([null]),o=void 0,l=void 0,e.containerState._closeFlow=void 0}}function tH(n,e,t){return ft(n,n.attempt(this.parser.constructs.document,e,t),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Kl(n){if(n===null||Nt(n)||Is(n))return 1;if(Gd(n))return 2}function Yd(n,e,t){const i=[];let l=-1;for(;++l1&&n[t][1].end.offset-n[t][1].start.offset>1?2:1,a={...n[l][1].end},c={...n[t][1].start};dC(a,-o),dC(c,o);const f={type:o>1?"strongSequence":"emphasisSequence",start:a,end:{...n[l][1].end}},d={type:o>1?"strongSequence":"emphasisSequence",start:{...n[t][1].start},end:c},m={type:o>1?"strongText":"emphasisText",start:{...n[l][1].end},end:{...n[t][1].start}},g={type:o>1?"strong":"emphasis",start:{...f.start},end:{...d.end}};n[l][1].end={...f.start},n[t][1].start={...d.end},i=[],n[l][1].end.offset-n[l][1].start.offset&&(i=Di(i,[["enter",n[l][1],e],["exit",n[l][1],e]])),i=Di(i,[["enter",g,e],["enter",f,e],["exit",f,e],["enter",m,e]]),i=Di(i,Yd(e.parser.constructs.insideSpan.null,n.slice(l+1,t),e)),i=Di(i,[["exit",m,e],["enter",d,e],["exit",d,e],["exit",g,e]]);let b=0;n[t][1].end.offset-n[t][1].start.offset&&(b=2,i=Di(i,[["enter",n[t][1],e],["exit",n[t][1],e]])),Yi(n,l-1,t-l+3,i),t=l+i.length-b-2;break}}for(t=-1;++t0&&Je(D)?ft(n,_,"linePrefix",o+1)(D):_(D)}function _(D){return D===null||He(D)?n.check(Q0,S,P)(D):(n.enter("codeFlowValue"),M(D))}function M(D){return D===null||He(D)?(n.exit("codeFlowValue"),_(D)):(n.consume(D),M)}function P(D){return n.exit("codeFenced"),e(D)}function L(D,j,H){let Z=0;return I;function I(ie){return D.enter("lineEnding"),D.consume(ie),D.exit("lineEnding"),F}function F(ie){return D.enter("codeFencedFence"),Je(ie)?ft(D,A,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(ie):A(ie)}function A(ie){return ie===c?(D.enter("codeFencedFenceSequence"),ne(ie)):H(ie)}function ne(ie){return ie===c?(Z++,D.consume(ie),ne):Z>=a?(D.exit("codeFencedFenceSequence"),Je(ie)?ft(D,ae,"whitespace")(ie):ae(ie)):H(ie)}function ae(ie){return ie===null||He(ie)?(D.exit("codeFencedFence"),j(ie)):H(ie)}}}const vx={name:"codeIndented",tokenize:pH},mH={partial:!0,tokenize:gH};function pH(n,e,t){return i;function i(c){return n.enter("codeIndented"),jA(n,l,t,"linePrefix",4,4)(c)}function l(c){return c===null?a(c):He(c)?n.attempt(mH,l,a)(c):(n.enter("codeFlowValue"),o(c))}function o(c){return c===null||He(c)?(n.exit("codeFlowValue"),l(c)):(n.consume(c),o)}function a(c){return n.exit("codeIndented"),e(c)}}function gH(n,e,t){const i=this;return l;function l(a){return i.parser.lazy[i.now().line]?t(a):He(a)?(n.enter("lineEnding"),n.consume(a),n.exit("lineEnding"),l):jA(n,e,o,"linePrefix",4,4)(a)}function o(a){return He(a)?l(a):t(a)}}const xH={name:"codeText",previous:bH,resolve:yH,tokenize:vH};function yH(n){let e=n.length-4,t=3,i,l;if((n[t][1].type==="lineEnding"||n[t][1].type==="space")&&(n[e][1].type==="lineEnding"||n[e][1].type==="space")){for(i=t;++i=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return ethis.left.length?this.right.slice(this.right.length-i+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-i+this.left.length).reverse())}splice(e,t,i){const l=t||0;this.setCursor(Math.trunc(e));const o=this.right.splice(this.right.length-l,Number.POSITIVE_INFINITY);return i&&kc(this.left,i),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),kc(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),kc(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e=4?e(a):n.interrupt(i.parser.constructs.flow,t,e)(a)}}function BA(n,e,t,i,l,o,a,c,f){const d=f||Number.POSITIVE_INFINITY;let m=0;return g;function g(O){return O===60?(n.enter(i),n.enter(l),n.enter(o),n.consume(O),n.exit(o),b):O===null||O===32||O===41||Sd(O)?t(O):(n.enter(i),n.enter(a),n.enter(c),n.enter("chunkString",{contentType:"string"}),S(O))}function b(O){return O===62?(n.enter(o),n.consume(O),n.exit(o),n.exit(l),n.exit(i),e):(n.enter(c),n.enter("chunkString",{contentType:"string"}),v(O))}function v(O){return O===62?(n.exit("chunkString"),n.exit(c),b(O)):O===null||O===60||He(O)?t(O):(n.consume(O),O===92?w:v)}function w(O){return O===60||O===62||O===92?(n.consume(O),v):v(O)}function S(O){return!m&&(O===null||O===41||Nt(O))?(n.exit("chunkString"),n.exit(c),n.exit(a),n.exit(i),e(O)):m999||v===null||v===91||v===93&&!f||v===94&&!c&&"_hiddenFootnoteSupport"in a.parser.constructs?t(v):v===93?(n.exit(o),n.enter(l),n.consume(v),n.exit(l),n.exit(i),e):He(v)?(n.enter("lineEnding"),n.consume(v),n.exit("lineEnding"),m):(n.enter("chunkString",{contentType:"string"}),g(v))}function g(v){return v===null||v===91||v===93||He(v)||c++>999?(n.exit("chunkString"),m(v)):(n.consume(v),f||(f=!Je(v)),v===92?b:g)}function b(v){return v===91||v===92||v===93?(n.consume(v),c++,g):g(v)}}function HA(n,e,t,i,l,o){let a;return c;function c(b){return b===34||b===39||b===40?(n.enter(i),n.enter(l),n.consume(b),n.exit(l),a=b===40?41:b,f):t(b)}function f(b){return b===a?(n.enter(l),n.consume(b),n.exit(l),n.exit(i),e):(n.enter(o),d(b))}function d(b){return b===a?(n.exit(o),f(a)):b===null?t(b):He(b)?(n.enter("lineEnding"),n.consume(b),n.exit("lineEnding"),ft(n,d,"linePrefix")):(n.enter("chunkString",{contentType:"string"}),m(b))}function m(b){return b===a||b===null||He(b)?(n.exit("chunkString"),d(b)):(n.consume(b),b===92?g:m)}function g(b){return b===a||b===92?(n.consume(b),m):m(b)}}function Hc(n,e){let t;return i;function i(l){return He(l)?(n.enter("lineEnding"),n.consume(l),n.exit("lineEnding"),t=!0,i):Je(l)?ft(n,i,t?"linePrefix":"lineSuffix")(l):e(l)}}const AH={name:"definition",tokenize:MH},EH={partial:!0,tokenize:DH};function MH(n,e,t){const i=this;let l;return o;function o(v){return n.enter("definition"),a(v)}function a(v){return PA.call(i,n,c,t,"definitionLabel","definitionLabelMarker","definitionLabelString")(v)}function c(v){return l=Ki(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),v===58?(n.enter("definitionMarker"),n.consume(v),n.exit("definitionMarker"),f):t(v)}function f(v){return Nt(v)?Hc(n,d)(v):d(v)}function d(v){return BA(n,m,t,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function m(v){return n.attempt(EH,g,g)(v)}function g(v){return Je(v)?ft(n,b,"whitespace")(v):b(v)}function b(v){return v===null||He(v)?(n.exit("definition"),i.parser.defined.push(l),e(v)):t(v)}}function DH(n,e,t){return i;function i(c){return Nt(c)?Hc(n,l)(c):t(c)}function l(c){return HA(n,o,t,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return Je(c)?ft(n,a,"whitespace")(c):a(c)}function a(c){return c===null||He(c)?e(c):t(c)}}const jH={name:"hardBreakEscape",tokenize:RH};function RH(n,e,t){return i;function i(o){return n.enter("hardBreakEscape"),n.consume(o),l}function l(o){return He(o)?(n.exit("hardBreakEscape"),e(o)):t(o)}}const _H={name:"headingAtx",resolve:LH,tokenize:zH};function LH(n,e){let t=n.length-2,i=3;if(n[i][1].type==="whitespace"&&(i+=2),t-2>i&&n[t][1].type==="whitespace"&&(t-=2),n[t][1].type==="atxHeadingSequence"&&(i===t-1||t-4>i&&n[t-2][1].type==="whitespace")&&(t-=i+1===t?2:4),t>i){const l={type:"atxHeadingText",start:n[i][1].start,end:n[t][1].end},o={type:"chunkText",start:n[i][1].start,end:n[t][1].end,contentType:"text"};Yi(n,i,t-i+1,[["enter",l,e],["enter",o,e],["exit",o,e],["exit",l,e]])}return n}function zH(n,e,t){let i=0;return l;function l(m){return n.enter("atxHeading"),o(m)}function o(m){return n.enter("atxHeadingSequence"),a(m)}function a(m){return m===35&&i++<6?(n.consume(m),a):m===null||Nt(m)?(n.exit("atxHeadingSequence"),c(m)):t(m)}function c(m){return m===35?(n.enter("atxHeadingSequence"),f(m)):m===null||He(m)?(n.exit("atxHeading"),e(m)):Je(m)?ft(n,c,"whitespace")(m):(n.enter("atxHeadingText"),d(m))}function f(m){return m===35?(n.consume(m),f):(n.exit("atxHeadingSequence"),c(m))}function d(m){return m===null||m===35||Nt(m)?(n.exit("atxHeadingText"),c(m)):(n.consume(m),d)}}const IA=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],X0=["pre","script","style","textarea"],BH={concrete:!0,name:"htmlFlow",resolveTo:HH,tokenize:IH},PH={partial:!0,tokenize:UH};function HH(n){let e=n.length;for(;e--&&!(n[e][0]==="enter"&&n[e][1].type==="htmlFlow"););return e>1&&n[e-2][1].type==="linePrefix"&&(n[e][1].start=n[e-2][1].start,n[e+1][1].start=n[e-2][1].start,n.splice(e-2,2)),n}function IH(n,e,t){const i=this;let l,o,a,c,f;return d;function d(B){return m(B)}function m(B){return n.enter("htmlFlow"),n.enter("htmlFlowData"),n.consume(B),g}function g(B){return B===33?(n.consume(B),b):B===47?(n.consume(B),o=!0,S):B===63?(n.consume(B),l=3,i.interrupt?e:T):Cn(B)?(n.consume(B),a=String.fromCharCode(B),C):t(B)}function b(B){return B===45?(n.consume(B),l=2,v):B===91?(n.consume(B),l=5,c=0,w):Cn(B)?(n.consume(B),l=4,i.interrupt?e:T):t(B)}function v(B){return B===45?(n.consume(B),i.interrupt?e:T):t(B)}function w(B){const R="CDATA[";return B===R.charCodeAt(c++)?(n.consume(B),c===R.length?i.interrupt?e:A:w):t(B)}function S(B){return Cn(B)?(n.consume(B),a=String.fromCharCode(B),C):t(B)}function C(B){if(B===null||B===47||B===62||Nt(B)){const R=B===47,V=a.toLowerCase();return!R&&!o&&X0.includes(V)?(l=1,i.interrupt?e(B):A(B)):IA.includes(a.toLowerCase())?(l=6,R?(n.consume(B),O):i.interrupt?e(B):A(B)):(l=7,i.interrupt&&!i.parser.lazy[i.now().line]?t(B):o?_(B):M(B))}return B===45||On(B)?(n.consume(B),a+=String.fromCharCode(B),C):t(B)}function O(B){return B===62?(n.consume(B),i.interrupt?e:A):t(B)}function _(B){return Je(B)?(n.consume(B),_):I(B)}function M(B){return B===47?(n.consume(B),I):B===58||B===95||Cn(B)?(n.consume(B),P):Je(B)?(n.consume(B),M):I(B)}function P(B){return B===45||B===46||B===58||B===95||On(B)?(n.consume(B),P):L(B)}function L(B){return B===61?(n.consume(B),D):Je(B)?(n.consume(B),L):M(B)}function D(B){return B===null||B===60||B===61||B===62||B===96?t(B):B===34||B===39?(n.consume(B),f=B,j):Je(B)?(n.consume(B),D):H(B)}function j(B){return B===f?(n.consume(B),f=null,Z):B===null||He(B)?t(B):(n.consume(B),j)}function H(B){return B===null||B===34||B===39||B===47||B===60||B===61||B===62||B===96||Nt(B)?L(B):(n.consume(B),H)}function Z(B){return B===47||B===62||Je(B)?M(B):t(B)}function I(B){return B===62?(n.consume(B),F):t(B)}function F(B){return B===null||He(B)?A(B):Je(B)?(n.consume(B),F):t(B)}function A(B){return B===45&&l===2?(n.consume(B),$):B===60&&l===1?(n.consume(B),oe):B===62&&l===4?(n.consume(B),he):B===63&&l===3?(n.consume(B),T):B===93&&l===5?(n.consume(B),Y):He(B)&&(l===6||l===7)?(n.exit("htmlFlowData"),n.check(PH,ye,ne)(B)):B===null||He(B)?(n.exit("htmlFlowData"),ne(B)):(n.consume(B),A)}function ne(B){return n.check(Q0,ae,ye)(B)}function ae(B){return n.enter("lineEnding"),n.consume(B),n.exit("lineEnding"),ie}function ie(B){return B===null||He(B)?ne(B):(n.enter("htmlFlowData"),A(B))}function $(B){return B===45?(n.consume(B),T):A(B)}function oe(B){return B===47?(n.consume(B),a="",J):A(B)}function J(B){if(B===62){const R=a.toLowerCase();return X0.includes(R)?(n.consume(B),he):A(B)}return Cn(B)&&a.length<8?(n.consume(B),a+=String.fromCharCode(B),J):A(B)}function Y(B){return B===93?(n.consume(B),T):A(B)}function T(B){return B===62?(n.consume(B),he):B===45&&l===2?(n.consume(B),T):A(B)}function he(B){return B===null||He(B)?(n.exit("htmlFlowData"),ye(B)):(n.consume(B),he)}function ye(B){return n.exit("htmlFlow"),e(B)}}function UH(n,e,t){return i;function i(l){return n.enter("lineEnding"),n.consume(l),n.exit("lineEnding"),n.attempt(mu,e,t)}}const FH={name:"htmlText",tokenize:qH};function qH(n,e,t){const i=this;let l,o,a;return c;function c(T){return n.enter("htmlText"),n.enter("htmlTextData"),n.consume(T),f}function f(T){return T===33?(n.consume(T),d):T===47?(n.consume(T),L):T===63?(n.consume(T),M):Cn(T)?(n.consume(T),H):t(T)}function d(T){return T===45?(n.consume(T),m):T===91?(n.consume(T),o=0,w):Cn(T)?(n.consume(T),_):t(T)}function m(T){return T===45?(n.consume(T),v):t(T)}function g(T){return T===null?t(T):T===45?(n.consume(T),b):He(T)?(a=g,oe(T)):(n.consume(T),g)}function b(T){return T===45?(n.consume(T),v):g(T)}function v(T){return T===62?$(T):T===45?b(T):g(T)}function w(T){const he="CDATA[";return T===he.charCodeAt(o++)?(n.consume(T),o===he.length?S:w):t(T)}function S(T){return T===null?t(T):T===93?(n.consume(T),C):He(T)?(a=S,oe(T)):(n.consume(T),S)}function C(T){return T===93?(n.consume(T),O):S(T)}function O(T){return T===62?$(T):T===93?(n.consume(T),O):S(T)}function _(T){return T===null||T===62?$(T):He(T)?(a=_,oe(T)):(n.consume(T),_)}function M(T){return T===null?t(T):T===63?(n.consume(T),P):He(T)?(a=M,oe(T)):(n.consume(T),M)}function P(T){return T===62?$(T):M(T)}function L(T){return Cn(T)?(n.consume(T),D):t(T)}function D(T){return T===45||On(T)?(n.consume(T),D):j(T)}function j(T){return He(T)?(a=j,oe(T)):Je(T)?(n.consume(T),j):$(T)}function H(T){return T===45||On(T)?(n.consume(T),H):T===47||T===62||Nt(T)?Z(T):t(T)}function Z(T){return T===47?(n.consume(T),$):T===58||T===95||Cn(T)?(n.consume(T),I):He(T)?(a=Z,oe(T)):Je(T)?(n.consume(T),Z):$(T)}function I(T){return T===45||T===46||T===58||T===95||On(T)?(n.consume(T),I):F(T)}function F(T){return T===61?(n.consume(T),A):He(T)?(a=F,oe(T)):Je(T)?(n.consume(T),F):Z(T)}function A(T){return T===null||T===60||T===61||T===62||T===96?t(T):T===34||T===39?(n.consume(T),l=T,ne):He(T)?(a=A,oe(T)):Je(T)?(n.consume(T),A):(n.consume(T),ae)}function ne(T){return T===l?(n.consume(T),l=void 0,ie):T===null?t(T):He(T)?(a=ne,oe(T)):(n.consume(T),ne)}function ae(T){return T===null||T===34||T===39||T===60||T===61||T===96?t(T):T===47||T===62||Nt(T)?Z(T):(n.consume(T),ae)}function ie(T){return T===47||T===62||Nt(T)?Z(T):t(T)}function $(T){return T===62?(n.consume(T),n.exit("htmlTextData"),n.exit("htmlText"),e):t(T)}function oe(T){return n.exit("htmlTextData"),n.enter("lineEnding"),n.consume(T),n.exit("lineEnding"),J}function J(T){return Je(T)?ft(n,Y,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):Y(T)}function Y(T){return n.enter("htmlTextData"),a(T)}}const Jy={name:"labelEnd",resolveAll:$H,resolveTo:GH,tokenize:YH},VH={tokenize:KH},QH={tokenize:WH},XH={tokenize:ZH};function $H(n){let e=-1;const t=[];for(;++e0&&l[l.length-1]._balanced;)l.pop();o=l[l.length-1]}return c;function c(b){return o?o._inactive?g(b):(a=i.parser.defined.includes(Ki(i.sliceSerialize({start:o.end,end:i.now()}))),n.enter("labelEnd"),n.enter("labelMarker"),n.consume(b),n.exit("labelMarker"),n.exit("labelEnd"),f):t(b)}function f(b){return b===40?n.attempt(VH,m,a?m:g)(b):b===91?n.attempt(QH,m,a?d:g)(b):a?m(b):g(b)}function d(b){return n.attempt(XH,m,g)(b)}function m(b){return l.pop(),e(b)}function g(b){return o._balanced=!0,t(b)}}function KH(n,e,t){return i;function i(g){return n.enter("resource"),n.enter("resourceMarker"),n.consume(g),n.exit("resourceMarker"),l}function l(g){return Nt(g)?Hc(n,o)(g):o(g)}function o(g){return g===41?m(g):BA(n,a,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(g)}function a(g){return Nt(g)?Hc(n,f)(g):m(g)}function c(g){return t(g)}function f(g){return g===34||g===39||g===40?HA(n,d,t,"resourceTitle","resourceTitleMarker","resourceTitleString")(g):m(g)}function d(g){return Nt(g)?Hc(n,m)(g):m(g)}function m(g){return g===41?(n.enter("resourceMarker"),n.consume(g),n.exit("resourceMarker"),n.exit("resource"),e):t(g)}}function WH(n,e,t){const i=this;return l;function l(c){return PA.call(i,n,o,a,"reference","referenceMarker","referenceString")(c)}function o(c){return i.parser.defined.includes(Ki(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?e(c):t(c)}function a(c){return t(c)}}function ZH(n,e,t){return i;function i(o){return n.enter("reference"),n.enter("referenceMarker"),n.consume(o),n.exit("referenceMarker"),l}function l(o){return o===93?(n.enter("referenceMarker"),n.consume(o),n.exit("referenceMarker"),n.exit("reference"),e):t(o)}}const JH={name:"labelStartImage",resolveAll:Jy.resolveAll,tokenize:e7};function e7(n,e,t){const i=this;let l;return o;function o(f){return n.enter("labelImage"),n.enter("labelImageMarker"),n.consume(f),n.exit("labelImageMarker"),a}function a(f){return f===91?(n.enter("labelMarker"),n.consume(f),n.exit("labelMarker"),l=n.exit("labelImage"),c):t(f)}function c(f){return f===94&&"_hiddenFootnoteSupport"in i.parser.constructs?t(f):(i._labelStarts=i._labelStarts||[],i._labelStarts.push(l),e(f))}}const t7={name:"labelStartLink",resolveAll:Jy.resolveAll,tokenize:n7};function n7(n,e,t){const i=this;let l;return o;function o(c){return n.enter("labelLink"),n.enter("labelMarker"),n.consume(c),n.exit("labelMarker"),l=n.exit("labelLink"),a}function a(c){return c===94&&"_hiddenFootnoteSupport"in i.parser.constructs?t(c):(i._labelStarts=i._labelStarts||[],i._labelStarts.push(l),e(c))}}const wx={name:"lineEnding",tokenize:i7};function i7(n,e){return t;function t(i){return n.enter("lineEnding"),n.consume(i),n.exit("lineEnding"),ft(n,e,"linePrefix")}}const qh={name:"thematicBreak",tokenize:r7};function r7(n,e,t){let i=0,l;return o;function o(d){return n.enter("thematicBreak"),a(d)}function a(d){return l=d,c(d)}function c(d){return d===l?(n.enter("thematicBreakSequence"),f(d)):i>=3&&(d===null||He(d))?(n.exit("thematicBreak"),e(d)):t(d)}function f(d){return d===l?(n.consume(d),i++,f):(n.exit("thematicBreakSequence"),Je(d)?ft(n,c,"whitespace")(d):c(d))}}const Zn={continuation:{tokenize:a7},exit:u7,name:"list",tokenize:o7},l7={partial:!0,tokenize:f7},s7={partial:!0,tokenize:c7};function o7(n,e,t){const i=this,l=i.events[i.events.length-1];let o=l&&l[1].type==="linePrefix"?l[2].sliceSerialize(l[1],!0).length:0,a=0;return c;function c(v){const w=i.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(w==="listUnordered"?!i.containerState.marker||v===i.containerState.marker:q0(v)){if(i.containerState.type||(i.containerState.type=w,n.enter(w,{_container:!0})),w==="listUnordered")return n.enter("listItemPrefix"),v===42||v===45?n.check(qh,t,d)(v):d(v);if(!i.interrupt||v===49)return n.enter("listItemPrefix"),n.enter("listItemValue"),f(v)}return t(v)}function f(v){return q0(v)&&++a<10?(n.consume(v),f):(!i.interrupt||a<2)&&(i.containerState.marker?v===i.containerState.marker:v===41||v===46)?(n.exit("listItemValue"),d(v)):t(v)}function d(v){return n.enter("listItemMarker"),n.consume(v),n.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||v,n.check(mu,i.interrupt?t:m,n.attempt(l7,b,g))}function m(v){return i.containerState.initialBlankLine=!0,o++,b(v)}function g(v){return Je(v)?(n.enter("listItemPrefixWhitespace"),n.consume(v),n.exit("listItemPrefixWhitespace"),b):t(v)}function b(v){return i.containerState.size=o+i.sliceSerialize(n.exit("listItemPrefix"),!0).length,e(v)}}function a7(n,e,t){const i=this;return i.containerState._closeFlow=void 0,n.check(mu,l,o);function l(c){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,ft(n,e,"listItemIndent",i.containerState.size+1)(c)}function o(c){return i.containerState.furtherBlankLines||!Je(c)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,a(c)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,n.attempt(s7,e,a)(c))}function a(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,ft(n,n.attempt(Zn,e,t),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function c7(n,e,t){const i=this;return ft(n,l,"listItemIndent",i.containerState.size+1);function l(o){const a=i.events[i.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===i.containerState.size?e(o):t(o)}}function u7(n){n.exit(this.containerState.type)}function f7(n,e,t){const i=this;return ft(n,l,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function l(o){const a=i.events[i.events.length-1];return!Je(o)&&a&&a[1].type==="listItemPrefixWhitespace"?e(o):t(o)}}const pC={name:"setextUnderline",resolveTo:h7,tokenize:d7};function h7(n,e){const t=new Cd;let i=n.length,l,o,a;for(;i--;)if(n[i][0]==="enter"){if(n[i][1].type==="content"){l=i;break}n[i][1].type==="paragraph"&&(o=i)}else n[i][1].type==="content"&&t.add(i,1,[]),!a&&n[i][1].type==="definition"&&(a=i);const c={type:"setextHeading",start:{...n[l][1].start},end:{...n[n.length-1][1].end}};return n[o][1].type="setextHeadingText",a?(t.add(o,0,[["enter",c,e]]),t.add(a+1,0,[["exit",n[l][1],e]]),n[l][1].end={...n[a][1].end}):n[l][1]=c,t.add(n.length,0,[["exit",c,e]]),t.consume(n),n}function d7(n,e,t){const i=this;let l;return o;function o(d){let m=i.events.length,g;for(;m--;)if(i.events[m][1].type!=="lineEnding"&&i.events[m][1].type!=="linePrefix"&&i.events[m][1].type!=="content"){g=i.events[m][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||g)?(n.enter("setextHeadingLine"),l=d,a(d)):t(d)}function a(d){return n.enter("setextHeadingLineSequence"),c(d)}function c(d){return d===l?(n.consume(d),c):(n.exit("setextHeadingLineSequence"),Je(d)?ft(n,f,"lineSuffix")(d):f(d))}function f(d){return d===null||He(d)?(n.exit("setextHeadingLine"),e(d)):t(d)}}const m7={tokenize:p7};function p7(n){const e=this,t=n.attempt(mu,i,n.attempt(this.parser.constructs.flowInitial,l,ft(n,n.attempt(this.parser.constructs.flow,l,n.attempt(SH,l)),"linePrefix")));return t;function i(o){if(o===null){n.consume(o);return}return n.enter("lineEndingBlank"),n.consume(o),n.exit("lineEndingBlank"),e.currentConstruct=void 0,t}function l(o){if(o===null){n.consume(o);return}return n.enter("lineEnding"),n.consume(o),n.exit("lineEnding"),e.currentConstruct=void 0,t}}const g7={resolveAll:FA()},x7=UA("string"),y7=UA("text");function UA(n){return{resolveAll:FA(n==="text"?b7:void 0),tokenize:e};function e(t){const i=this,l=this.parser.constructs[n],o=t.attempt(l,a,c);return a;function a(m){return d(m)?o(m):c(m)}function c(m){if(m===null){t.consume(m);return}return t.enter("data"),t.consume(m),f}function f(m){return d(m)?(t.exit("data"),o(m)):(t.consume(m),f)}function d(m){if(m===null)return!0;const g=l[m];let b=-1;if(g)for(;++b-1){const c=a[0];typeof c=="string"?a[0]=c.slice(i):a.shift()}o>0&&a.push(n[l].slice(0,o))}return a}function j7(n,e){let t=-1;const i=[];let l;for(;++t0&&!t&&(n[n.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),t}const cq={tokenize:xq,partial:!0};function uq(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:mq,continuation:{tokenize:pq},exit:gq}},text:{91:{name:"gfmFootnoteCall",tokenize:dq},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:fq,resolveTo:hq}}}}function fq(n,e,t){const i=this;let l=i.events.length;const o=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let a;for(;l--;){const f=i.events[l][1];if(f.type==="labelImage"){a=f;break}if(f.type==="gfmFootnoteCall"||f.type==="labelLink"||f.type==="label"||f.type==="image"||f.type==="link")break}return c;function c(f){if(!a||!a._balanced)return t(f);const d=Ki(i.sliceSerialize({start:a.end,end:i.now()}));return d.codePointAt(0)!==94||!o.includes(d.slice(1))?t(f):(n.enter("gfmFootnoteCallLabelMarker"),n.consume(f),n.exit("gfmFootnoteCallLabelMarker"),e(f))}}function hq(n,e){let t=n.length;for(;t--;)if(n[t][1].type==="labelImage"&&n[t][0]==="enter"){n[t][1];break}n[t+1][1].type="data",n[t+3][1].type="gfmFootnoteCallLabelMarker";const i={type:"gfmFootnoteCall",start:Object.assign({},n[t+3][1].start),end:Object.assign({},n[n.length-1][1].end)},l={type:"gfmFootnoteCallMarker",start:Object.assign({},n[t+3][1].end),end:Object.assign({},n[t+3][1].end)};l.end.column++,l.end.offset++,l.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},l.end),end:Object.assign({},n[n.length-1][1].start)},a={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},c=[n[t+1],n[t+2],["enter",i,e],n[t+3],n[t+4],["enter",l,e],["exit",l,e],["enter",o,e],["enter",a,e],["exit",a,e],["exit",o,e],n[n.length-2],n[n.length-1],["exit",i,e]];return n.splice(t,n.length-t+1,...c),n}function dq(n,e,t){const i=this,l=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o=0,a;return c;function c(g){return n.enter("gfmFootnoteCall"),n.enter("gfmFootnoteCallLabelMarker"),n.consume(g),n.exit("gfmFootnoteCallLabelMarker"),f}function f(g){return g!==94?t(g):(n.enter("gfmFootnoteCallMarker"),n.consume(g),n.exit("gfmFootnoteCallMarker"),n.enter("gfmFootnoteCallString"),n.enter("chunkString").contentType="string",d)}function d(g){if(o>999||g===93&&!a||g===null||g===91||Nt(g))return t(g);if(g===93){n.exit("chunkString");const b=n.exit("gfmFootnoteCallString");return l.includes(Ki(i.sliceSerialize(b)))?(n.enter("gfmFootnoteCallLabelMarker"),n.consume(g),n.exit("gfmFootnoteCallLabelMarker"),n.exit("gfmFootnoteCall"),e):t(g)}return Nt(g)||(a=!0),o++,n.consume(g),g===92?m:d}function m(g){return g===91||g===92||g===93?(n.consume(g),o++,d):d(g)}}function mq(n,e,t){const i=this,l=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o,a=0,c;return f;function f(w){return n.enter("gfmFootnoteDefinition")._container=!0,n.enter("gfmFootnoteDefinitionLabel"),n.enter("gfmFootnoteDefinitionLabelMarker"),n.consume(w),n.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(w){return w===94?(n.enter("gfmFootnoteDefinitionMarker"),n.consume(w),n.exit("gfmFootnoteDefinitionMarker"),n.enter("gfmFootnoteDefinitionLabelString"),n.enter("chunkString").contentType="string",m):t(w)}function m(w){if(a>999||w===93&&!c||w===null||w===91||Nt(w))return t(w);if(w===93){n.exit("chunkString");const S=n.exit("gfmFootnoteDefinitionLabelString");return o=Ki(i.sliceSerialize(S)),n.enter("gfmFootnoteDefinitionLabelMarker"),n.consume(w),n.exit("gfmFootnoteDefinitionLabelMarker"),n.exit("gfmFootnoteDefinitionLabel"),b}return Nt(w)||(c=!0),a++,n.consume(w),w===92?g:m}function g(w){return w===91||w===92||w===93?(n.consume(w),a++,m):m(w)}function b(w){return w===58?(n.enter("definitionMarker"),n.consume(w),n.exit("definitionMarker"),l.includes(o)||l.push(o),ft(n,v,"gfmFootnoteDefinitionWhitespace")):t(w)}function v(w){return e(w)}}function pq(n,e,t){return n.check(mu,e,n.attempt(cq,e,t))}function gq(n){n.exit("gfmFootnoteDefinition")}function xq(n,e,t){const i=this;return ft(n,l,"gfmFootnoteDefinitionIndent",5);function l(o){const a=i.events[i.events.length-1];return a&&a[1].type==="gfmFootnoteDefinitionIndent"&&a[2].sliceSerialize(a[1],!0).length===4?e(o):t(o)}}function yq(n){let t=(n||{}).singleTilde;const i={name:"strikethrough",tokenize:o,resolveAll:l};return t==null&&(t=!0),{text:{126:i},insideSpan:{null:[i]},attentionMarkers:{null:[126]}};function l(a,c){let f=-1;for(;++f1?f(w):(a.consume(w),g++,v);if(g<2&&!t)return f(w);const C=a.exit("strikethroughSequenceTemporary"),O=Kl(w);return C._open=!O||O===2&&!!S,C._close=!S||S===2&&!!O,c(w)}}}class bq{constructor(){this.map=[],this.index=new Map}add(e,t,i){vq(this,e,t,i)}consume(e){if(this.map.sort(function(o,a){return o[0]-a[0]}),this.map.length===0)return;let t=this.map.length;const i=[];for(;t>0;)t-=1,i.push(e.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),e.length=this.map[t][0];i.push(e.slice()),e.length=0;let l=i.pop();for(;l;){for(const o of l)e.push(o);l=i.pop()}this.map.length=0,this.index.clear()}}function vq(n,e,t,i){if(t===0&&i.length===0)return;const l=n.index.get(e);if(l){l[1]+=t,l[2].push(...i);return}const o=[e,t,i];n.map.push(o),n.index.set(e,o)}function wq(n,e){let t=!1;const i=[];for(;e-1;){const{type:ae}=i.events[F][1];if(ae==="lineEnding"||ae==="linePrefix")F--;else break}const A=F>-1?i.events[F][1].type:null,ne=A==="tableHead"||A==="tableRow"?D:f;return ne===D&&i.parser.lazy[i.now().line]?t(I):ne(I)}function f(I){return n.enter("tableHead"),n.enter("tableRow"),d(I)}function d(I){return I===124||(a=!0,o+=1),m(I)}function m(I){return I===null?t(I):He(I)?o>1?(o=0,i.interrupt=!0,n.exit("tableRow"),n.enter("lineEnding"),n.consume(I),n.exit("lineEnding"),v):t(I):Je(I)?ft(n,m,"whitespace")(I):(o+=1,a&&(a=!1,l+=1),I===124?(n.enter("tableCellDivider"),n.consume(I),n.exit("tableCellDivider"),a=!0,m):(n.enter("data"),g(I)))}function g(I){return I===null||I===124||Nt(I)?(n.exit("data"),m(I)):(n.consume(I),I===92?b:g)}function b(I){return I===92||I===124?(n.consume(I),g):g(I)}function v(I){return i.interrupt=!1,i.parser.lazy[i.now().line]?t(I):(n.enter("tableDelimiterRow"),a=!1,Je(I)?ft(n,w,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):w(I))}function w(I){return I===45||I===58?C(I):I===124?(a=!0,n.enter("tableCellDivider"),n.consume(I),n.exit("tableCellDivider"),S):L(I)}function S(I){return Je(I)?ft(n,C,"whitespace")(I):C(I)}function C(I){return I===58?(o+=1,a=!0,n.enter("tableDelimiterMarker"),n.consume(I),n.exit("tableDelimiterMarker"),O):I===45?(o+=1,O(I)):I===null||He(I)?P(I):L(I)}function O(I){return I===45?(n.enter("tableDelimiterFiller"),_(I)):L(I)}function _(I){return I===45?(n.consume(I),_):I===58?(a=!0,n.exit("tableDelimiterFiller"),n.enter("tableDelimiterMarker"),n.consume(I),n.exit("tableDelimiterMarker"),M):(n.exit("tableDelimiterFiller"),M(I))}function M(I){return Je(I)?ft(n,P,"whitespace")(I):P(I)}function P(I){return I===124?w(I):I===null||He(I)?!a||l!==o?L(I):(n.exit("tableDelimiterRow"),n.exit("tableHead"),e(I)):L(I)}function L(I){return t(I)}function D(I){return n.enter("tableRow"),j(I)}function j(I){return I===124?(n.enter("tableCellDivider"),n.consume(I),n.exit("tableCellDivider"),j):I===null||He(I)?(n.exit("tableRow"),e(I)):Je(I)?ft(n,j,"whitespace")(I):(n.enter("data"),H(I))}function H(I){return I===null||I===124||Nt(I)?(n.exit("data"),j(I)):(n.consume(I),I===92?Z:H)}function Z(I){return I===92||I===124?(n.consume(I),H):H(I)}}function Cq(n,e){let t=-1,i=!0,l=0,o=[0,0,0,0],a=[0,0,0,0],c=!1,f=0,d,m,g;const b=new bq;for(;++tt[2]+1){const w=t[2]+1,S=t[3]-t[2]-1;n.add(w,S,[])}}n.add(t[3]+1,0,[["exit",g,e]])}return l!==void 0&&(o.end=Object.assign({},qo(e.events,l)),n.add(l,0,[["exit",o,e]]),o=void 0),o}function UC(n,e,t,i,l){const o=[],a=qo(e.events,t);l&&(l.end=Object.assign({},a),o.push(["exit",l,e])),i.end=Object.assign({},a),o.push(["exit",i,e]),n.add(t+1,0,o)}function qo(n,e){const t=n[e],i=t[0]==="enter"?"start":"end";return t[1][i]}const Oq={name:"tasklistCheck",tokenize:Tq};function Nq(){return{text:{91:Oq}}}function Tq(n,e,t){const i=this;return l;function l(f){return i.previous!==null||!i._gfmTasklistFirstContentOfListItem?t(f):(n.enter("taskListCheck"),n.enter("taskListCheckMarker"),n.consume(f),n.exit("taskListCheckMarker"),o)}function o(f){return Nt(f)?(n.enter("taskListCheckValueUnchecked"),n.consume(f),n.exit("taskListCheckValueUnchecked"),a):f===88||f===120?(n.enter("taskListCheckValueChecked"),n.consume(f),n.exit("taskListCheckValueChecked"),a):t(f)}function a(f){return f===93?(n.enter("taskListCheckMarker"),n.consume(f),n.exit("taskListCheckMarker"),n.exit("taskListCheck"),c):t(f)}function c(f){return He(f)?e(f):Je(f)?n.check({tokenize:Aq},e,t)(f):t(f)}}function Aq(n,e,t){return ft(n,i,"whitespace");function i(l){return l===null?t(l):e(l)}}function Eq(n){return EA([eq(),uq(),yq(n),kq(),Nq()])}const Mq={};function Dq(n){const e=this,t=n||Mq,i=e.data(),l=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),a=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);l.push(Eq(t)),o.push(KF()),a.push(WF(t))}function jq(n){return n.replace(/\\n/g,` `).replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\'/g,"'").replace(/\\\\/g,"\\")}const Rq={h1:({children:n})=>y.jsx("h3",{className:"mt-3 mb-1.5 text-base font-bold text-ink first:mt-0",children:n}),h2:({children:n})=>y.jsx("h4",{className:"mt-3 mb-1 text-sm font-semibold text-ink first:mt-0",children:n}),h3:({children:n})=>y.jsx("h5",{className:"mt-2 mb-1 text-xs font-semibold text-ink first:mt-0",children:n}),p:({children:n})=>y.jsx("p",{className:"my-1.5 leading-relaxed first:mt-0 last:mb-0",children:n}),strong:({children:n})=>y.jsx("strong",{className:"font-semibold text-ink",children:n}),em:({children:n})=>y.jsx("em",{className:"italic text-ink-secondary",children:n}),del:({children:n})=>y.jsx("del",{className:"text-ink-muted line-through",children:n}),a:({children:n,href:e})=>y.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"text-chip-indigo-text underline underline-offset-2 hover:text-ink",children:n}),code:({children:n,className:e})=>y.jsx("code",{className:`break-words rounded bg-elevated px-1 py-0.5 font-mono text-chip-indigo-text whitespace-pre-wrap ${e??""}`,children:n}),pre:({children:n})=>y.jsx("pre",{className:"my-2 overflow-x-auto rounded-lg border border-line bg-elevated p-3 font-mono text-xs text-ink [&_code]:bg-transparent [&_code]:px-0 [&_code]:py-0 [&_code]:text-inherit",children:n}),ul:({children:n})=>y.jsx("ul",{className:"my-1.5 list-disc space-y-0.5 pl-5",children:n}),ol:({children:n})=>y.jsx("ol",{className:"my-1.5 list-decimal space-y-0.5 pl-5",children:n}),li:({children:n})=>y.jsx("li",{className:"leading-relaxed",children:n}),blockquote:({children:n})=>y.jsx("blockquote",{className:"my-2 border-l-2 border-line-strong pl-3 text-ink-secondary italic",children:n}),table:({children:n})=>y.jsx("div",{className:"my-2 overflow-x-auto",children:y.jsx("table",{className:"w-full border-collapse text-xs",children:n})}),th:({children:n})=>y.jsx("th",{className:"border border-line bg-elevated px-2 py-1 text-left font-semibold",children:n}),td:({children:n})=>y.jsx("td",{className:"border border-line px-2 py-1 align-top",children:n}),hr:()=>y.jsx("hr",{className:"my-3 border-line"}),img:({alt:n,src:e,title:t})=>y.jsx("img",{src:e,alt:n,title:t,loading:"lazy",referrerPolicy:"no-referrer",className:"my-2 max-w-full rounded-lg border border-line"})};function Eh({text:n}){return n?y.jsx(aU,{remarkPlugins:[Dq,bU],components:Rq,children:jq(n)}):null}function CE(n){return n==="completed"||n==="aborted"||n==="failed"}function Cc({label:n}){return y.jsx("kbd",{"aria-hidden":"true",className:"ml-1.5 inline-block rounded border border-line/60 bg-elevated/60 px-1 py-px font-mono text-[10px] font-normal leading-none opacity-90",children:n})}function FC(n){!n||CE(n.status)||IM(n.session_id).catch(()=>{})}const _q={running:"running",completed:"done",skipped:"skipped",failed:"failed",pending:"pending"};function Mh({text:n}){const[e,t]=E.useState(!1),i=E.useRef(void 0);E.useEffect(()=>()=>window.clearTimeout(i.current),[]);const l=async()=>{try{await navigator.clipboard.writeText(n),t(!0),window.clearTimeout(i.current),i.current=window.setTimeout(()=>t(!1),1500)}catch{}};return y.jsx("button",{type:"button",onClick:l,"aria-label":e?"Copied":"Copy content",title:e?"Copied!":"Copy content",className:"absolute right-2 top-2 rounded-md p-1.5 text-ink-muted hover:bg-elevated hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500",children:e?y.jsx(Sr,{className:"h-3.5 w-3.5"}):y.jsx(Fn,{className:"h-3.5 w-3.5"})})}function Lq({isOpen:n,onClose:e,directory:t,filename:i,release:l,args:o,onFinished:a}){var ye,B;const[c,f]=E.useState(null),[d,m]=E.useState(!1),[g,b]=E.useState(null),[v,w]=E.useState(null),[S,C]=E.useState(!1),[O,_]=E.useState(0),M=E.useRef(null),P=E.useRef(!1),L=E.useRef(null),D=E.useRef(!1);E.useEffect(()=>{if(!n||!t||!i){f(null),b(null),C(!1),w(null),D.current=!1;return}let R=!0;return m(!0),b(null),C(!1),w(null),PM({directory:t,filename:i,release:l,args:o}).then(V=>{R&&(f(V),m(!1),(V.status==="completed"||V.status==="aborted"||V.status==="failed")&&(a==null||a(V.status,V.final_message||"")))}).catch(V=>{R&&((V==null?void 0:V.status)===404&&C(!0),b(V.message||"Failed to start workflow"),m(!1))}),()=>{R=!1}},[n,t,i,l,o,O]);const j=async R=>{if(!(!c||P.current)){P.current=!0,m(!0);try{const V=await HM(c.session_id,R);f(V),(V.status==="completed"||V.status==="aborted"||V.status==="failed")&&(a==null||a(V.status,V.final_message||""))}catch(V){(V==null?void 0:V.status)===404?(C(!0),b(V.message||"Workflow session on the server has expired.")):b(V.message||"Failed to process workflow response")}finally{P.current=!1,m(!1)}}},H=E.useRef(c);H.current=c;const Z=E.useRef(j);Z.current=j;const I=E.useRef(v);I.current=v;const F=E.useRef([]),A=(R,V)=>{var je,Ne;if(R.key!=="ArrowDown"&&R.key!=="ArrowUp"&&R.key!=="Home"&&R.key!=="End")return;R.preventDefault();const ue=((je=H.current)==null?void 0:je.steps.length)??0;if(ue===0)return;const pe=R.key==="ArrowDown"?(V+1)%ue:R.key==="ArrowUp"?(V-1+ue)%ue:R.key==="Home"?0:ue-1;w(pe),(Ne=F.current[pe])==null||Ne.focus()};E.useEffect(()=>()=>FC(H.current),[]);const ne=()=>{D.current||(D.current=!0,FC(H.current),e())},ae=()=>{f(null),b(null),C(!1),w(null),D.current=!1,_(R=>R+1)},ie=tl({isOpen:n,onClose:ne,dialogRef:M,initialFocusRef:L});if(E.useEffect(()=>{if(!n)return;const R=V=>{var Ee,jt,Ut;if(V.key==="Escape"){V.preventDefault(),ne();return}const ue=H.current;if(!ue)return;if(CE(ue.status)){V.key==="Enter"&&!V.repeat&&!V.ctrlKey&&!V.metaKey&&!V.altKey&&!P.current&&((Ee=V.target)==null?void 0:Ee.tagName)!=="BUTTON"&&((jt=document.activeElement)==null?void 0:jt.tagName)!=="BUTTON"&&(V.preventDefault(),ne());return}if(P.current||V.repeat||V.ctrlKey||V.metaKey||V.altKey)return;const pe=V.target;if((pe==null?void 0:pe.tagName)==="INPUT"||(pe==null?void 0:pe.tagName)==="TEXTAREA"||pe!=null&&pe.isContentEditable)return;const je=I.current,Ne=je===null||je===ue.current_index,Pe=ue.status==="waiting_ask"?"yes":ue.status==="waiting_notify"||ue.status==="waiting_notice"?"ack":null;if(!Ne||Pe===null)return;if(V.key==="Enter"){const Ft=V.target;if((Ft==null?void 0:Ft.tagName)==="BUTTON"||((Ut=document.activeElement)==null?void 0:Ut.tagName)==="BUTTON")return;V.preventDefault(),Z.current(Pe);return}if(ue.status!=="waiting_ask")return;const ve=V.key.toLowerCase();ve==="y"?(V.preventDefault(),Z.current("yes")):ve==="s"?(V.preventDefault(),Z.current("skip")):ve==="n"&&(V.preventDefault(),Z.current("no"))};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[n,e]),E.useEffect(()=>{if(!n||!c)return;const R=requestAnimationFrame(()=>{var V;return(V=L.current)==null?void 0:V.focus()});return()=>cancelAnimationFrame(R)},[n,c==null?void 0:c.status]),!n)return null;const $=v!==null?c==null?void 0:c.steps[v]:c==null?void 0:c.steps[c.current_index],oe=(c==null?void 0:c.status)==="completed"||(c==null?void 0:c.status)==="aborted"||(c==null?void 0:c.status)==="failed",J=!!c&&!oe&&!S&&(((ye=c.status)==null?void 0:ye.startsWith("waiting"))??!1),Y=(((B=c==null?void 0:c.steps[(c==null?void 0:c.current_index)??-1])==null?void 0:B.phase)??"pre")==="post",he=!S&&(v===null||v===(c==null?void 0:c.current_index))&&($!=null&&$.command)&&((c==null?void 0:c.status)==="waiting_notify"||(c==null?void 0:c.status)==="waiting_notice"||(c==null?void 0:c.status)==="waiting_ask")?y.jsxs("div",{className:"space-y-2",children:[y.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-ink-muted",children:"Command:"}),y.jsxs("div",{className:"relative rounded-lg border border-line bg-surface-strong p-4 pr-10 font-mono text-xs text-ink leading-relaxed",children:[y.jsx(Mh,{text:$.command}),$.command]})]}):null;return y.jsx("div",{ref:M,role:"dialog","aria-modal":"true","aria-labelledby":"workflow-runner-title",onKeyDown:ie,className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 p-4 backdrop-blur-xs",children:y.jsxs("div",{className:"animate-modal-in flex h-[80vh] w-full max-w-5xl flex-col rounded-xl border border-frame-line glass-panel overflow-hidden",children:[y.jsxs("div",{className:"flex items-center justify-between border-b border-line px-5 py-3.5 bg-surface-strong/30 shrink-0",children:[y.jsxs("div",{className:"flex items-center gap-2.5",children:[y.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-chip-indigo-bg text-chip-indigo-text",children:y.jsx(iO,{className:"h-4 w-4"})}),y.jsxs("div",{children:[y.jsx("h2",{id:"workflow-runner-title",className:"text-sm font-semibold text-ink",children:"Launch Workflow Engine"}),y.jsxs("p",{className:"text-xs text-ink-muted",children:[i," ",c!=null&&c.pattern?`• Pattern: ${c.pattern}`:""]})]})]}),y.jsxs("div",{className:"flex items-center gap-1.5",children:[c&&!oe&&!S&&y.jsxs("button",{type:"button",disabled:!J||d,onClick:()=>j("bypass"),title:Y?"Skip the remaining post-launch steps":"Skip the remaining steps and launch with the OS default app",className:"btn inline-flex items-center gap-1.5 rounded-md border border-line bg-surface px-3 py-1.5 text-xs font-medium text-status-warning-text hover:bg-status-warning-bg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 disabled:cursor-not-allowed disabled:opacity-40",children:[y.jsx(cD,{className:"h-3.5 w-3.5"}),Y?"Skip rest":"Launch now"]}),y.jsx("button",{type:"button",onClick:ne,className:"rounded-md p-1.5 text-ink-muted hover:bg-elevated hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500",children:y.jsx(ri,{className:"h-4 w-4"})})]})]}),y.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[y.jsxs("div",{className:"w-72 border-r border-line bg-surface-strong/20 p-4 overflow-y-auto flex flex-col gap-2 shrink-0",children:[y.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-ink-muted px-1 mb-1",children:"Workflow Steps (Click to inspect)"}),c&&c.steps.length>0?y.jsx("ul",{role:"list",className:"flex flex-col gap-2",children:c.steps.map((R,V)=>{const ue=c.current_index===V&&!oe,pe=v===V||v===null&&ue,je=_q[R.status];return y.jsx("li",{children:y.jsxs("button",{ref:Ne=>{F.current[V]=Ne},type:"button",tabIndex:pe?0:-1,"aria-current":pe?"step":void 0,onKeyDown:Ne=>A(Ne,V),onClick:()=>w(V),className:`flex items-start text-left gap-2.5 rounded-lg border px-3 py-2.5 transition-colors cursor-pointer w-full ${pe?"border-chip-indigo-border bg-chip-indigo-bg shadow-xs ring-1 ring-chip-indigo-border/40":"border-line/60 bg-surface/60 hover:bg-elevated/80"}`,children:[y.jsxs("div",{className:"mt-0.5 shrink-0",children:[R.status==="running"&&y.jsx(Yr,{className:"h-4 w-4 animate-spin text-chip-indigo-text"}),R.status==="completed"&&y.jsx(Uk,{className:"h-4 w-4 text-status-success-text"}),R.status==="skipped"&&y.jsx(E4,{className:"h-4 w-4 text-status-warning-text"}),R.status==="failed"&&y.jsx(Ec,{className:"h-4 w-4 text-status-danger-text"}),R.status==="pending"&&y.jsx("div",{className:"h-4 w-4 rounded-full border border-line-strong flex items-center justify-center text-[10px] text-ink-faint font-mono",children:R.index})]}),y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsxs("div",{className:"flex items-center justify-between",children:[y.jsx("span",{className:"font-mono text-[11px] font-bold uppercase text-chip-indigo-text",children:R.action}),y.jsxs("span",{className:"text-[10px] font-mono text-ink-faint",children:["#",R.index," · ",je]})]}),y.jsx("p",{className:"truncate font-mono text-[11px] text-ink-secondary mt-0.5",title:R.command,children:R.message?R.message.split(` `)[0]:R.command}),R.note&&y.jsx("p",{className:"mt-1 text-[10px] text-ink-faint italic",children:R.note})]})]})},R.index)})}):y.jsx("div",{className:"p-4 text-center text-xs text-ink-faint",children:g||S?"Session unavailable — see the error panel.":"Loading steps..."})]}),y.jsxs("div",{className:"flex-1 flex flex-col bg-app",children:[y.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-6",children:y.jsx("div",{className:"space-y-6",children:y.jsxs("div",{className:"rounded-xl border border-line bg-surface p-5 shadow-xs space-y-4",children:[y.jsxs("div",{className:"flex items-center justify-between border-b border-line pb-3",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"rounded bg-chip-indigo-bg px-2 py-0.5 font-mono text-xs font-semibold uppercase text-chip-indigo-text",children:($==null?void 0:$.action)||(c==null?void 0:c.status)}),y.jsx("span",{className:"text-xs text-ink-muted",children:$?`Step ${$.index} of ${c==null?void 0:c.steps.length}`:"Status"}),v!==null&&v!==(c==null?void 0:c.current_index)&&y.jsx("button",{type:"button",onClick:()=>w(null),className:"text-[11px] text-chip-indigo-text hover:underline ml-2",children:"(Return to active step)"})]}),d&&y.jsx(Yr,{className:"h-4 w-4 animate-spin text-chip-indigo-text"})]}),y.jsxs("div",{className:"space-y-3 text-xs text-ink font-sans leading-relaxed",children:[(v===null||v===(c==null?void 0:c.current_index))&&(c==null?void 0:c.status)==="waiting_notify"&&c.notify_message&&y.jsxs("div",{className:"space-y-2",children:[y.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-ink-muted",children:"Notification Message:"}),y.jsx("div",{className:"rounded-lg border border-line bg-surface-strong p-4 text-ink",children:y.jsx(Eh,{text:c.notify_message})}),he]}),(v===null||v===(c==null?void 0:c.current_index))&&(c==null?void 0:c.status)==="waiting_notice"&&c.notice_message&&y.jsxs("div",{className:"space-y-2",children:[y.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-ink-muted",children:"Notice:"}),y.jsx("div",{className:"rounded-lg border border-line bg-surface-strong p-4 text-ink",children:y.jsx(Eh,{text:c.notice_message})}),he,y.jsx("p",{className:"text-[11px] text-ink-faint",children:"The command will run when you continue."})]}),(v===null||v===(c==null?void 0:c.current_index))&&(c==null?void 0:c.status)==="waiting_ask"&&c.ask_prompt&&y.jsxs("div",{className:"space-y-2",children:[c.ask_message&&y.jsx("div",{className:"rounded-lg border border-line bg-surface-strong p-4 text-ink",children:y.jsx(Eh,{text:c.ask_message})}),y.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-status-warning-text",children:"Confirmation Prompt:"}),y.jsx("div",{className:"rounded-lg border border-status-warning-border bg-status-warning-bg p-4 text-sm font-medium text-ink",children:c.ask_prompt}),he]}),oe&&v===null&&y.jsxs("div",{className:`rounded-xl border p-8 text-center space-y-4 ${(c==null?void 0:c.status)==="completed"?"border-status-success-border bg-status-success-bg text-status-success-text":"border-status-danger-border bg-status-danger-bg text-status-danger-text"}`,children:[y.jsx("div",{className:"inline-flex h-12 w-12 items-center justify-center rounded-full bg-surface/50 mx-auto",children:(c==null?void 0:c.status)==="completed"?y.jsx(Uk,{className:"h-6 w-6 text-status-success-text"}):y.jsx(Ec,{className:"h-6 w-6 text-status-danger-text"})}),y.jsxs("div",{className:"space-y-1",children:[y.jsx("h3",{className:"text-base font-bold",children:(c==null?void 0:c.status)==="completed"?"Workflow Finished":"Workflow Terminated"}),y.jsx("p",{className:"text-xs text-ink-secondary max-w-md mx-auto",children:(c==null?void 0:c.final_message)||"The launch sequence has ended."})]}),y.jsx("div",{className:"pt-2",children:y.jsx("button",{type:"button",onClick:e,className:"btn btn-primary px-8 py-2.5 font-bold shadow-lg",children:"Close Engine Runner"})})]}),oe&&v===null&&(c==null?void 0:c.last_output)&&y.jsxs("div",{className:"space-y-2",children:[y.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-ink-muted",children:"Command Output:"}),y.jsxs("div",{className:"relative",children:[y.jsx(Mh,{text:c.last_output}),y.jsx("pre",{className:"max-h-48 overflow-y-auto whitespace-pre-wrap break-words rounded-lg border border-line bg-surface-strong p-4 font-mono text-xs text-ink",children:c.last_output})]})]}),!S&&!(oe&&v===null)&&!((v===null||v===(c==null?void 0:c.current_index))&&((c==null?void 0:c.status)==="waiting_notify"||(c==null?void 0:c.status)==="waiting_ask"||(c==null?void 0:c.status)==="waiting_notice"))&&y.jsxs("div",{className:"space-y-4",children:[($==null?void 0:$.message)&&y.jsxs("div",{className:"space-y-2",children:[y.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-ink-muted",children:"Message:"}),y.jsx("div",{className:"rounded-lg border border-line bg-surface-strong p-4 text-xs text-ink",children:y.jsx(Eh,{text:$.message})})]}),y.jsxs("div",{className:"space-y-2",children:[y.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-ink-muted",children:"Command:"}),y.jsx("div",{className:"relative rounded-lg border border-line bg-surface-strong p-4 font-mono text-xs text-ink leading-relaxed",children:$!=null&&$.command?y.jsxs(y.Fragment,{children:[y.jsx(Mh,{text:$.command}),y.jsx("span",{className:"block pr-8",children:$.command})]}):"Waiting..."})]}),($==null?void 0:$.output)&&y.jsxs("div",{className:"space-y-2",children:[y.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-ink-muted",children:"Output:"}),y.jsxs("div",{className:"relative",children:[y.jsx(Mh,{text:$.output}),y.jsx("pre",{className:"max-h-48 overflow-y-auto whitespace-pre-wrap break-words rounded-lg border border-line bg-surface-strong p-4 font-mono text-xs text-ink",children:$.output})]})]}),($==null?void 0:$.ask)&&y.jsxs("div",{className:"rounded-lg border border-status-warning-border bg-status-warning-bg p-3 text-xs text-status-warning-text",children:[y.jsx("span",{className:"font-semibold",children:"Workflow Guard:"})," ",$.ask]}),($==null?void 0:$.note)&&y.jsxs("div",{className:"rounded-lg border border-line bg-surface-strong p-3 text-xs text-ink-muted italic",children:[y.jsx("span",{className:"font-semibold text-ink-secondary not-italic uppercase text-[10px]",children:"Log:"})," ",$.note]})]})]})]})})}),(g||S)&&y.jsx("div",{className:"shrink-0 px-6 pt-3",children:y.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-status-danger-border bg-status-danger-bg p-3 text-xs text-status-danger-text",children:[y.jsx(Ec,{className:"mt-0.5 h-4 w-4 shrink-0"}),y.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5",children:[y.jsx("p",{children:S?"Workflow session on the server has expired or ended.":g}),S?y.jsxs("div",{className:"space-y-2",children:[g&&y.jsxs("details",{className:"text-ink-muted",children:[y.jsx("summary",{className:"cursor-pointer select-none text-[11px] underline",children:"Raw error (for bug reports)"}),y.jsx("pre",{className:"mt-1 overflow-x-auto whitespace-pre-wrap break-words font-mono text-[11px]",children:g})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("button",{type:"button",onClick:ae,className:"btn btn-primary px-4 py-1.5 text-xs font-semibold",children:"Restart workflow"}),y.jsx("button",{type:"button",onClick:ne,className:"btn rounded-md border-line bg-surface px-4 py-1.5 text-xs",children:"Close"})]})]}):null]})]})}),y.jsxs("div",{className:"shrink-0 px-6 pt-4 pb-4 border-t border-line flex items-center justify-between bg-app",children:[y.jsx("div",{className:"text-xs text-ink-muted","aria-live":"polite",children:S?"Session unavailable — restart or close above.":(c==null?void 0:c.status)==="waiting_ask"&&(v===null||v===c.current_index)?"Action required to proceed:":(c==null?void 0:c.status)==="waiting_notify"&&(v===null||v===c.current_index)?"Acknowledge message to proceed:":(c==null?void 0:c.status)==="waiting_notice"&&(v===null||v===c.current_index)?"Continue to run the command:":oe?"Session terminated.":"Step in progress..."}),y.jsxs("div",{className:"flex items-center gap-2",children:[!S&&(c==null?void 0:c.status)==="waiting_notice"&&(v===null||v===c.current_index)&&y.jsxs("button",{type:"button",ref:L,disabled:d,onClick:()=>j("ack"),className:"btn btn-primary px-5 py-2 font-semibold shadow-sm",children:["Run Command",y.jsx(Cc,{label:"↵"})]}),!S&&(c==null?void 0:c.status)==="waiting_notify"&&(v===null||v===c.current_index)&&y.jsxs("button",{type:"button",ref:L,disabled:d,onClick:()=>j("ack"),className:"btn btn-primary px-5 py-2 font-semibold shadow-sm",children:["Continue Workflow",y.jsx(Cc,{label:"↵"})]}),!S&&(c==null?void 0:c.status)==="waiting_ask"&&(v===null||v===c.current_index)&&y.jsxs(y.Fragment,{children:[y.jsxs("button",{type:"button",disabled:d,onClick:()=>j("no"),className:"btn rounded-md border-line bg-surface px-4 py-2 text-status-danger-text hover:bg-status-danger-bg",children:["Abort Launch",y.jsx(Cc,{label:"N"})]}),y.jsxs("button",{type:"button",disabled:d,onClick:()=>j("skip"),className:"btn rounded-md border-line bg-surface px-4 py-2 text-status-warning-text hover:bg-status-warning-bg",children:["Skip Step",y.jsx(Cc,{label:"S"})]}),y.jsxs("button",{type:"button",ref:L,disabled:d,onClick:()=>j("yes"),className:"btn btn-primary px-5 py-2 font-semibold shadow-sm",children:["Execute Step",y.jsx(Cc,{label:"Y"})]})]}),oe&&y.jsx("button",{type:"button",ref:L,onClick:e,className:"btn btn-primary px-5 py-2 font-semibold shadow-sm",children:"Close Runner"})]})]})]})]})]})})}function Oc(n){return/[",\n\r]/.test(n)?`"${n.replace(/"/g,'""')}"`:n}function zq(n,e,t,i){var f,d;const l=[],a=[["Exported",new Date().toISOString()],["App Version",(t==null?void 0:t.release)??"unknown"],["Config File",(t==null?void 0:t.config_path)??"none"],["Config Exists",String((t==null?void 0:t.config_exists)??!1)],["Directory",(t==null?void 0:t.active_directory)??""],["Extensions",((f=t==null?void 0:t.extensions)==null?void 0:f.join(" | "))??""],["Filter Text",i??((d=t==null?void 0:t.filters)==null?void 0:d[0])??""],["Recursive",String((t==null?void 0:t.recursive_search)??!0)],["Title",(t==null?void 0:t.title)??""],["Release",(t==null?void 0:t.release)??""]];for(const[m,g]of a)l.push(`${Oc(m)},${Oc(g)}`);l.push("");const c=e.length>0?e:["filename","path","rel_path"];l.push(c.map(Oc).join(","));for(const m of n){const g=c.map(b=>b in m?Oc(String(m[b]??"")):Oc(m.column_values[b]??""));l.push(g.join(","))}return l.join(`\r -`)}function Bq(n){const e=n.replace(/\\/g,"/"),t=e.startsWith("//"),i=Hq(e.replace(/^\/+/,""));return t?`file://${i}`:`file:///${i}`}const Pq=/[A-Za-z0-9\-._~!$&'()*+,;=:@]/;function Hq(n){return[...n].map(e=>e==="/"||Pq.test(e)?e:Iq(e)).join("")}function Iq(n){return Array.from(new TextEncoder().encode(n),e=>`%${e.toString(16).toUpperCase().padStart(2,"0")}`).join("")}const Uq=120;function Fq(){const{theme:n,applyTheme:e,toggleTheme:t}=GD(),[i,l]=E.useState(null),[o,a]=E.useState(null),[c,f]=E.useState(""),[d,m]=E.useState(""),[g,b]=E.useState(""),[v,w]=E.useState(!0),[S,C]=E.useState(null),[O,_]=E.useState(!1),[M,P]=E.useState(0),[L,D]=E.useState(""),[j,H]=E.useState(null),[Z,I]=E.useState(!1),{toastMessage:F,showToast:A,dismissToast:ne}=PD(),[ae,ie]=E.useState(!1),[$,oe]=E.useState("en"),[J,Y]=E.useState(!1),[T,he]=E.useState(!1),[ye,B]=E.useState(!1),[R,V]=E.useState(0),[ue,pe]=E.useState(!1),[je,Ne]=E.useState(null),[Pe,ve]=E.useState(null),[Ee,jt]=E.useState(!1),[Ut,Ft]=E.useState(!1),[zt,mt]=E.useState(!1),[$e,Xt]=E.useState(null),[Tn,en]=E.useState(!1),[tn,Ce]=E.useState(void 0),[Fe,Ve]=E.useState(null),[at,te]=E.useState(""),[fe,_e]=E.useState(!1),[ze,Dt]=E.useState(null),ce=K=>{mt(!0)},xe=E.useRef(null),Le=()=>({directory:c,extension:d,filter_text:g,recursive:v}),we=BD({showToast:A,getScanParams:Le,onFreshResults:()=>{xe.current=null,P(0)}}),{barcodeMode:pt,setBarcodeMode:An,handleBarcodeToggle:mn,handleCameraDetected:Tt}=XD({showToast:A,scanWith:we.scanWith,getScanParams:Le,onApplyValues:K=>{K.filter!==void 0&&b(K.filter),K.ext!==void 0&&m(K.ext),K.recursive!==void 0&&w(K.recursive),K.dir!==void 0&&f(K.dir)},onSingleMatch:Dt,onCameraClose:()=>_e(!1),setFilterText:b});E.useEffect(()=>{if(!g.trim()){D("");return}const K=window.setTimeout(()=>D(g),Uq);return()=>window.clearTimeout(K)},[g]);const ht=E.useMemo(()=>L.trim()===""?we.files:we.files.filter(K=>k8(K.rel_path,L)),[we.files,L]),Bi=g.trim()&&we.files.length{const K=xe.current,de=K?ht.findIndex(Oe=>Oe.path===K):-1;if(de>=0){P(Oe=>de!==Oe?de:Oe);return}P(Oe=>Math.min(Oe,Math.max(0,ht.length-1)))},[ht]);const Ln=async()=>{if(ae)return;ie(!0),A("Reloading configuration...");const K=we.beginScan();try{const de=await Qh();l(de);const Oe=await TM();a(Oe),e(Bg(Oe.theme),{persist:!1});const We=Oe.active_directory||c,$t=Oe.extensions[0]??"",Xn=Oe.filters[0]??"";We&&f(We),m($t),b(Xn),w(Oe.recursive_search),Oe.reloaded===!1?A(`Config file not found: ${Oe.config_path||"(unknown path)"} — kept current configuration.`,"error"):A("Configuration reloaded."),We&&await we.scanWithGeneration(K,{directory:We,extension:$t,filter_text:Xn,recursive:Oe.recursive_search},{errorPrefix:"Failed to reload configuration"})}catch(de){A(`Failed to reload configuration: ${de.message}`,"error")}finally{ie(!1),we.finishScan(K)}},Er=async K=>{const de=we.beginScan();a(K),e(Bg(K.theme),{persist:!1});const Oe=K.active_directory||c||(K.directories[0]??""),We=K.extensions[0]??"",$t=K.filters[0]??"";Oe&&f(Oe),m(We),b($t),w(K.recursive_search),K.session_trial||A(K.config_exists?`Loaded config: ${K.config_path}`:"Starter configuration created."),Oe?await we.scanWithGeneration(de,{directory:Oe,extension:We,filter_text:$t,recursive:K.recursive_search},{errorPrefix:"Scan failed after config load"}):we.finishScan(de)},{dropOverlayVisible:em,resetDrop:gu,applyConfigFile:tm}=ZD({onConfigLoaded:Er,showToast:A});ID({onConfigApplied:async()=>{const K=await Dk();await Er(K)},showToast:A});const nm=()=>{Y(!0)},Jl=async K=>{const de=we.beginScan();Y(!1),f(K),A(`Directory selected: ${K}`);let Oe;try{Oe=await jk(K),a(Oe)}catch(Xn){console.error("select-directory failed:",Xn)}if(!we.isCurrentScan(de))return;const We=Yf(d,Oe==null?void 0:Oe.extensions,d),$t=Yf(g,Oe==null?void 0:Oe.filters,g);m(We),b($t),await we.scanWithGeneration(de,{directory:K,extension:We,filter_text:$t,recursive:v},{errorPrefix:"Scan failed"})},zn=async(K,de)=>{if(!we.isCurrentScan(de))return;e(Bg(K.theme),{persist:!0}),a(K);const Oe=K.active_directory||(K.directories.length>0?K.directories[0]:""),We=K.extensions.length>0?K.extensions[0]:"",$t=K.filters.length>0?K.filters[0]:"";if(Oe&&f(Oe),We&&m(We),K.recursive_search!==void 0&&w(K.recursive_search),$t&&b($t),K.config_exists||he(!0),Oe)try{await we.runScan(de,{directory:Oe,extension:We,filter_text:$t,recursive:K.recursive_search})}catch(Xn){we.isCurrentScan(de)&&A(`Initial scan failed: ${Xn.message}`,"error")}},Pi=async()=>{const K=we.claimGeneration();C(null),_(!0);try{const de=await Qh();l(de);const Oe=await Dk();await zn(Oe,K)}catch(de){C((de==null?void 0:de.message)||"Couldn't fetch system info or configuration.")}finally{_(!1)}};E.useEffect(()=>{Pi()},[]);const on=async K=>{const de=we.beginScan();f(K);try{const Oe=await jk(K);if(!we.isCurrentScan(de))return!1;a(Oe);const We=Yf(d,Oe.extensions,""),$t=Yf(g,Oe.filters,"");return m(We),b($t),(await we.scanWithGeneration(de,{directory:K,extension:We,filter_text:$t,recursive:v},{errorPrefix:"Directory change failed"})).ok}catch(Oe){return we.isCurrentScan(de)&&A(`Directory change failed: ${Oe.message}`,"error"),!1}finally{we.finishScan(de)}},qs=async()=>{await we.scanWith({directory:c,extension:d,filter_text:g,recursive:v},{errorPrefix:"Scan failed"})},{autoRescanInterval:xu,handleTimerSet:im}=FD({scan:()=>{qs()},showToast:A}),Vs=K=>{b(K),we.scheduleDeferredRescan()},Qs=K=>{w(K),we.scheduleDeferredRescan()},Xs=K=>{m(K),we.scheduleDeferredRescan()},Mr=async()=>{b(""),await we.scanWith({directory:c,extension:d,filter_text:"",recursive:v},{errorPrefix:"Scan failed"})},$s=async()=>{w(!1),await we.scanWith({directory:c,extension:d,filter_text:g,recursive:!1},{errorPrefix:"Scan failed"})},vi=async(K,de)=>{if(K.has_hook){Xt({file:K,args:de});return}try{await jM({directory:c,filename:K.rel_path,release:o==null?void 0:o.release,args:de}),A(`Launched ${K.filename}`)}catch(Oe){A(`Launch error: ${Oe.message}`,"error")}},ka=()=>{ht.length>0&&ht[M]&&vi(ht[M])},rm=K=>{var de;xe.current=((de=ht[K])==null?void 0:de.path)??null,P(K)},yu=async(K,de)=>{vi(K,de)},Sa=async K=>{try{await XC(K.path),A("Revealed in file manager.")}catch(de){A(`Error: ${de.message}`,"error")}},es=async K=>{try{await _x(K.path),A("Folder opened in file manager.")}catch(de){A(`Error: ${de.message}`,"error")}},lm=async K=>{try{const de=await Pk(K.path);A(de.message||"Terminal opened.")}catch(de){A(`Error: ${de.message}`,"error")}},bu=async K=>{await on(K)&&A(`Scanned directory: ${K}`)},vu=K=>{b(K),we.scanWith({directory:c,extension:d,filter_text:K,recursive:v},{errorPrefix:"Scan failed"})},wu=K=>{m(K),we.scanWith({directory:c,extension:K,filter_text:g,recursive:v},{errorPrefix:"Scan failed"})},Ca=async(K,de)=>{const Oe=de?K.path.replace(/\\/g,"/"):K.path;try{await navigator.clipboard.writeText(Oe),A("Path copied to clipboard.")}catch(We){A(`Copy failed: ${(We==null?void 0:We.message)??We}`,"error")}},Oa=async(K,de)=>{let Oe=K.filename;if(de){const We=Oe.lastIndexOf(".");We!==-1&&(Oe=Oe.slice(0,We))}try{await navigator.clipboard.writeText(Oe),A("Filename copied to clipboard.")}catch(We){A(`Copy failed: ${(We==null?void 0:We.message)??We}`,"error")}},ku=async(K,de)=>{try{A(`Computing ${de.toUpperCase()}...`);const Oe=await Hk(K.path,de);await navigator.clipboard.writeText(Oe.hash),A(`${de.toUpperCase()} hash copied: ${Oe.hash.slice(0,12)}...`)}catch(Oe){A(`Hash computation failed: ${Oe.message}`,"error")}},Su=async K=>{try{const de=Bq(K.path);await navigator.clipboard.writeText(de),A("File URI copied to clipboard.")}catch(de){A(`URI copy failed: ${de.message}`,"error")}},wi=async(K,de,Oe)=>{A(`Computing ${de.toUpperCase()}...`);try{const $t=(await Hk(K.path,de)).hash.toLowerCase()===Oe.trim().toLowerCase();A($t?`✅ ${de.toUpperCase()} matches!`:`❌ ${de.toUpperCase()} mismatch`)}catch(We){A(`Verification failed: ${We.message}`,"error")}},nn=async(K,de)=>{let Oe;try{Oe=await navigator.clipboard.readText()}catch{te(""),Ve({file:K,algorithm:de});return}if(!Oe.trim()){A("Clipboard is empty — copy a hash first, then try again.");return}await wi(K,de,Oe)},pn=K=>{ve(K),pe(!0)},il=K=>{Ne(K)},Cu=async()=>{const K=je;if(Ne(null),!!K)try{if(A("Deleting file..."),!(await fetch("/api/actions/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file_path:K.path})})).ok)throw new Error("Failed to delete file");A("File deleted successfully."),qs()}catch(de){A(`Delete failed: ${de.message}`,"error")}},sm=K=>{Ce(K.path),en(!0)},Ou=async()=>{if(c)try{await _x(c),A("Directory opened in file manager.")}catch(K){A(`Error: ${K.message}`,"error")}},Nu=async K=>{if(K)try{await Pk(K),A("Terminal opened in directory.")}catch(de){A(`Error: ${de.message}`,"error")}},rl=async()=>{try{await on("~"),A("Directory set to home folder.")}catch(K){A(`Error: ${K.message}`,"error")}},Gs=async()=>{if(c)try{const K=await QC(c);K.parent_path?(await on(K.parent_path),A("Moved to parent directory.")):A("Already at root directory.")}catch(K){A(`Error: ${K.message}`,"error")}},Ys=async()=>{if(we.files.length===0){A("No files to export.");return}try{const K=zq(we.files,(o==null?void 0:o.column_names)||[],o??void 0,g),de=`profiles-export-${new Date().toISOString().slice(0,19).replace(/[:.]/g,"-")}.csv`,Oe=await zM(K,de);A(`Exported ${we.files.length} loaded row${we.files.length===1?"":"s"}${g?` matching "${g}"`:""} — ${Oe.message}`)}catch(K){A(`Export failed: ${K.message}`,"error")}};return UD({anyModalOpen:!!(j||Z||J||T||ue||Ee||Ut||Tn||fe||ze||$e||je),visibleFiles:ht,selectedIndex:M,activeDirectory:c,activeExtension:d,filterText:g,recursive:v,barcodeMode:pt,onEscape:()=>{H(null),I(!1),jt(!1),Ft(!1),gu()},onContextMenu:H,onExecute:ka,onScan:qs,onReloadConfig:Ln,onGoHome:rl,onProperties:pn,onToggleTheme:()=>t({persist:!0}),setShowLogViewer:jt,setShowShortcuts:I,setShowTimerModal:Ft,setShowConfigEditor:B,setShowLanModal:mt,setBarcodeMode:An,setShowCameraScanner:_e,moveSelection:K=>{P(de=>{var We;const Oe=K(de,ht.length);return xe.current=((We=ht[Oe])==null?void 0:We.path)??null,Oe})}}),y.jsxs("div",{className:"flex h-dvh flex-col bg-elevated/30 p-1 font-sans text-ink transition-colors duration-200 sm:p-1.5",children:[y.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border border-frame-line bg-app shadow-[0_2px_6px_rgb(0_0_0/0.35)] transition-colors duration-200 sm:rounded-xl",children:[y.jsx(m8,{title:(o==null?void 0:o.title)||"",release:(o==null?void 0:o.release)||"",directories:(o==null?void 0:o.directories)||[],activeDirectory:c,onDirectoryChange:on,onBrowseDirectory:nm,onGoToParentDirectory:Gs,onGoToHomeDirectory:rl,onOpenActiveDirectory:Ou,onOpenTerminal:Nu}),y.jsx(C8,{extensions:(o==null?void 0:o.extensions)||[],activeExtension:d,onExtensionChange:Xs,filterOptions:(o==null?void 0:o.filters)||[],filterText:g,onFilterTextChange:Vs,recursive:v,onRecursiveChange:Qs,onScan:qs,scanning:we.scanning,barcodeMode:pt,onBarcodeToggle:mn,onCameraBarcodeClick:()=>_e(!0),autoRescanActive:xu>0,onTimerClick:()=>Ft(!0)}),S?y.jsx(p8,{message:S,onRetry:()=>void Pi(),retrying:O}):y.jsx(LD,{files:ht,totalCount:we.totalCount,rawLoadedCount:we.files.length,onLoadMore:we.handleLoadMore,loadingMore:we.loadingMore,scanning:we.scanning,hasScanned:we.hasScanned,activeDirectory:c,recursive:v,onDisableRecursive:$s,onOpenDirectory:Ou,onLoadConfig:()=>he(!0),filterText:g,onClearFilter:Mr,columnHeaders:(o==null?void 0:o.column_headers)||[],columnNames:(o==null?void 0:o.column_names)||[],selectedIndex:M,onSelectIndex:rm,prefilterNote:Bi,onLaunch:vi,onContextMenu:(K,de,Oe)=>{K.preventDefault(),xe.current=de.path,P(Oe),H({x:K.clientX,y:K.clientY,file:de})},rowColors:(o==null?void 0:o.row_colors)||[],sort:we.sort,onSortChange:we.applySort}),y.jsx(nj,{onExecute:ka,scanning:we.scanning,scanningDirectory:c,hasSelection:ht.length>0,fileCount:ht.length,totalCount:we.totalCount,toastMessage:F,onToastDismiss:ne}),y.jsx(Q8,{systemInfo:i,fileCount:we.totalCount,theme:n,onToggleTheme:()=>t({persist:!0}),onOpenLog:()=>jt(!0),onOpenConfig:()=>B(!0),onShowShortcuts:()=>I(!0),onReloadConfig:Ln,onExport:Ys,exportDisabled:we.files.length===0||we.scanning,language:$,onLanguageChange:oe,lanEnabled:(i==null?void 0:i.lan_enabled)??null,onToggleLan:ce})]}),y.jsx(c8,{open:ye,onClose:()=>B(!1),onApplied:Er,onLoadConfig:()=>he(!0),reloadKey:R}),y.jsx(M8,{isOpen:T,activeConfigPath:o==null?void 0:o.config_path,configExists:o==null?void 0:o.config_exists,onClose:()=>he(!1),onLoaded:K=>{Er(K),V(de=>de+1)}}),y.jsx(h8,{visible:em,onFileSelected:tm}),y.jsx(f8,{isOpen:J,initialPath:c,onClose:()=>Y(!1),onSelect:Jl}),y.jsx(u8,{position:j,onClose:()=>H(null),onLaunch:vi,onLaunchWithArgs:yu,onReveal:Sa,onOpenFolder:es,onOpenTerminal:lm,onScanDirectory:bu,onFilterFolder:vu,onFilterExtension:wu,onCopyPath:Ca,onCopyFilename:Oa,onCopyUri:Su,onComputeHash:ku,onVerifyHash:nn,onProperties:pn,onClearFile:il,onGenerateBarcode:sm,showToast:A}),y.jsx(E8,{isOpen:Z,onClose:()=>I(!1)}),y.jsx(L8,{isOpen:ue,file:Pe,onLaunch:vi,onClose:()=>{pe(!1),ve(null)}}),y.jsx($8,{isOpen:Ut,currentInterval:xu,onClose:()=>Ft(!1),onSetInterval:im}),y.jsx(A8,{isOpen:Ee,onClose:()=>jt(!1),onOpenExternally:()=>{kM().then(K=>A(K.message)).catch(K=>A(K instanceof Error?K.message:"Failed to open the log file","error"))}}),y.jsx(Lq,{isOpen:!!$e,onClose:()=>Xt(null),directory:c,filename:($e==null?void 0:$e.file.rel_path)||"",release:o==null?void 0:o.release,args:$e==null?void 0:$e.args,onFinished:(K,de)=>{K==="completed"?A(de||"Workflow launched successfully."):(K==="aborted"||K==="failed")&&A(`Workflow stopped: ${de}`,"error")}}),y.jsx(dA,{isOpen:Tn,onClose:()=>{en(!1),Ce(void 0)},initialFilePath:tn}),Fe&&y.jsx("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm",onClick:()=>Ve(null),children:y.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"verify-hash-title",onKeyDown:K=>{K.key==="Escape"&&(K.preventDefault(),K.stopPropagation(),Ve(null))},onClick:K=>K.stopPropagation(),className:"animate-modal-in w-[440px] max-w-full rounded-2xl border border-frame-line glass-panel p-5",children:[y.jsxs("h2",{id:"verify-hash-title",className:"mb-1 text-sm font-semibold text-ink",children:["Verify ",Fe.algorithm.toUpperCase()]}),y.jsx("p",{className:"mb-3 text-xs text-ink-muted",children:"Clipboard access is unavailable here — paste the expected hash below."}),y.jsx("input",{autoFocus:!0,type:"text",value:at,onChange:K=>te(K.target.value),placeholder:"Expected hash","aria-label":"Expected hash",className:"mb-4 w-full rounded-lg border border-line bg-elevated px-3 py-2 font-mono text-xs text-ink placeholder:text-ink-faint focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400"}),y.jsxs("div",{className:"flex justify-end gap-2",children:[y.jsx("button",{type:"button",onClick:()=>Ve(null),className:"min-h-9 rounded-lg border border-line bg-elevated px-3.5 text-sm text-ink-secondary transition-colors hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:"Cancel"}),y.jsx("button",{type:"button",disabled:!at.trim(),onClick:()=>{const{file:K,algorithm:de}=Fe;Ve(null),wi(K,de,at)},className:"min-h-9 rounded-lg border border-transparent bg-indigo-600 px-4 text-sm font-semibold text-white transition-colors hover:bg-indigo-500 disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:"Verify"})]})]})}),y.jsx(q8,{isOpen:fe,onClose:()=>_e(!1),onDetected:Tt}),y.jsx(Wo,{isOpen:!!je,title:"Delete file",message:`Delete this file? +`)}function Bq(n){const e=n.replace(/\\/g,"/"),t=e.startsWith("//"),i=Hq(e.replace(/^\/+/,""));return t?`file://${i}`:`file:///${i}`}const Pq=/[A-Za-z0-9\-._~!$&'()*+,;=:@]/;function Hq(n){return[...n].map(e=>e==="/"||Pq.test(e)?e:Iq(e)).join("")}function Iq(n){return Array.from(new TextEncoder().encode(n),e=>`%${e.toString(16).toUpperCase().padStart(2,"0")}`).join("")}const Uq=120;function Fq(){const{theme:n,applyTheme:e,toggleTheme:t}=GD(),[i,l]=E.useState(null),[o,a]=E.useState(null),[c,f]=E.useState(""),[d,m]=E.useState(""),[g,b]=E.useState(""),[v,w]=E.useState(!0),[S,C]=E.useState(null),[O,_]=E.useState(!1),[M,P]=E.useState(0),[L,D]=E.useState(""),[j,H]=E.useState(null),[Z,I]=E.useState(!1),{toastMessage:F,showToast:A,dismissToast:ne}=PD(),[ae,ie]=E.useState(!1),[$,oe]=E.useState("en"),[J,Y]=E.useState(!1),[T,he]=E.useState(null),[ye,B]=E.useState(!1),[R,V]=E.useState(0),[ue,pe]=E.useState(!1),[je,Ne]=E.useState(null),[Pe,ve]=E.useState(null),[Ee,jt]=E.useState(!1),[Ut,Ft]=E.useState(!1),[zt,mt]=E.useState(!1),[$e,Xt]=E.useState(null),[Tn,en]=E.useState(!1),[tn,Ce]=E.useState(void 0),[Fe,Ve]=E.useState(null),[at,te]=E.useState(""),[fe,_e]=E.useState(!1),[ze,Dt]=E.useState(null),ce=K=>{mt(!0)},xe=E.useRef(null),Le=()=>({directory:c,extension:d,filter_text:g,recursive:v}),we=BD({showToast:A,getScanParams:Le,onFreshResults:()=>{xe.current=null,P(0)}}),{barcodeMode:pt,setBarcodeMode:An,handleBarcodeToggle:mn,handleCameraDetected:Tt}=XD({showToast:A,scanWith:we.scanWith,getScanParams:Le,onApplyValues:K=>{K.filter!==void 0&&b(K.filter),K.ext!==void 0&&m(K.ext),K.recursive!==void 0&&w(K.recursive),K.dir!==void 0&&f(K.dir)},onSingleMatch:Dt,onCameraClose:()=>_e(!1),setFilterText:b});E.useEffect(()=>{if(!g.trim()){D("");return}const K=window.setTimeout(()=>D(g),Uq);return()=>window.clearTimeout(K)},[g]);const ht=E.useMemo(()=>L.trim()===""?we.files:we.files.filter(K=>k8(K.rel_path,L)),[we.files,L]),Bi=g.trim()&&we.files.length{const K=xe.current,de=K?ht.findIndex(Oe=>Oe.path===K):-1;if(de>=0){P(Oe=>de!==Oe?de:Oe);return}P(Oe=>Math.min(Oe,Math.max(0,ht.length-1)))},[ht]);const Ln=async()=>{if(ae)return;ie(!0),A("Reloading configuration...");const K=we.beginScan();try{const de=await Qh();l(de);const Oe=await TM();a(Oe),e(Bg(Oe.theme),{persist:!1});const We=Oe.active_directory||c,$t=Oe.extensions[0]??"",Xn=Oe.filters[0]??"";We&&f(We),m($t),b(Xn),w(Oe.recursive_search),Oe.reloaded===!1?A(`Config file not found: ${Oe.config_path||"(unknown path)"} — kept current configuration.`,"error"):A("Configuration reloaded."),We&&await we.scanWithGeneration(K,{directory:We,extension:$t,filter_text:Xn,recursive:Oe.recursive_search},{errorPrefix:"Failed to reload configuration"})}catch(de){A(`Failed to reload configuration: ${de.message}`,"error")}finally{ie(!1),we.finishScan(K)}},Er=async K=>{const de=we.beginScan();a(K),e(Bg(K.theme),{persist:!1});const Oe=K.active_directory||c||(K.directories[0]??""),We=K.extensions[0]??"",$t=K.filters[0]??"";Oe&&f(Oe),m(We),b($t),w(K.recursive_search),K.session_trial||A(K.config_exists?`Loaded config: ${K.config_path}`:"Starter configuration created."),Oe?await we.scanWithGeneration(de,{directory:Oe,extension:We,filter_text:$t,recursive:K.recursive_search},{errorPrefix:"Scan failed after config load"}):we.finishScan(de)},{dropOverlayVisible:em,resetDrop:gu,applyConfigFile:tm}=ZD({onConfigLoaded:Er,showToast:A});ID({onConfigApplied:async()=>{const K=await Dk();await Er(K)},showToast:A});const nm=()=>{Y(!0)},Jl=async K=>{const de=we.beginScan();Y(!1),f(K),A(`Directory selected: ${K}`);let Oe;try{Oe=await jk(K),a(Oe)}catch(Xn){console.error("select-directory failed:",Xn)}if(!we.isCurrentScan(de))return;const We=Yf(d,Oe==null?void 0:Oe.extensions,d),$t=Yf(g,Oe==null?void 0:Oe.filters,g);m(We),b($t),await we.scanWithGeneration(de,{directory:K,extension:We,filter_text:$t,recursive:v},{errorPrefix:"Scan failed"})},zn=async(K,de)=>{if(!we.isCurrentScan(de))return;e(Bg(K.theme),{persist:!0}),a(K);const Oe=K.active_directory||(K.directories.length>0?K.directories[0]:""),We=K.extensions.length>0?K.extensions[0]:"",$t=K.filters.length>0?K.filters[0]:"";if(Oe&&f(Oe),We&&m(We),K.recursive_search!==void 0&&w(K.recursive_search),$t&&b($t),K.config_exists||he("create"),Oe)try{await we.runScan(de,{directory:Oe,extension:We,filter_text:$t,recursive:K.recursive_search})}catch(Xn){we.isCurrentScan(de)&&A(`Initial scan failed: ${Xn.message}`,"error")}},Pi=async()=>{const K=we.claimGeneration();C(null),_(!0);try{const de=await Qh();l(de);const Oe=await Dk();await zn(Oe,K)}catch(de){C((de==null?void 0:de.message)||"Couldn't fetch system info or configuration.")}finally{_(!1)}};E.useEffect(()=>{Pi()},[]);const on=async K=>{const de=we.beginScan();f(K);try{const Oe=await jk(K);if(!we.isCurrentScan(de))return!1;a(Oe);const We=Yf(d,Oe.extensions,""),$t=Yf(g,Oe.filters,"");return m(We),b($t),(await we.scanWithGeneration(de,{directory:K,extension:We,filter_text:$t,recursive:v},{errorPrefix:"Directory change failed"})).ok}catch(Oe){return we.isCurrentScan(de)&&A(`Directory change failed: ${Oe.message}`,"error"),!1}finally{we.finishScan(de)}},qs=async()=>{await we.scanWith({directory:c,extension:d,filter_text:g,recursive:v},{errorPrefix:"Scan failed"})},{autoRescanInterval:xu,handleTimerSet:im}=FD({scan:()=>{qs()},showToast:A}),Vs=K=>{b(K),we.scheduleDeferredRescan()},Qs=K=>{w(K),we.scheduleDeferredRescan()},Xs=K=>{m(K),we.scheduleDeferredRescan()},Mr=async()=>{b(""),await we.scanWith({directory:c,extension:d,filter_text:"",recursive:v},{errorPrefix:"Scan failed"})},$s=async()=>{w(!1),await we.scanWith({directory:c,extension:d,filter_text:g,recursive:!1},{errorPrefix:"Scan failed"})},vi=async(K,de)=>{if(K.has_hook){Xt({file:K,args:de});return}try{await jM({directory:c,filename:K.rel_path,release:o==null?void 0:o.release,args:de}),A(`Launched ${K.filename}`)}catch(Oe){A(`Launch error: ${Oe.message}`,"error")}},ka=()=>{ht.length>0&&ht[M]&&vi(ht[M])},rm=K=>{var de;xe.current=((de=ht[K])==null?void 0:de.path)??null,P(K)},yu=async(K,de)=>{vi(K,de)},Sa=async K=>{try{await XC(K.path),A("Revealed in file manager.")}catch(de){A(`Error: ${de.message}`,"error")}},es=async K=>{try{await _x(K.path),A("Folder opened in file manager.")}catch(de){A(`Error: ${de.message}`,"error")}},lm=async K=>{try{const de=await Pk(K.path);A(de.message||"Terminal opened.")}catch(de){A(`Error: ${de.message}`,"error")}},bu=async K=>{await on(K)&&A(`Scanned directory: ${K}`)},vu=K=>{b(K),we.scanWith({directory:c,extension:d,filter_text:K,recursive:v},{errorPrefix:"Scan failed"})},wu=K=>{m(K),we.scanWith({directory:c,extension:K,filter_text:g,recursive:v},{errorPrefix:"Scan failed"})},Ca=async(K,de)=>{const Oe=de?K.path.replace(/\\/g,"/"):K.path;try{await navigator.clipboard.writeText(Oe),A("Path copied to clipboard.")}catch(We){A(`Copy failed: ${(We==null?void 0:We.message)??We}`,"error")}},Oa=async(K,de)=>{let Oe=K.filename;if(de){const We=Oe.lastIndexOf(".");We!==-1&&(Oe=Oe.slice(0,We))}try{await navigator.clipboard.writeText(Oe),A("Filename copied to clipboard.")}catch(We){A(`Copy failed: ${(We==null?void 0:We.message)??We}`,"error")}},ku=async(K,de)=>{try{A(`Computing ${de.toUpperCase()}...`);const Oe=await Hk(K.path,de);await navigator.clipboard.writeText(Oe.hash),A(`${de.toUpperCase()} hash copied: ${Oe.hash.slice(0,12)}...`)}catch(Oe){A(`Hash computation failed: ${Oe.message}`,"error")}},Su=async K=>{try{const de=Bq(K.path);await navigator.clipboard.writeText(de),A("File URI copied to clipboard.")}catch(de){A(`URI copy failed: ${de.message}`,"error")}},wi=async(K,de,Oe)=>{A(`Computing ${de.toUpperCase()}...`);try{const $t=(await Hk(K.path,de)).hash.toLowerCase()===Oe.trim().toLowerCase();A($t?`✅ ${de.toUpperCase()} matches!`:`❌ ${de.toUpperCase()} mismatch`)}catch(We){A(`Verification failed: ${We.message}`,"error")}},nn=async(K,de)=>{let Oe;try{Oe=await navigator.clipboard.readText()}catch{te(""),Ve({file:K,algorithm:de});return}if(!Oe.trim()){A("Clipboard is empty — copy a hash first, then try again.");return}await wi(K,de,Oe)},pn=K=>{ve(K),pe(!0)},il=K=>{Ne(K)},Cu=async()=>{const K=je;if(Ne(null),!!K)try{if(A("Deleting file..."),!(await fetch("/api/actions/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file_path:K.path})})).ok)throw new Error("Failed to delete file");A("File deleted successfully."),qs()}catch(de){A(`Delete failed: ${de.message}`,"error")}},sm=K=>{Ce(K.path),en(!0)},Ou=async()=>{if(c)try{await _x(c),A("Directory opened in file manager.")}catch(K){A(`Error: ${K.message}`,"error")}},Nu=async K=>{if(K)try{await Pk(K),A("Terminal opened in directory.")}catch(de){A(`Error: ${de.message}`,"error")}},rl=async()=>{try{await on("~"),A("Directory set to home folder.")}catch(K){A(`Error: ${K.message}`,"error")}},Gs=async()=>{if(c)try{const K=await QC(c);K.parent_path?(await on(K.parent_path),A("Moved to parent directory.")):A("Already at root directory.")}catch(K){A(`Error: ${K.message}`,"error")}},Ys=async()=>{if(we.files.length===0){A("No files to export.");return}try{const K=zq(we.files,(o==null?void 0:o.column_names)||[],o??void 0,g),de=`profiles-export-${new Date().toISOString().slice(0,19).replace(/[:.]/g,"-")}.csv`,Oe=await zM(K,de);A(`Exported ${we.files.length} loaded row${we.files.length===1?"":"s"}${g?` matching "${g}"`:""} — ${Oe.message}`)}catch(K){A(`Export failed: ${K.message}`,"error")}};return UD({anyModalOpen:!!(j||Z||J||T!==null||ue||Ee||Ut||Tn||fe||ze||$e||je),visibleFiles:ht,selectedIndex:M,activeDirectory:c,activeExtension:d,filterText:g,recursive:v,barcodeMode:pt,onEscape:()=>{H(null),I(!1),jt(!1),Ft(!1),gu()},onContextMenu:H,onExecute:ka,onScan:qs,onReloadConfig:Ln,onGoHome:rl,onProperties:pn,onToggleTheme:()=>t({persist:!0}),setShowLogViewer:jt,setShowShortcuts:I,setShowTimerModal:Ft,setShowConfigEditor:B,setShowLanModal:mt,setBarcodeMode:An,setShowCameraScanner:_e,moveSelection:K=>{P(de=>{var We;const Oe=K(de,ht.length);return xe.current=((We=ht[Oe])==null?void 0:We.path)??null,Oe})}}),y.jsxs("div",{className:"flex h-dvh flex-col bg-elevated/30 p-1 font-sans text-ink transition-colors duration-200 sm:p-1.5",children:[y.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border border-frame-line bg-app shadow-[0_2px_6px_rgb(0_0_0/0.35)] transition-colors duration-200 sm:rounded-xl",children:[y.jsx(m8,{title:(o==null?void 0:o.title)||"",release:(o==null?void 0:o.release)||"",directories:(o==null?void 0:o.directories)||[],activeDirectory:c,onDirectoryChange:on,onBrowseDirectory:nm,onGoToParentDirectory:Gs,onGoToHomeDirectory:rl,onOpenActiveDirectory:Ou,onOpenTerminal:Nu}),y.jsx(C8,{extensions:(o==null?void 0:o.extensions)||[],activeExtension:d,onExtensionChange:Xs,filterOptions:(o==null?void 0:o.filters)||[],filterText:g,onFilterTextChange:Vs,recursive:v,onRecursiveChange:Qs,onScan:qs,scanning:we.scanning,barcodeMode:pt,onBarcodeToggle:mn,onCameraBarcodeClick:()=>_e(!0),autoRescanActive:xu>0,onTimerClick:()=>Ft(!0)}),S?y.jsx(p8,{message:S,onRetry:()=>void Pi(),retrying:O}):y.jsx(LD,{files:ht,totalCount:we.totalCount,rawLoadedCount:we.files.length,onLoadMore:we.handleLoadMore,loadingMore:we.loadingMore,scanning:we.scanning,hasScanned:we.hasScanned,activeDirectory:c,recursive:v,onDisableRecursive:$s,onOpenDirectory:Ou,onLoadConfig:()=>he("load"),filterText:g,onClearFilter:Mr,columnHeaders:(o==null?void 0:o.column_headers)||[],columnNames:(o==null?void 0:o.column_names)||[],selectedIndex:M,onSelectIndex:rm,prefilterNote:Bi,onLaunch:vi,onContextMenu:(K,de,Oe)=>{K.preventDefault(),xe.current=de.path,P(Oe),H({x:K.clientX,y:K.clientY,file:de})},rowColors:(o==null?void 0:o.row_colors)||[],sort:we.sort,onSortChange:we.applySort}),y.jsx(nj,{onExecute:ka,scanning:we.scanning,scanningDirectory:c,hasSelection:ht.length>0,fileCount:ht.length,totalCount:we.totalCount,toastMessage:F,onToastDismiss:ne}),y.jsx(Q8,{systemInfo:i,fileCount:we.totalCount,theme:n,onToggleTheme:()=>t({persist:!0}),onOpenLog:()=>jt(!0),onOpenConfig:()=>B(!0),onShowShortcuts:()=>I(!0),onReloadConfig:Ln,onExport:Ys,exportDisabled:we.files.length===0||we.scanning,language:$,onLanguageChange:oe,lanEnabled:(i==null?void 0:i.lan_enabled)??null,onToggleLan:ce})]}),y.jsx(c8,{open:ye,onClose:()=>B(!1),onApplied:Er,onLoadConfig:()=>he("load"),reloadKey:R}),y.jsx(M8,{isOpen:T!==null,mode:T??"load",activeConfigPath:o==null?void 0:o.config_path,onClose:()=>he(null),onLoaded:K=>{Er(K),V(de=>de+1)}}),y.jsx(h8,{visible:em,onFileSelected:tm}),y.jsx(f8,{isOpen:J,initialPath:c,onClose:()=>Y(!1),onSelect:Jl}),y.jsx(u8,{position:j,onClose:()=>H(null),onLaunch:vi,onLaunchWithArgs:yu,onReveal:Sa,onOpenFolder:es,onOpenTerminal:lm,onScanDirectory:bu,onFilterFolder:vu,onFilterExtension:wu,onCopyPath:Ca,onCopyFilename:Oa,onCopyUri:Su,onComputeHash:ku,onVerifyHash:nn,onProperties:pn,onClearFile:il,onGenerateBarcode:sm,showToast:A}),y.jsx(E8,{isOpen:Z,onClose:()=>I(!1)}),y.jsx(L8,{isOpen:ue,file:Pe,onLaunch:vi,onClose:()=>{pe(!1),ve(null)}}),y.jsx($8,{isOpen:Ut,currentInterval:xu,onClose:()=>Ft(!1),onSetInterval:im}),y.jsx(A8,{isOpen:Ee,onClose:()=>jt(!1),onOpenExternally:()=>{kM().then(K=>A(K.message)).catch(K=>A(K instanceof Error?K.message:"Failed to open the log file","error"))}}),y.jsx(Lq,{isOpen:!!$e,onClose:()=>Xt(null),directory:c,filename:($e==null?void 0:$e.file.rel_path)||"",release:o==null?void 0:o.release,args:$e==null?void 0:$e.args,onFinished:(K,de)=>{K==="completed"?A(de||"Workflow launched successfully."):(K==="aborted"||K==="failed")&&A(`Workflow stopped: ${de}`,"error")}}),y.jsx(dA,{isOpen:Tn,onClose:()=>{en(!1),Ce(void 0)},initialFilePath:tn}),Fe&&y.jsx("div",{className:"animate-overlay-in fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm",onClick:()=>Ve(null),children:y.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"verify-hash-title",onKeyDown:K=>{K.key==="Escape"&&(K.preventDefault(),K.stopPropagation(),Ve(null))},onClick:K=>K.stopPropagation(),className:"animate-modal-in w-[440px] max-w-full rounded-2xl border border-frame-line glass-panel p-5",children:[y.jsxs("h2",{id:"verify-hash-title",className:"mb-1 text-sm font-semibold text-ink",children:["Verify ",Fe.algorithm.toUpperCase()]}),y.jsx("p",{className:"mb-3 text-xs text-ink-muted",children:"Clipboard access is unavailable here — paste the expected hash below."}),y.jsx("input",{autoFocus:!0,type:"text",value:at,onChange:K=>te(K.target.value),placeholder:"Expected hash","aria-label":"Expected hash",className:"mb-4 w-full rounded-lg border border-line bg-elevated px-3 py-2 font-mono text-xs text-ink placeholder:text-ink-faint focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400"}),y.jsxs("div",{className:"flex justify-end gap-2",children:[y.jsx("button",{type:"button",onClick:()=>Ve(null),className:"min-h-9 rounded-lg border border-line bg-elevated px-3.5 text-sm text-ink-secondary transition-colors hover:bg-surface-strong hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:"Cancel"}),y.jsx("button",{type:"button",disabled:!at.trim(),onClick:()=>{const{file:K,algorithm:de}=Fe;Ve(null),wi(K,de,at)},className:"min-h-9 rounded-lg border border-transparent bg-indigo-600 px-4 text-sm font-semibold text-white transition-colors hover:bg-indigo-500 disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:"Verify"})]})]})}),y.jsx(q8,{isOpen:fe,onClose:()=>_e(!1),onDetected:Tt}),y.jsx(Wo,{isOpen:!!je,title:"Delete file",message:`Delete this file? ${(je==null?void 0:je.path)??""} diff --git a/src/profiles/web/dist/index.html b/src/profiles/web/dist/index.html index 03b6d7c..853048a 100644 --- a/src/profiles/web/dist/index.html +++ b/src/profiles/web/dist/index.html @@ -5,7 +5,7 @@ ProFiles - + diff --git a/src/profiles/web/dist/sw.js b/src/profiles/web/dist/sw.js index 2b6d202..d0ae469 100644 --- a/src/profiles/web/dist/sw.js +++ b/src/profiles/web/dist/sw.js @@ -1 +1 @@ -if(!self.define){let e,s={};const i=(i,n)=>(i=new URL(i+".js",n).href,s[i]||new Promise(s=>{if("document"in self){const e=document.createElement("script");e.src=i,e.onload=s,document.head.appendChild(e)}else e=i,importScripts(i),s()}).then(()=>{let e=s[i];if(!e)throw new Error(`Module ${i} didn’t register its module`);return e}));self.define=(n,r)=>{const t=e||("document"in self?document.currentScript.src:"")||location.href;if(s[t])return;let o={};const d=e=>i(e,t),l={module:{uri:t},exports:o,require:d};s[t]=Promise.all(n.map(e=>l[e]||d(e))).then(e=>(r(...e),o))}}define(["./workbox-9c191d2f"],function(e){"use strict";self.skipWaiting(),e.clientsClaim(),e.precacheAndRoute([{url:"registerSW.js",revision:"1872c500de691dce40960bb85481de07"},{url:"index.html",revision:"55fcdf5c43b6ba8ea01b44d84bd93537"},{url:"assets/index-Dsvw1NQU.js",revision:null},{url:"assets/index-DTCv5-8y.css",revision:null},{url:"manifest.webmanifest",revision:"5a42ebe8b55b07b5831cbbddda834829"}],{}),e.cleanupOutdatedCaches(),e.registerRoute(new e.NavigationRoute(e.createHandlerBoundToURL("index.html")))}); +if(!self.define){let e,i={};const s=(s,n)=>(s=new URL(s+".js",n).href,i[s]||new Promise(i=>{if("document"in self){const e=document.createElement("script");e.src=s,e.onload=i,document.head.appendChild(e)}else e=s,importScripts(s),i()}).then(()=>{let e=i[s];if(!e)throw new Error(`Module ${s} didn’t register its module`);return e}));self.define=(n,r)=>{const t=e||("document"in self?document.currentScript.src:"")||location.href;if(i[t])return;let o={};const l=e=>s(e,t),d={module:{uri:t},exports:o,require:l};i[t]=Promise.all(n.map(e=>d[e]||l(e))).then(e=>(r(...e),o))}}define(["./workbox-9c191d2f"],function(e){"use strict";self.skipWaiting(),e.clientsClaim(),e.precacheAndRoute([{url:"registerSW.js",revision:"1872c500de691dce40960bb85481de07"},{url:"index.html",revision:"352bc7c6434621d063e95079ad5bf1a2"},{url:"assets/index-DbQBfiWD.js",revision:null},{url:"assets/index-DTCv5-8y.css",revision:null},{url:"manifest.webmanifest",revision:"5a42ebe8b55b07b5831cbbddda834829"}],{}),e.cleanupOutdatedCaches(),e.registerRoute(new e.NavigationRoute(e.createHandlerBoundToURL("index.html")))}); diff --git a/src/profiles/web/src/App.configEditor.test.tsx b/src/profiles/web/src/App.configEditor.test.tsx index 949f1ef..b9794e7 100644 --- a/src/profiles/web/src/App.configEditor.test.tsx +++ b/src/profiles/web/src/App.configEditor.test.tsx @@ -281,3 +281,75 @@ describe("App config editor integration", () => { ); }); }); + +/** + * Picker-mode regressions (issue #192): with NO active configuration + * (`config_exists: false`), only the first-run auto-prompt opens Create + * mode. Every explicit Load/Choose action must open Load mode — previously + * the picker inferred its mode from `configExists` and all entry points + * rendered Create. + */ +describe("App config picker mode (issue #192)", () => { + /** A no-config session: per-user default path, no directories. */ + const NO_CONFIG_OVERRIDES = { + config_exists: false, + config_path: "C:/Users/op/.profiles/.profiles", + directories: [], + active_directory: "", + }; + + it("test_first_run_auto_prompt_opens_create_mode_then_editor_entry_opens_load_mode", async () => { + const user = userEvent.setup(); + fetchConfigSpy.mockResolvedValue(makeAppConfig(NO_CONFIG_OVERRIDES)); + render(); + + // First-run auto-prompt: Create mode, as before. + const firstRun = await screen.findByRole("dialog", { name: /create configuration/i }); + expect( + within(firstRun).getByRole("button", { name: /create configuration/i }), + ).toBeTruthy(); + + // Dismiss it — nothing else opens until the user acts. + await user.click(within(firstRun).getByRole("button", { name: /^cancel$/i })); + await waitFor(() => + expect(screen.queryByRole("dialog", { name: /configuration/i })).toBeNull(), + ); + + // Editor header "Load config file…": an explicit load action → Load mode. + await user.click(screen.getByRole("button", { name: /^config$/i })); + const editor = await screen.findByRole("dialog", { name: /configuration editor/i }); + browseSpy.mockResolvedValue( + makeBrowseResult({ + current_path: "C:/Users/op/.profiles", + items: [{ name: "user.profiles", path: "C:/Users/op/.profiles/user.profiles", is_dir: false, is_config: true }], + }), + ); + await user.click(within(editor).getByRole("button", { name: /load config file/i })); + + const picker = await screen.findByRole("dialog", { name: /load configuration/i }); + expect( + within(picker).getByRole("button", { name: /^load configuration$/i }), + ).toBeTruthy(); + expect(within(picker).queryByText(/no configuration file was found/i)).toBeNull(); + }); + + it("test_filelist_choose_configuration_opens_load_mode", async () => { + const user = userEvent.setup(); + fetchConfigSpy.mockResolvedValue(makeAppConfig(NO_CONFIG_OVERRIDES)); + render(); + + // Dismiss the first-run auto-prompt. + const firstRun = await screen.findByRole("dialog", { name: /create configuration/i }); + await user.click(within(firstRun).getByRole("button", { name: /^cancel$/i })); + await waitFor(() => + expect(screen.queryByRole("dialog", { name: /configuration/i })).toBeNull(), + ); + + // FileList empty-state "Choose configuration": Load mode, not Create. + await user.click(screen.getByRole("button", { name: /choose configuration/i })); + const picker = await screen.findByRole("dialog", { name: /load configuration/i }); + expect( + within(picker).getByRole("button", { name: /^load configuration$/i }), + ).toBeTruthy(); + }); +}); diff --git a/src/profiles/web/src/App.tsx b/src/profiles/web/src/App.tsx index e2ee50f..f74c87f 100644 --- a/src/profiles/web/src/App.tsx +++ b/src/profiles/web/src/App.tsx @@ -37,6 +37,7 @@ import { SearchBar } from "./components/SearchBar"; import { LogViewerModal } from "./components/LogViewerModal"; import { ShortcutsModal } from "./components/ShortcutsModal"; import { LoadConfigModal } from "./components/LoadConfigModal"; +import type { ConfigPickerMode } from "./components/LoadConfigModal"; import { FilePropertiesModal } from "./components/FilePropertiesModal"; import { BarcodeModal } from "./components/BarcodeModal"; import { CameraBarcodeModal } from "./components/CameraBarcodeModal"; @@ -77,7 +78,13 @@ export default function App() { const [reloading, setReloading] = useState(false); const [language, setLanguage] = useState<"en" | "fr">("en"); const [showDirPicker, setShowDirPicker] = useState(false); - const [showConfigPicker, setShowConfigPicker] = useState(false); + /** + * Config picker intent (issue #192): null = closed, "create" = the + * first-run auto-prompt, "load" = an explicit Load/Choose action. The + * mode lives HERE because the caller knows why the picker opened; + * LoadConfigModal no longer infers it from the global config state. + */ + const [configPickerMode, setConfigPickerMode] = useState(null); // In-app YAML configuration editor (issue #95), opened from the StatusBar // "Config" button. The old OS-launch behavior moved into the editor's // header ("Open in OS"). @@ -394,7 +401,8 @@ export default function App() { if (cfg.recursive_search !== undefined) setRecursive(cfg.recursive_search); if (initialFilter) setFilterText(initialFilter); if (!cfg.config_exists) { - setShowConfigPicker(true); + // First-run auto-prompt: the ONLY entry point that proposes create. + setConfigPickerMode("create"); } if (initialDir) { @@ -811,7 +819,7 @@ export default function App() { contextMenuPos || showShortcuts || showDirPicker || - showConfigPicker || + configPickerMode !== null || showPropertiesModal || showLogViewer || showTimerModal || @@ -909,7 +917,9 @@ export default function App() { recursive={recursive} onDisableRecursive={handleDisableRecursive} onOpenDirectory={handleOpenActiveDirectory} - onLoadConfig={() => setShowConfigPicker(true)} + // FileList empty-state "Choose configuration" (issue #192): an + // explicit choose action always opens the picker in Load mode. + onLoadConfig={() => setConfigPickerMode("load")} filterText={filterText} onClearFilter={handleClearFilter} columnHeaders={config?.column_headers || []} @@ -974,7 +984,9 @@ export default function App() { open={showConfigEditor} onClose={() => setShowConfigEditor(false)} onApplied={handleConfigLoaded} - onLoadConfig={() => setShowConfigPicker(true)} + // Editor header "Load config file…" (issue #192): an explicit load + // action opens the picker in Load mode, never the first-run Create. + onLoadConfig={() => setConfigPickerMode("load")} reloadKey={editorReloadKey} /> @@ -982,10 +994,10 @@ export default function App() { so an editor left open underneath re-fetches the freshly picked file instead of keeping stale text (issue #101). */} setShowConfigPicker(false)} + onClose={() => setConfigPickerMode(null)} onLoaded={(cfg) => { void handleConfigLoaded(cfg); setEditorReloadKey((key) => key + 1); diff --git a/src/profiles/web/src/components/LoadConfigModal.test.tsx b/src/profiles/web/src/components/LoadConfigModal.test.tsx new file mode 100644 index 0000000..75a0fd3 --- /dev/null +++ b/src/profiles/web/src/components/LoadConfigModal.test.tsx @@ -0,0 +1,158 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { cleanup, render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { LoadConfigModal } from "./LoadConfigModal"; +import { browseForConfigFiles, createConfigFile, loadConfigFile } from "../api/client"; +import type { AppConfigData, BrowseResult } from "../api/types"; + +/** + * Unit tests for the config picker's explicit mode (issue #192): the + * caller tells the component WHY it opened — an explicit load action or + * the first-run create prompt — instead of the component inferring it + * from the global config state (`configExists === false`). + */ + +vi.mock("../api/client", () => ({ + browseForConfigFiles: vi.fn(), + createConfigFile: vi.fn(), + loadConfigFile: vi.fn(), +})); + +const browseSpy = vi.mocked(browseForConfigFiles); +const createSpy = vi.mocked(createConfigFile); +const loadSpy = vi.mocked(loadConfigFile); + +function makeBrowse(overrides: Partial = {}): BrowseResult { + return { + current_path: "/home/user/.profiles", + parent_path: "/home/user", + items: [ + { + name: "other.profiles", + path: "/home/user/.profiles/other.profiles", + is_dir: false, + is_config: true, + }, + ], + ...overrides, + }; +} + +function makeLoadedConfig(overrides: Partial = {}): AppConfigData { + return { + title: "other", + release: "1.0", + search_dir: "/home/user/data", + recursive_search: false, + theme: "dark", + directories: ["/home/user/data"], + extensions: [".mttl"], + filters: [], + active_directory: "/home/user/data", + config_path: "/home/user/.profiles/other.profiles", + config_exists: true, + column_headers: [], + column_names: [], + row_colors: [], + ...overrides, + }; +} + +function renderModal(overrides: { mode?: "load" | "create"; isOpen?: boolean } = {}) { + const onClose = vi.fn(); + const onLoaded = vi.fn(); + render( + , + ); + return { onClose, onLoaded }; +} + +beforeEach(() => { + vi.clearAllMocks(); + browseSpy.mockResolvedValue(makeBrowse()); +}); + +afterEach(() => { + cleanup(); + document.body.innerHTML = ""; +}); + +describe("LoadConfigModal modes (issue #192)", () => { + it("mode=create renders the create title, banner and primary button", async () => { + renderModal({ mode: "create" }); + + const dialog = await screen.findByRole("dialog"); + expect(within(dialog).getByRole("heading", { name: "Create configuration" })).toBeTruthy(); + expect( + within(dialog).getByText(/no configuration file was found/i), + ).toBeTruthy(); + expect( + await within(dialog).findByRole("button", { name: /create configuration/i }), + ).toBeTruthy(); + expect(browseSpy).toHaveBeenCalled(); + }); + + it("mode=create creates the config in the typed directory", async () => { + createSpy.mockResolvedValue(makeLoadedConfig()); + const { onLoaded, onClose } = renderModal({ mode: "create" }); + + const dialog = await screen.findByRole("dialog"); + await userEvent.setup().click( + await within(dialog).findByRole("button", { name: /create configuration/i }), + ); + + await waitFor(() => expect(createSpy).toHaveBeenCalledWith("/home/user/.profiles")); + await waitFor(() => expect(onLoaded).toHaveBeenCalledWith(makeLoadedConfig())); + await waitFor(() => expect(onClose).toHaveBeenCalled()); + }); + + it("mode=load renders the load title and primary button without the create banner", async () => { + renderModal({ mode: "load" }); + + const dialog = await screen.findByRole("dialog"); + expect(within(dialog).getByRole("heading", { name: "Load configuration" })).toBeTruthy(); + expect(within(dialog).queryByText(/no configuration file was found/i)).toBeNull(); + expect( + await within(dialog).findByRole("button", { name: /^load configuration$/i }), + ).toBeTruthy(); + }); + + it("mode=load keeps the load button disabled until a config is selected", async () => { + renderModal({ mode: "load" }); + + const loadButton = () => + screen.getByRole("button", { name: /^load configuration$/i }) as HTMLButtonElement; + await waitFor(() => expect(loadButton()).toBeTruthy()); + expect(loadButton().disabled).toBe(true); + + // Selecting a configuration file enables the load action. + await userEvent.setup().click(screen.getByRole("button", { name: /other\.profiles/i })); + expect(loadButton().disabled).toBe(false); + }); + + it("mode=load loads the selected config file", async () => { + loadSpy.mockResolvedValue(makeLoadedConfig()); + const { onLoaded, onClose } = renderModal({ mode: "load" }); + + await userEvent + .setup() + .click(await screen.findByRole("button", { name: /other\.profiles/i })); + await userEvent.setup().click(screen.getByRole("button", { name: /^load configuration$/i })); + + await waitFor(() => expect(loadSpy).toHaveBeenCalledWith("/home/user/.profiles/other.profiles")); + await waitFor(() => expect(onLoaded).toHaveBeenCalledWith(makeLoadedConfig())); + await waitFor(() => expect(onClose).toHaveBeenCalled()); + }); + + it("closed modal renders nothing", () => { + renderModal({ isOpen: false }); + expect(screen.queryByRole("dialog")).toBeNull(); + }); +}); diff --git a/src/profiles/web/src/components/LoadConfigModal.tsx b/src/profiles/web/src/components/LoadConfigModal.tsx index 71fbe78..a68abe5 100644 --- a/src/profiles/web/src/components/LoadConfigModal.tsx +++ b/src/profiles/web/src/components/LoadConfigModal.tsx @@ -6,18 +6,24 @@ import { Check, ChevronRight, FileCog, FileText, Folder, Home, Loader2, X } from import { browseForConfigFiles, createConfigFile, loadConfigFile } from "../api/client"; import type { AppConfigData, BrowseResult } from "../api/types"; +/** Why the picker is open: an explicit load action, or the first-run + * auto-prompt that proposes creating a starter configuration (#192). + * The caller owns the intent; the component never infers it from + * unrelated global config state. */ +export type ConfigPickerMode = "load" | "create"; + export interface LoadConfigModalProps { isOpen: boolean; + mode: ConfigPickerMode; activeConfigPath?: string; - configExists?: boolean; onClose: () => void; onLoaded: (config: AppConfigData) => void; } export function LoadConfigModal({ isOpen, + mode, activeConfigPath, - configExists = true, onClose, onLoaded, }: LoadConfigModalProps) { @@ -30,7 +36,7 @@ export function LoadConfigModal({ const pathInputRef = useRef(null); const previousFocusRef = useRef(null); - const isCreateMode = configExists === false; + const isCreateMode = mode === "create"; useEffect(() => { if (!isOpen) { diff --git a/src/profiles/web/tsconfig.tsbuildinfo b/src/profiles/web/tsconfig.tsbuildinfo index 4f010fc..507f755 100644 --- a/src/profiles/web/tsconfig.tsbuildinfo +++ b/src/profiles/web/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/app.configeditor.test.tsx","./src/app.scanflow.test.tsx","./src/app.tsx","./src/main.tsx","./src/setup-tests.ts","./src/vite-env.d.ts","./src/vitest.d.ts","./src/api/client.test.ts","./src/api/client.ts","./src/api/types.ts","./src/components/actionbar.tsx","./src/components/barcodemodal.test.tsx","./src/components/barcodemodal.tsx","./src/components/camerabarcodemodal.tsx","./src/components/configeditormodal.test.tsx","./src/components/configeditormodal.tsx","./src/components/confirmdialog.tsx","./src/components/contextmenu.tsx","./src/components/copyableurl.test.tsx","./src/components/copyableurl.tsx","./src/components/directorypickermodal.tsx","./src/components/dropconfigoverlay.tsx","./src/components/editablecombobox.test.tsx","./src/components/editablecombobox.tsx","./src/components/errorboundary.tsx","./src/components/filelisttable.tsx","./src/components/filepropertiesmodal.tsx","./src/components/filtersyntaxhelper.tsx","./src/components/headerbar.tsx","./src/components/initerrorpanel.tsx","./src/components/lanmodal.test.tsx","./src/components/lanmodal.tsx","./src/components/loadconfigmodal.tsx","./src/components/logviewermodal.test.tsx","./src/components/logviewermodal.tsx","./src/components/markdownmessage.test.tsx","./src/components/markdownmessage.tsx","./src/components/saveasdialog.test.tsx","./src/components/saveasdialog.tsx","./src/components/scanstatusstrip.tsx","./src/components/searchbar.tsx","./src/components/shortcutsmodal.tsx","./src/components/singlematchpromptmodal.tsx","./src/components/statusbar.test.tsx","./src/components/statusbar.tsx","./src/components/timermodal.tsx","./src/components/tooltip.tsx","./src/components/workflowrunnermodal.test.tsx","./src/components/workflowrunnermodal.tsx","./src/hooks/useautorescantimer.test.tsx","./src/hooks/useautorescantimer.ts","./src/hooks/usebarcodemode.test.tsx","./src/hooks/usebarcodemode.ts","./src/hooks/usedragdropconfig.test.tsx","./src/hooks/usedragdropconfig.ts","./src/hooks/useexternalevents.test.tsx","./src/hooks/useexternalevents.ts","./src/hooks/useglobalshortcuts.test.tsx","./src/hooks/useglobalshortcuts.ts","./src/hooks/usemodala11y.test.tsx","./src/hooks/usemodala11y.ts","./src/hooks/usescancontroller.test.tsx","./src/hooks/usescancontroller.ts","./src/hooks/usetheme.test.tsx","./src/hooks/usetheme.ts","./src/hooks/usetoast.test.tsx","./src/hooks/usetoast.ts","./src/utils/barcodedecoder.test.ts","./src/utils/barcodedecoder.ts","./src/utils/barcodescanner.test.ts","./src/utils/barcodescanner.ts","./src/utils/configdrop.test.ts","./src/utils/configdrop.ts","./src/utils/exportcsv.ts","./src/utils/fileproperties.test.ts","./src/utils/fileproperties.ts","./src/utils/fileuri.test.ts","./src/utils/fileuri.ts","./src/utils/scandefaults.test.ts","./src/utils/scandefaults.ts","./src/utils/searchsyntax.test.ts","./src/utils/searchsyntax.ts","./src/utils/theme.test.ts","./src/utils/theme.ts","./src/utils/version.test.ts","./src/utils/version.ts"],"version":"5.7.3"} \ No newline at end of file +{"root":["./src/app.configeditor.test.tsx","./src/app.scanflow.test.tsx","./src/app.tsx","./src/main.tsx","./src/setup-tests.ts","./src/vite-env.d.ts","./src/vitest.d.ts","./src/api/client.test.ts","./src/api/client.ts","./src/api/types.ts","./src/components/actionbar.tsx","./src/components/barcodemodal.test.tsx","./src/components/barcodemodal.tsx","./src/components/camerabarcodemodal.tsx","./src/components/configeditormodal.test.tsx","./src/components/configeditormodal.tsx","./src/components/confirmdialog.tsx","./src/components/contextmenu.tsx","./src/components/copyableurl.test.tsx","./src/components/copyableurl.tsx","./src/components/directorypickermodal.tsx","./src/components/dropconfigoverlay.tsx","./src/components/editablecombobox.test.tsx","./src/components/editablecombobox.tsx","./src/components/errorboundary.tsx","./src/components/filelisttable.tsx","./src/components/filepropertiesmodal.tsx","./src/components/filtersyntaxhelper.tsx","./src/components/headerbar.tsx","./src/components/initerrorpanel.tsx","./src/components/lanmodal.test.tsx","./src/components/lanmodal.tsx","./src/components/loadconfigmodal.test.tsx","./src/components/loadconfigmodal.tsx","./src/components/logviewermodal.test.tsx","./src/components/logviewermodal.tsx","./src/components/markdownmessage.test.tsx","./src/components/markdownmessage.tsx","./src/components/saveasdialog.test.tsx","./src/components/saveasdialog.tsx","./src/components/scanstatusstrip.tsx","./src/components/searchbar.tsx","./src/components/shortcutsmodal.tsx","./src/components/singlematchpromptmodal.tsx","./src/components/statusbar.test.tsx","./src/components/statusbar.tsx","./src/components/timermodal.tsx","./src/components/tooltip.tsx","./src/components/workflowrunnermodal.test.tsx","./src/components/workflowrunnermodal.tsx","./src/hooks/useautorescantimer.test.tsx","./src/hooks/useautorescantimer.ts","./src/hooks/usebarcodemode.test.tsx","./src/hooks/usebarcodemode.ts","./src/hooks/usedragdropconfig.test.tsx","./src/hooks/usedragdropconfig.ts","./src/hooks/useexternalevents.test.tsx","./src/hooks/useexternalevents.ts","./src/hooks/useglobalshortcuts.test.tsx","./src/hooks/useglobalshortcuts.ts","./src/hooks/usemodala11y.test.tsx","./src/hooks/usemodala11y.ts","./src/hooks/usescancontroller.test.tsx","./src/hooks/usescancontroller.ts","./src/hooks/usetheme.test.tsx","./src/hooks/usetheme.ts","./src/hooks/usetoast.test.tsx","./src/hooks/usetoast.ts","./src/utils/barcodedecoder.test.ts","./src/utils/barcodedecoder.ts","./src/utils/barcodescanner.test.ts","./src/utils/barcodescanner.ts","./src/utils/configdrop.test.ts","./src/utils/configdrop.ts","./src/utils/exportcsv.ts","./src/utils/fileproperties.test.ts","./src/utils/fileproperties.ts","./src/utils/fileuri.test.ts","./src/utils/fileuri.ts","./src/utils/scandefaults.test.ts","./src/utils/scandefaults.ts","./src/utils/searchsyntax.test.ts","./src/utils/searchsyntax.ts","./src/utils/theme.test.ts","./src/utils/theme.ts","./src/utils/version.test.ts","./src/utils/version.ts"],"version":"5.7.3"} \ No newline at end of file diff --git a/tests/AGENTS.md b/tests/AGENTS.md index ffb25dc..c7c16a9 100644 --- a/tests/AGENTS.md +++ b/tests/AGENTS.md @@ -37,6 +37,7 @@ tests/ ├── characterization/ # cross-cutting golden baseline (see exceptions) ├── core/ │ ├── test_actions.py # ← core/actions.py +│ ├── test_paths.py # ← core/paths.py (per-user path policy, #191) │ ├── config/ │ │ ├── test_inheritance.py # ← core/config/inheritance.py │ │ ├── test_loader.py # ← core/config/loader.py diff --git a/tests/conftest.py b/tests/conftest.py index a616189..e5cfe5a 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -55,3 +55,20 @@ def empty_config_path(tmp_path: Path) -> Path: config_file = tmp_path / ".profiles" config_file.write_text(dedent(config_content)) return config_file + + +@pytest.fixture(scope="function") +def isolated_user_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """Point the per-user data dir at a temp home (issue #191 hermeticity). + + Every path helper in :mod:`profiles.core.paths` resolves the user + home through ``Path.home()``; patching it makes ``user_data_dir``, + ``user_config_path``, ``find_user_config``, the uninformative-directory + home check and the ``default_search_directory`` fallback all see the + same fake home, so tests never depend on (or pollute) the developer's + real ``~/.profiles`` folder. Returns the fake home itself. + """ + user_home = tmp_path / "uhome" + user_home.mkdir() + monkeypatch.setattr("profiles.core.paths.Path.home", lambda: user_home) + return user_home diff --git a/tests/core/config/test_loader.py b/tests/core/config/test_loader.py index d98f8b8..a31c41f 100644 --- a/tests/core/config/test_loader.py +++ b/tests/core/config/test_loader.py @@ -29,10 +29,11 @@ def test_with_none_searches_tree(self, tmp_path: Path, monkeypatch: pytest.Monke assert config.theme == "light" def test_not_found_uses_default_path( - self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, isolated_user_home ) -> None: monkeypatch.chdir(tmp_path) - # No .profiles in tree — falls back to default ".profiles" in CWD + # No .profiles in tree or user dir — defaults bound to the default + # path (issue #191: the project folder for a terminal launch) config = load_config() assert config.config_path == Path.cwd() / ".profiles" @@ -47,6 +48,45 @@ def test_fallback_to_profiles_yaml_when_profiles_missing( assert config.theme == "dark" assert config.config_path == fallback + def test_user_config_loaded_when_project_tree_empty( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, isolated_user_home + ) -> None: + """No project config but ~/.profiles/.profiles exists → it loads (#191).""" + monkeypatch.chdir(tmp_path) + user_config = isolated_user_home / ".profiles" / ".profiles" + user_config.parent.mkdir(parents=True) + user_config.write_text("defaults:\n theme: dark\n", encoding="utf-8") + + config = load_config() + assert config.theme == "dark" + assert config.config_path == user_config + + def test_uninformative_cwd_skips_tree_search( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, isolated_user_home + ) -> None: + """A System32-style CWD is never searched for configs (#191).""" + monkeypatch.setenv("SystemRoot", str(tmp_path)) + system32 = tmp_path / "System32" + system32.mkdir() + (system32 / ".profiles").write_text("defaults:\n theme: light\n", encoding="utf-8") + monkeypatch.chdir(system32) + + config = load_config() + # Not the System32 "project" config: defaults bound to the user path + assert config.config_path == isolated_user_home / ".profiles" / ".profiles" + + def test_default_path_is_user_config_for_launcher_cwd( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, isolated_user_home + ) -> None: + """No config anywhere + System32 CWD → defaults bound to the user path.""" + monkeypatch.setenv("SystemRoot", str(tmp_path)) + system32 = tmp_path / "System32" + system32.mkdir() + monkeypatch.chdir(system32) + + config = load_config() + assert config.config_path == isolated_user_home / ".profiles" / ".profiles" + class TestDefaultColumnsWithoutConfig: """Tests verifying default columns are set when no config file exists.""" @@ -140,3 +180,18 @@ def failing_write(*args, **kwargs): # noqa: ANN001 monkeypatch.setattr("profiles.core.actions.write_text_atomic", failing_write) assert propose_config_creation() is False + + def test_launcher_cwd_creates_in_user_dir( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, isolated_user_home + ) -> None: + """A System32-style CWD creates the config in ~/.profiles (#191).""" + monkeypatch.setenv("SystemRoot", str(tmp_path)) + system32 = tmp_path / "System32" + system32.mkdir() + monkeypatch.chdir(system32) + monkeypatch.setattr("builtins.input", lambda: "y") + + assert propose_config_creation() is True + target = isolated_user_home / ".profiles" / ".profiles" + assert target.exists() + assert not (system32 / ".profiles").exists() diff --git a/tests/core/test_paths.py b/tests/core/test_paths.py new file mode 100644 index 0000000..68d2af1 --- /dev/null +++ b/tests/core/test_paths.py @@ -0,0 +1,205 @@ +"""Tests for :mod:`profiles.core.paths` — the per-user path policy. + +Issue #191: launcher-style launches (Start Menu, ``.desktop``) run with +an uninformative CWD (System32, the home folder) and must propose +``~/.profiles/.profiles`` instead of writing a config into a system +directory. All user-home-dependent behaviour is exercised through the +``isolated_user_home`` fixture so no test touches the real home. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import pytest + +from profiles.core.paths import ( + USER_DATA_DIRNAME, + default_config_path, + default_search_directory, + find_user_config, + is_uninformative_directory, + user_config_path, + user_data_dir, +) + +pytestmark = pytest.mark.usefixtures("isolated_user_home") + + +class TestUserDataDir: + def test_user_data_dir_is_under_home(self, isolated_user_home: Path) -> None: + assert user_data_dir() == isolated_user_home / USER_DATA_DIRNAME + assert USER_DATA_DIRNAME == ".profiles" + + def test_user_config_path_is_primary_name_in_data_dir(self, isolated_user_home: Path) -> None: + assert user_config_path() == isolated_user_home / ".profiles" / ".profiles" + + def test_default_log_path_shares_the_data_dir(self, isolated_user_home: Path) -> None: + """Logs and the per-user config live in the same folder (#191).""" + from profiles.core.telemetry.diagnostics import default_log_path + + assert default_log_path() == user_data_dir() / "profiles.log" + + +class TestFindUserConfig: + def test_returns_none_when_data_dir_is_missing(self) -> None: + assert find_user_config() is None + + def test_finds_primary_name(self, isolated_user_home: Path) -> None: + config = user_config_path() + config.parent.mkdir(parents=True) + config.write_text("defaults:\n theme: light\n") + assert find_user_config() == config + + def test_yaml_fallback_only_without_primary(self, isolated_user_home: Path) -> None: + data_dir = user_data_dir() + data_dir.mkdir(parents=True) + yaml_config = data_dir / ".profiles.yaml" + yaml_config.write_text("defaults:\n theme: dark\n") + assert find_user_config() == yaml_config + + def test_primary_beats_yaml(self, isolated_user_home: Path) -> None: + data_dir = user_data_dir() + data_dir.mkdir(parents=True) + (data_dir / ".profiles").write_text("x") + yaml_config = data_dir / ".profiles.yaml" + yaml_config.write_text("x") + assert find_user_config() == data_dir / ".profiles" + + def test_ignores_directories_named_like_configs(self, isolated_user_home: Path) -> None: + """A directory must never be mistaken for a config file.""" + data_dir = user_data_dir() + (data_dir / ".profiles").mkdir(parents=True) + assert find_user_config() is None + + def test_ignores_nested_configs(self, isolated_user_home: Path) -> None: + """Depth 0 only: no wildcard walk of the data dir.""" + nested = user_data_dir() / "sub" / ".profiles" + nested.parent.mkdir(parents=True) + nested.write_text("x") + assert find_user_config() is None + + +class TestIsUninformativeDirectory: + def test_none_is_uninformative(self) -> None: + assert is_uninformative_directory(None) is True + + def test_filesystem_root_is_uninformative(self) -> None: + root = Path(tmp_root()) + assert is_uninformative_directory(root) is True + + def test_home_itself_is_uninformative(self, isolated_user_home: Path) -> None: + assert is_uninformative_directory(isolated_user_home) is True + + def test_directory_inside_home_is_informative(self, isolated_user_home: Path) -> None: + project = isolated_user_home / "project" + project.mkdir() + assert is_uninformative_directory(project) is False + + def test_python_prefix_is_uninformative(self, isolated_user_home: Path) -> None: + inside_runtime = Path(sys.prefix) / "lib" + assert is_uninformative_directory(inside_runtime) is True + + def test_executable_directory_is_uninformative(self, isolated_user_home: Path) -> None: + exe_dir = Path(sys.executable).resolve().parent + assert is_uninformative_directory(exe_dir) is True + + def test_system_root_env_is_uninformative( + self, isolated_user_home: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """A fake %SystemRoot% (via env, portable on every platform).""" + monkeypatch.setenv("SystemRoot", str(isolated_user_home / "Windows")) + system32 = isolated_user_home / "Windows" / "System32" + system32.mkdir(parents=True) + assert is_uninformative_directory(system32) is True + + def test_windir_env_is_uninformative( + self, isolated_user_home: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setenv("windir", str(isolated_user_home / "WinDir")) + inside = isolated_user_home / "WinDir" / "SysWOW64" + inside.mkdir(parents=True) + assert is_uninformative_directory(inside) is True + + def test_program_files_env_is_uninformative( + self, isolated_user_home: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setenv("ProgramFiles", str(isolated_user_home / "Program Files")) + inside = isolated_user_home / "Program Files" / "ProFiles" + inside.mkdir(parents=True) + assert is_uninformative_directory(inside) is True + + def test_program_files_x86_env_is_uninformative( + self, isolated_user_home: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setenv("ProgramFiles(x86)", str(isolated_user_home / "PF86")) + inside = isolated_user_home / "PF86" / "ProFiles" + inside.mkdir(parents=True) + assert is_uninformative_directory(inside) is True + + def test_temp_dir_is_informative(self, tmp_path: Path) -> None: + assert is_uninformative_directory(tmp_path) is False + + +def tmp_root() -> str: + """Return a filesystem root for the current platform.""" + return "/" if sys.platform != "win32" else "C:\\" + + +class TestDefaultConfigPath: + def test_uninformative_start_proposes_user_config( + self, isolated_user_home: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + system32 = isolated_user_home / "Windows" / "System32" + system32.mkdir(parents=True) + monkeypatch.setenv("SystemRoot", str(isolated_user_home / "Windows")) + assert default_config_path(system32) == user_config_path() + + def test_none_start_uses_cwd_policy( + self, isolated_user_home: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """None start resolves the CWD; an uninformative one → per-user path.""" + system32 = isolated_user_home / "Windows" / "System32" + system32.mkdir(parents=True) + monkeypatch.setenv("SystemRoot", str(isolated_user_home / "Windows")) + monkeypatch.chdir(system32) + assert default_config_path(None) == user_config_path() + + def test_informative_start_proposes_in_place(self, tmp_path: Path) -> None: + assert default_config_path(tmp_path) == tmp_path / ".profiles" + + def test_directory_collision_falls_back_to_user_config( + self, isolated_user_home: Path, tmp_path: Path + ) -> None: + """start/.profiles already being a DIRECTORY must never be proposed.""" + (tmp_path / ".profiles").mkdir() + assert default_config_path(tmp_path) == user_config_path() + + def test_existing_file_does_not_trigger_collision_fallback( + self, isolated_user_home: Path, tmp_path: Path + ) -> None: + """An existing .profiles FILE stays the candidate (idempotent).""" + (tmp_path / ".profiles").write_text("x") + assert default_config_path(tmp_path) == tmp_path / ".profiles" + + +class TestDefaultSearchDirectory: + def test_uninformative_start_returns_home( + self, isolated_user_home: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + system32 = isolated_user_home / "Windows" / "System32" + system32.mkdir(parents=True) + monkeypatch.setenv("SystemRoot", str(isolated_user_home / "Windows")) + assert default_search_directory(system32) == isolated_user_home + + def test_informative_start_returns_itself(self, tmp_path: Path) -> None: + assert default_search_directory(tmp_path) == tmp_path + + def test_none_start_resolves_cwd(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.chdir(tmp_path) + assert default_search_directory() == tmp_path + + def test_home_cwd_resolves_to_home(self, isolated_user_home: Path) -> None: + """CWD == home is uninformative: the scan target becomes home.""" + assert default_search_directory(isolated_user_home) == isolated_user_home diff --git a/tests/desktop/test_launcher.py b/tests/desktop/test_launcher.py index db0d532..4d47ab8 100644 --- a/tests/desktop/test_launcher.py +++ b/tests/desktop/test_launcher.py @@ -114,16 +114,51 @@ def test_applies_config_and_records_notification(self, tmp_path) -> None: assert events[-1]["config_applied"] is True assert "b.profiles" in events[-1]["message"] - def test_rejects_and_reports_a_non_config_file(self, tmp_path) -> None: + def test_skips_a_folder_document_without_events(self, tmp_path) -> None: + """A folder opened with the running app is not a config apply (#193). + + macOS delivers the opened folder as an odoc document too; launch + resolution skips it and falls back to the directory search, so the + running-window applier must not report a failed config apply — + no toast, no state change. + """ + state = ServerState(config=AppConfig(title="t")) + folder = tmp_path / "session" + folder.mkdir() + (folder / "a.profiles").write_text("defaults:\n title: A\n", encoding="utf-8") + + _make_document_applier(state)([str(folder)]) # must not raise + + assert state.external_events_after(0) == [] + assert state.config_path is None + + def test_skips_a_non_config_file_silently(self, tmp_path) -> None: + """A non-config document is skipped like launch resolution does (#193).""" state = ServerState(config=AppConfig(title="t")) junk = tmp_path / "junk.txt" junk.write_text("nope", encoding="utf-8") _make_document_applier(state)([str(junk)]) # must not raise + assert state.external_events_after(0) == [] + assert state.config_path is None + + def test_applies_a_case_variant_config_name(self, tmp_path) -> None: + """The skip guard accepts exactly what the apply step accepts. + + Case-insensitive like the load/save endpoints (issue #95 wave): a + ``ConfigB.PROFILES`` document applies instead of being skipped. + """ + state = ServerState(config=AppConfig(title="t")) + config = tmp_path / "ConfigB.PROFILES" + config.write_text("defaults:\n title: B\n", encoding="utf-8") + + _make_document_applier(state)([str(config)]) # must not raise + + assert state.config_path == config.resolve() events = state.external_events_after(0) - assert events[-1]["kind"] == "config_handoff_failed" - assert events[-1]["config_applied"] is False + assert events[-1]["kind"] == "config_handoff" + assert events[-1]["config_applied"] is True def test_reports_a_missing_file_without_raising(self, tmp_path) -> None: state = ServerState(config=AppConfig(title="t")) diff --git a/tests/launch/test_context.py b/tests/launch/test_context.py index ccb2b45..b91cfa4 100644 --- a/tests/launch/test_context.py +++ b/tests/launch/test_context.py @@ -282,7 +282,13 @@ def test_relative_documents_resolve_against_cwd(self, monkeypatch, tmp_path) -> class TestCwdIsUninformative: - """The GUI-launch CWD heuristic shared by the probe and odoc capture.""" + """The GUI-launch CWD heuristic shared by the probe and odoc capture. + + Delegates to profiles.core.paths.is_uninformative_directory (issue + #191), so System32-style and home-folder CWDs are uninformative on + every platform — verified here with monkeypatched env vars / homes + for portability. + """ def test_root_is_uninformative(self) -> None: assert cwd_is_uninformative(Path("/")) is True @@ -295,3 +301,14 @@ def test_runtime_prefix_is_uninformative(self) -> None: def test_real_working_directory_is_informative(self, tmp_path) -> None: assert cwd_is_uninformative(tmp_path) is False + + def test_system32_is_uninformative(self, isolated_user_home, monkeypatch) -> None: + """Start-Menu CWD (%SystemRoot%\\System32) must be discarded (#191).""" + monkeypatch.setenv("SystemRoot", str(isolated_user_home / "Windows")) + system32 = isolated_user_home / "Windows" / "System32" + system32.mkdir(parents=True) + assert cwd_is_uninformative(system32) is True + + def test_home_folder_is_uninformative(self, isolated_user_home) -> None: + """A launcher CWD == home says nothing about a project (#191).""" + assert cwd_is_uninformative(isolated_user_home) is True diff --git a/tests/launch/test_creation.py b/tests/launch/test_creation.py index 6e101b8..6f94ff6 100644 --- a/tests/launch/test_creation.py +++ b/tests/launch/test_creation.py @@ -84,3 +84,53 @@ def test_creation_result_is_immutable(self) -> None: # Should raise AttributeError if we try to modify with pytest.raises(AttributeError): result.status = "SKIPPED" # type: ignore + + +class TestStarterSearchDir: + """The starter's search_dir template placeholder (issue #191).""" + + @staticmethod + def _starter_search_dir(config_path: Path) -> str: + """Extract the search_dir value from a written starter file.""" + for line in config_path.read_text(encoding="utf-8").splitlines(): + stripped = line.strip() + if stripped.startswith("search_dir:"): + return stripped.split(":", 1)[1].strip().strip("'\"") + raise AssertionError("starter has no search_dir line") + + def test_project_target_scans_itself(self, tmp_path, monkeypatch) -> None: + """A project-directory creation scans the project folder.""" + monkeypatch.chdir(tmp_path) + result = propose_creation(tmp_path) + + assert result.status == "CREATED" + assert self._starter_search_dir(result.path) == str(tmp_path) + + def test_explicit_search_dir_is_used(self, tmp_path) -> None: + """An explicit search_dir lands in the template verbatim.""" + scan_dir = tmp_path / "programs" + scan_dir.mkdir() + result = propose_creation(tmp_path, search_dir=scan_dir) + + assert result.status == "CREATED" + assert self._starter_search_dir(result.path) == str(scan_dir) + + def test_user_data_dir_target_scans_home( + self, tmp_path, isolated_user_home, monkeypatch + ) -> None: + """Creating in ~/.profiles scans the home, not the data dir (#191). + + The data folder only holds logs and configs, so scanning it is + useless; with an uninformative CWD (Start-Menu style) the scan + target falls back to the home folder itself. + """ + monkeypatch.setenv("SystemRoot", str(tmp_path)) + system32 = tmp_path / "System32" + system32.mkdir() + monkeypatch.chdir(system32) + + data_dir = isolated_user_home / ".profiles" + result = propose_creation(data_dir) + + assert result.status == "CREATED" + assert self._starter_search_dir(result.path) == str(isolated_user_home) diff --git a/tests/launch/test_resolution.py b/tests/launch/test_resolution.py index e7fcaf7..123055e 100644 --- a/tests/launch/test_resolution.py +++ b/tests/launch/test_resolution.py @@ -3,10 +3,17 @@ These tests verify the pure decision logic that chooses which configuration file ProFiles should use at startup. No files are read or written here; that is tested in :mod:`test_creation`. + +Since issue #191 the resolution also consults the per-user default +(``~/.profiles/.profiles``) as the final fallback and skips the CWD tree +search for uninformative directories — the user home is isolated through +the ``isolated_user_home`` fixture wherever that fallback is in play. """ from __future__ import annotations +import pytest + from profiles.launch.context import LaunchContext from profiles.launch.resolution import resolve_config_path @@ -76,8 +83,8 @@ def test_tree_search_from_working_directory(self, tmp_path) -> None: result = resolve_config_path(ctx) assert result == deep - def test_no_match_returns_none(self, tmp_path) -> None: - """When nothing is found, resolve_config_path returns None.""" + def test_no_match_returns_none(self, tmp_path, isolated_user_home) -> None: + """When nothing is found anywhere, resolve_config_path returns None.""" ctx = LaunchContext( document_paths=(), working_directory=tmp_path, @@ -157,3 +164,108 @@ def test_search_tier_priority(self, tmp_path) -> None: source="cwd", ) assert resolve_config_path(ctx) == yaml_conf + + +class TestPerUserConfigFallback: + """The per-user default (~/.profiles/.profiles) as final fallback (#191).""" + + def test_empty_tree_falls_back_to_user_config(self, tmp_path, isolated_user_home) -> None: + """Matrix row 6: no project config, user config exists → it wins.""" + user_config = isolated_user_home / ".profiles" / ".profiles" + user_config.parent.mkdir(parents=True) + user_config.write_text("defaults:\n theme: dark\n") + + ctx = LaunchContext( + document_paths=(), + working_directory=tmp_path, + explicit_config=None, + source="cwd", + ) + assert resolve_config_path(ctx) == user_config + + def test_project_config_beats_user_config(self, tmp_path, isolated_user_home) -> None: + """A project config in the CWD tree still wins over the user one.""" + user_config = isolated_user_home / ".profiles" / ".profiles" + user_config.parent.mkdir(parents=True) + user_config.write_text("x") + + project_config = tmp_path / ".profiles" + project_config.write_text("x") + + ctx = LaunchContext( + document_paths=(), + working_directory=tmp_path, + explicit_config=None, + source="cwd", + ) + assert resolve_config_path(ctx) == project_config + + def test_uninformative_cwd_skips_tree_search( + self, tmp_path, isolated_user_home, monkeypatch + ) -> None: + """A System32-style CWD is never walked for configs (#191).""" + monkeypatch.setenv("SystemRoot", str(tmp_path)) + system32 = tmp_path / "System32" + system32.mkdir() + # A config inside the "system" tree must NOT be discovered. + (system32 / ".profiles").write_text("x") + + ctx = LaunchContext( + document_paths=(), + working_directory=system32, + explicit_config=None, + source="cwd", + ) + assert resolve_config_path(ctx) is None + + def test_uninformative_cwd_with_user_config_falls_back( + self, tmp_path, isolated_user_home, monkeypatch + ) -> None: + """Matrix row 4: launcher start, user config exists → loaded.""" + monkeypatch.setenv("SystemRoot", str(tmp_path)) + system32 = tmp_path / "System32" + system32.mkdir() + + user_config = isolated_user_home / ".profiles" / ".profiles" + user_config.parent.mkdir(parents=True) + user_config.write_text("x") + + ctx = LaunchContext( + document_paths=(), + working_directory=system32, + explicit_config=None, + source="cwd", + ) + assert resolve_config_path(ctx) == user_config + + def test_yaml_user_config_is_found(self, tmp_path, isolated_user_home) -> None: + """The legacy .profiles.yaml name also works as the user default.""" + user_config = isolated_user_home / ".profiles" / ".profiles.yaml" + user_config.parent.mkdir(parents=True) + user_config.write_text("x") + + ctx = LaunchContext( + document_paths=(), + working_directory=tmp_path, + explicit_config=None, + source="cwd", + ) + assert resolve_config_path(ctx) == user_config + + @pytest.mark.parametrize("winner", ["explicit", "document"]) + def test_explicit_and_document_still_win(self, tmp_path, isolated_user_home, winner) -> None: + """Explicit flags and opened documents outrank the user default.""" + user_config = isolated_user_home / ".profiles" / ".profiles" + user_config.parent.mkdir(parents=True) + user_config.write_text("x") + + winning = tmp_path / "winner.profiles" + winning.write_text("x") + + ctx = LaunchContext( + document_paths=(winning,) if winner == "document" else (), + working_directory=tmp_path, + explicit_config=winning if winner == "explicit" else None, + source=winner, + ) + assert resolve_config_path(ctx) == winning diff --git a/tests/server/routes/test_config.py b/tests/server/routes/test_config.py index 1f4d3a3..ae17692 100644 --- a/tests/server/routes/test_config.py +++ b/tests/server/routes/test_config.py @@ -138,3 +138,76 @@ async def test_fs_browse(test_state: ServerState, tmp_path: Path) -> None: data = response.json() assert "items" in data assert any(item["name"] == "programs" and item["is_dir"] for item in data["items"]) + + +# --------------------------------------------------------------------------- +# Per-user config path policy (issue #191) +# --------------------------------------------------------------------------- + + +class TestActiveConfigPathPolicy: + """ServerState.active_config_path fallback rules from issue #191.""" + + def test_never_returns_an_existing_directory(self, test_state, tmp_path: Path) -> None: + """A directory (the ~/.profiles log-dir collision) is never the config.""" + collision = tmp_path / ".profiles" + collision.mkdir() # a DIRECTORY named like a config + test_state.config_path = collision + assert test_state.active_config_path() != collision + assert not test_state.active_config_path().is_dir() + + def test_falls_back_to_default_config_path_when_unanchored( + self, test_state, tmp_path: Path, isolated_user_home, monkeypatch + ) -> None: + """No recorded path → default_config_path (CWD-aware, issue #191). + + An informative empty CWD proposes in place; a System32-style CWD + proposes the per-user ``~/.profiles/.profiles``. + """ + test_state.config_path = None + test_state.config.config_path = None + + empty_cwd = tmp_path / "empty-cwd" + empty_cwd.mkdir() + monkeypatch.chdir(empty_cwd) + assert test_state.active_config_path() == empty_cwd / ".profiles" + + monkeypatch.setenv("SystemRoot", str(tmp_path)) + system32 = tmp_path / "System32" + system32.mkdir() + monkeypatch.chdir(system32) + assert test_state.active_config_path() == (isolated_user_home / ".profiles" / ".profiles") + + def test_recorded_file_path_is_returned_as_is(self, test_state, tmp_path: Path) -> None: + anchored = tmp_path / "sub" / ".profiles" + anchored.parent.mkdir() + anchored.write_text("version: 1\n", encoding="utf-8") + test_state.config_path = anchored + assert test_state.active_config_path() == anchored + + +@pytest.mark.anyio +async def test_get_config_prefills_home_for_uninformative_cwd( + tmp_path: Path, isolated_user_home, monkeypatch +) -> None: + """Empty-config first paint never scans System32 (issue #191). + + Given: a defaults-only config with NO candidate directories at all + When: GET /api/config runs with a %SystemRoot%\\System32-style CWD + Then: the active-directory fallback is the (isolated) home folder + """ + config = AppConfig(title="Fresh Install", search_dir="", extensions=(".mttl",)) + config.config_path = tmp_path / "nowhere" / ".profiles" + state = ServerState(config=config, active_directory=None) + + monkeypatch.setenv("SystemRoot", str(tmp_path)) + system32 = tmp_path / "System32" + system32.mkdir() + monkeypatch.chdir(system32) + + app = create_app(state) + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + response = await client.get("/api/config") + + assert response.status_code == 200 + assert response.json()["active_directory"] == str(isolated_user_home) diff --git a/tests/server/routes/test_config_editor.py b/tests/server/routes/test_config_editor.py index 31ed258..5c7df38 100644 --- a/tests/server/routes/test_config_editor.py +++ b/tests/server/routes/test_config_editor.py @@ -963,3 +963,34 @@ async def test_save_as_response_carries_content_hash(tmp_path: Path) -> None: payload = response.json() assert payload["status"] == "SAVED" assert payload["content_hash"] == content_hash(new_text) + + +@pytest.mark.anyio +async def test_template_without_active_directory_uses_default_search_directory( + tmp_path: Path, isolated_user_home, monkeypatch +) -> None: + """No active directory + launcher-style CWD → scan target is home (#191). + + The template's search_dir fallback must not inherit the process CWD: + a Start-Menu launch would otherwise draft a starter scanning System32. + """ + state = ServerState( + config=AppConfig(title="Fresh", search_dir="", extensions=(".txt",)), + active_directory=None, + ) + monkeypatch.setenv("SystemRoot", str(tmp_path)) + system32 = tmp_path / "System32" + system32.mkdir() + monkeypatch.chdir(system32) + + app = create_app(state) + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + response = await client.post("/api/config/template") + + assert response.status_code == 200 + search_line = next( + line + for line in response.json()["content"].splitlines() + if line.lstrip().startswith("search_dir:") + ) + assert str(isolated_user_home) in search_line diff --git a/tests/server/routes/test_config_load.py b/tests/server/routes/test_config_load.py index 587c8cb..70a6ac9 100644 --- a/tests/server/routes/test_config_load.py +++ b/tests/server/routes/test_config_load.py @@ -369,3 +369,41 @@ async def test_create_refuses_overwrite(config_state: ServerState, tmp_path: Pat assert response.status_code == 400 assert "already exists" in response.json()["detail"].lower() + + +@pytest.mark.anyio +async def test_create_in_user_data_dir_scans_home( + tmp_path: Path, isolated_user_home, monkeypatch +) -> None: + """Creating in ~/.profiles writes there and drafts a home scan dir (#191). + + Given: a session with no active directory and a System32-style CWD + When: POST /api/config/create targets the per-user data directory + Then: the starter lands at ~/.profiles/.profiles and its search_dir + points at the home folder — never at the process CWD. + """ + state = ServerState( + config=AppConfig(title="Fresh", search_dir="", extensions=(".mttl",)), + active_directory=None, + ) + monkeypatch.setenv("SystemRoot", str(tmp_path)) + system32 = tmp_path / "System32" + system32.mkdir() + monkeypatch.chdir(system32) + + data_dir = isolated_user_home / ".profiles" + app = create_app(state) + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + response = await client.post("/api/config/create", json={"directory": str(data_dir)}) + + assert response.status_code == 200 + created = data_dir / ".profiles" + assert created.exists() + assert response.json()["config_path"] == str(created) + search_line = next( + line + for line in created.read_text(encoding="utf-8").splitlines() + if line.lstrip().startswith("search_dir:") + ) + assert str(isolated_user_home) in search_line + assert "System32" not in search_line diff --git a/tests/test_app_launch_resolution.py b/tests/test_app_launch_resolution.py index 5011c32..f82e2ab 100644 --- a/tests/test_app_launch_resolution.py +++ b/tests/test_app_launch_resolution.py @@ -2,6 +2,8 @@ from __future__ import annotations +import pytest + from profiles.app import ProFileApp @@ -14,7 +16,7 @@ def test_explicit_config_flag_wins(self, tmp_path, monkeypatch) -> None: explicit.write_text("x") app = ProFileApp(config_path=explicit) - resolved, missing = app._resolve_startup_config(explicit) + resolved, missing, _default = app._resolve_startup_config(explicit) assert resolved == explicit assert missing is False @@ -30,16 +32,18 @@ def test_no_args_in_dir_with_config_finds_it( monkeypatch.chdir(tmp_path) app = ProFileApp() - resolved, missing = app._resolve_startup_config(None) + resolved, missing, _default = app._resolve_startup_config(None) assert resolved == config assert missing is False - def test_no_args_no_config_returns_none(self, monkeypatch, tmp_path) -> None: + def test_no_args_no_config_returns_none( + self, monkeypatch, tmp_path, isolated_user_home + ) -> None: """When no config found anywhere, returns None.""" monkeypatch.chdir(tmp_path) app = ProFileApp() - resolved, missing = app._resolve_startup_config(None) + resolved, missing, _default = app._resolve_startup_config(None) assert resolved is None assert missing is False @@ -53,7 +57,7 @@ def test_missing_explicit_config_is_reported( missing = tmp_path / "nonexistent.profiles" app = ProFileApp(config_path=missing) - resolved, missing_flag = app._resolve_startup_config(missing) + resolved, missing_flag, _default = app._resolve_startup_config(missing) assert resolved == missing assert missing_flag is True @@ -62,11 +66,13 @@ def test_missing_explicit_config_is_reported( class TestLaunchSourceRecording: """The context source is remembered for the handoff gate (issue #188).""" - def test_folder_search_launch_records_cwd_source(self, monkeypatch, tmp_path) -> None: + def test_folder_search_launch_records_cwd_source( + self, monkeypatch, tmp_path, isolated_user_home + ) -> None: """A launch with no explicit/doc signal is folder-search driven.""" monkeypatch.chdir(tmp_path) app = ProFileApp() - resolved, _missing = app._resolve_startup_config(None) + resolved, _missing, _default = app._resolve_startup_config(None) assert resolved is None # no literal config name in the folder assert app._launch_source == "cwd" @@ -107,8 +113,69 @@ def test_odoc_document_drives_resolution(self, monkeypatch, tmp_path, mocker) -> ) app = ProFileApp() - resolved, missing = app._resolve_startup_config(None) + resolved, missing, _default = app._resolve_startup_config(None) assert resolved == clicked assert missing is False assert app._launch_source == "document" + + +class TestStartMenuLaunch: + """Simulated launcher-style launches with an uninformative CWD (#191). + + A Start-Menu shortcut with an empty "Start in" runs with + ``CWD = %SystemRoot%\\System32``. The simulated repro monkeypatches + the CWD to a fake System32 and ``Path.home()`` to a temp folder, so + the whole startup resolution is exercised hermetically on any OS. + """ + + @pytest.fixture + def fake_system32_home(self, tmp_path, monkeypatch): + """Fake %SystemRoot%\\System32 CWD + fake home; yields (cwd, home). + + The macOS Finder probe is stubbed out: an uninformative CWD is + exactly the condition that triggers it, and the dev machine's + real front Finder window must never leak into the result. + """ + system_root = tmp_path / "Windows" + system32 = system_root / "System32" + system32.mkdir(parents=True) + user_home = tmp_path / "uhome" + user_home.mkdir() + monkeypatch.setenv("SystemRoot", str(system_root)) + monkeypatch.chdir(system32) + monkeypatch.setattr("profiles.core.paths.Path.home", lambda: user_home) + monkeypatch.setattr("profiles.launch.context._finder_working_directory", lambda: None) + return system32, user_home + + def test_resolution_proposes_user_config_path(self, fake_system32_home, monkeypatch) -> None: + """System32 CWD + empty home → launch default is ~/.profiles/.profiles.""" + _system32, user_home = fake_system32_home + app = ProFileApp() + resolved, missing, launch_default = app._resolve_startup_config(None) + + assert resolved is None # System32 tree is never searched + assert missing is False + assert launch_default == user_home / ".profiles" / ".profiles" + + def test_load_configuration_binds_user_config_path(self, fake_system32_home, mocker) -> None: + """AppConfig.config_path carries the per-user path for the UI.""" + _system32, user_home = fake_system32_home + app = ProFileApp() + config = app._load_configuration(mocker.Mock()) + + assert config.config_path == user_home / ".profiles" / ".profiles" + assert app._config_path == config.config_path + + def test_existing_user_config_is_loaded_on_relaunch(self, fake_system32_home) -> None: + """Matrix row 4: second Start-Menu launch loads the user config.""" + _system32, user_home = fake_system32_home + user_config = user_home / ".profiles" / ".profiles" + user_config.parent.mkdir(parents=True) + user_config.write_text("defaults:\n theme: dark\n", encoding="utf-8") + + app = ProFileApp() + resolved, missing, _default = app._resolve_startup_config(None) + + assert resolved == user_config + assert missing is False