Skip to content

UI API Reference

This document is automatically generated. Do not edit manually.

Component Architecture & Catalog Diagrams

Catalog Interactive Workbench Workflow

Component Catalog Workflow

UI Component Hierarchy

UI Component Hierarchy

app.ui.a11y

app.ui.a11y

Accessibility mixin and audit helpers shared by every TUI screen.

A11yMixin

Mixin providing WCAG 2.1 screen reader announcements, accessibility attributes, and audit hooks.

Source code in app/ui/a11y.py
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
class A11yMixin:
    """Mixin providing WCAG 2.1 screen reader announcements, accessibility attributes, and audit hooks."""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.announcements: list[dict[str, Any]] = []
        self.last_announcement: str | None = None
        self._speech_thread: threading.Thread | None = None

    def _resolve_app_instance(self) -> Any | None:
        """Return the owning Textual App instance if mounted or self is an App."""
        if isinstance(self, App):
            return self
        try:
            return getattr(self, "_app", None) or getattr(self, "app", None)
        except Exception:
            return None

    def _is_character_input_focused(self) -> bool:
        """Return True if an Input or Select widget (or Select overlay) holds active focus."""
        app_obj = self._resolve_app_instance()
        focused = getattr(self, "focused", None) or getattr(app_obj, "focused", None)
        if focused is None:
            return False
        if isinstance(focused, (Input, Select)):
            return True
        ancestors = getattr(focused, "ancestors_with_self", ())
        return any(isinstance(anc, (Input, Select)) for anc in ancestors)

    def _character_shortcuts_enabled(self) -> bool:
        """Return True if single-character keyboard shortcuts are enabled."""
        app_obj = self._resolve_app_instance()
        settings = getattr(self, "settings", None) or getattr(app_obj, "settings", None)
        if settings is None:
            return True
        return bool(getattr(settings, "ENABLE_CHARACTER_KEY_SHORTCUTS", True))

    def check_action(self, action: str, parameters: tuple[object, ...]) -> bool | None:
        """Gate character-triggered help overlay bindings on shortcut setting."""
        if action == "open_help_overlay" and parameters and parameters[0] is True:
            if not self._character_shortcuts_enabled():
                return False
        check_fn = getattr(super(), "check_action", None)
        if callable(check_fn):
            return check_fn(action, parameters)
        return True

    def action_open_help_overlay(self, from_character: bool = False) -> None:
        """Open keyboard shortcut cheat sheet overlay lazily from any screen or modal."""
        if from_character and (
            self._is_character_input_focused()
            or not self._character_shortcuts_enabled()
        ):
            return
        from app.ui.modals.help import ShortcutCheatSheetModal

        app_obj = self._resolve_app_instance()
        if app_obj is None:
            return
        if isinstance(getattr(app_obj, "screen", None), ShortcutCheatSheetModal):
            return
        push_fn = getattr(app_obj, "push_screen", None)
        if callable(push_fn):
            push_fn(ShortcutCheatSheetModal())

    def update_status(self, text: str) -> None:
        """Update visual status region on self or parent application."""
        try:
            app_obj = getattr(self, "app", None)
            update_fn = (
                getattr(app_obj, "update_status", None)
                if app_obj and app_obj is not self
                else None
            )
            if callable(update_fn):
                update_fn(text)
        except Exception:
            pass

    def join_speech_thread(self, timeout: float = 1.0) -> None:
        """Wait for active speech synthesis thread to finish."""
        speech_thread = self._speech_thread
        if speech_thread is not None:
            if speech_thread.is_alive():
                try:
                    speech_thread.join(timeout=timeout)
                except Exception:
                    pass
            if not speech_thread.is_alive():
                self._speech_thread = None
        app_obj = getattr(self, "app", None)
        join_fn = (
            getattr(app_obj, "join_speech_thread", None)
            if app_obj and app_obj is not self
            else None
        )
        if callable(join_fn):
            try:
                join_fn(timeout=timeout)
            except Exception:
                pass

    def on_unmount(self) -> None:
        """Lifecycle hook called when component is unmounted from Textual app."""
        self.join_speech_thread(timeout=0.5)
        unmount_fn = getattr(super(), "on_unmount", None)
        if callable(unmount_fn):
            try:
                unmount_fn()
            except Exception:
                pass

    def _speech_enabled(self) -> bool:
        """Return whether the user opted in to spoken status messages."""
        settings = getattr(self, "settings", None)
        try:
            return bool(getattr(settings, "SPEAK_ANNOUNCEMENTS", False))
        except Exception:
            return False

    def _get_speech_binary(self) -> str | None:
        """Resolve available speech synthesis executable based on host platform.

        On macOS, returns native 'say' command path. On Linux, returns 'spd-say' or
        'say' path. On Windows (win32), returns None as Linux/macOS speech binaries
        do not exist natively, defaulting to visual status live region fallback.
        """
        try:
            if sys.platform == "darwin":
                return shutil.which("say")
            elif sys.platform == "win32":
                return None
            else:
                return shutil.which("spd-say") or shutil.which("say")
        except (FileNotFoundError, OSError):
            return None

    def announce(
        self,
        message: str,
        priority: str = "polite",
        help_url: str | None = None,
    ) -> str:
        """Emit auditory screen reader announcement and log accessibility event."""
        if message is None:
            message = ""
        else:
            try:
                s_msg = str(message)
                message = (
                    sanitize_secret_patterns(scrub_user_home_paths(s_msg))
                    if s_msg
                    else ""
                )
            except Exception:
                try:
                    message = str(message)
                except Exception:
                    message = ""

        full_msg = (
            f"{message} [Help: {help_url}]"
            if help_url and help_url not in message
            else message
        )
        entry = {
            "message": full_msg,
            "priority": priority,
            "timestamp": time.time(),
            "help_url": help_url,
        }
        self.announcements.append(entry)
        self.last_announcement = full_msg

        forwarded = False
        # Forward to parent app if available
        try:
            app_obj = getattr(self, "_app", None) or getattr(self, "app", None)
            if app_obj and app_obj is not self and hasattr(app_obj, "announce"):
                app_obj.announce(message, priority=priority, help_url=help_url)
                forwarded = True
        except Exception:
            pass

        if not forwarded:
            # Speaking aloud is opt-in: screen-reader users already hear the
            # status bar, and everyone else should not hear every message.
            speech_bin = self._get_speech_binary() if self._speech_enabled() else None

            if speech_bin:
                speech_thread = self._speech_thread
                if speech_thread is None or not speech_thread.is_alive():
                    try:

                        def _speak():
                            try:
                                kwargs: dict[str, Any] = {
                                    "timeout": 1.0,
                                    "stdin": subprocess.DEVNULL,
                                    "stdout": subprocess.DEVNULL,
                                    "stderr": subprocess.DEVNULL,
                                    "check": False,
                                }
                                if sys.platform == "win32":
                                    kwargs["creationflags"] = getattr(
                                        subprocess, "CREATE_NO_WINDOW", 0
                                    )
                                subprocess.run(
                                    [speech_bin, message],
                                    **kwargs,
                                )
                            except BaseException as exc:
                                logger.debug(
                                    f"Speech synthesis execution failed: {exc}"
                                )
                            finally:
                                if (
                                    getattr(self, "_speech_thread", None)
                                    is threading.current_thread()
                                ):
                                    self._speech_thread = None

                        t = threading.Thread(target=_speak, daemon=True)
                        t.start()
                        self._speech_thread = t
                    except Exception as e:
                        logger.debug(f"Speech binary execution failed: {e}")

            # Fallback and update visual status region for every invocation
            if hasattr(self, "update_status") and callable(self.update_status):
                try:
                    self.update_status(message)
                except Exception:
                    pass

        return message

    def get_last_announcement(self) -> str | None:
        """Get the most recent screen reader announcement text."""
        return self.last_announcement

    def audit_a11y_compliance(self) -> dict[str, Any]:
        """Audit WCAG 2.1 accessibility compliance for this TUI component.

        Verifies:
        1. Interactive controls have tooltips or explicit accessibility labels.
        2. Modal screens define Escape key bindings for keyboard dismissal.
        3. Screen reader announcement logging capability exists.
        4. Root application defines visual status region capabilities and speech binary fallback handling.
        """
        violations = []

        try:
            query_fn = getattr(self, "query", None)
            widgets = list(query_fn("*")) if callable(query_fn) else []
            for widget in widgets:
                w_type = type(widget).__name__
                if w_type in (
                    "Input",
                    "Button",
                    "Select",
                    "Switch",
                    "Tree",
                    "Log",
                    "DensitySlider",
                ):
                    has_tooltip = bool(getattr(widget, "tooltip", None))
                    has_label = bool(
                        getattr(widget, "label", None)
                        or getattr(widget, "_text", None)
                        or (
                            getattr(widget, "value", None)
                            if w_type not in ("DensitySlider", "Input")
                            else None
                        )
                        or getattr(widget, "placeholder", None)
                        or getattr(widget, "prompt", None)
                    )
                    if not (has_tooltip or has_label):
                        violations.append(
                            {
                                "rule": "A11Y001_MISSING_LABEL",
                                "widget_id": getattr(widget, "id", None) or w_type,
                                "message": f"Interactive control '{w_type}' lacks explicit tooltip or accessible text label.",
                            }
                        )
        except Exception:
            pass

        if isinstance(self, ModalScreen):
            bindings = getattr(self, "BINDINGS", [])
            has_escape = any(
                getattr(b, "key", None) == "escape"
                or (isinstance(b, Binding) and b.key == "escape")
                for b in bindings
            )
            if not has_escape:
                violations.append(
                    {
                        "rule": "A11Y_MISSING_ESCAPE_BINDING",
                        "message": f"Modal screen '{type(self).__name__}' lacks Escape key binding for accessibility dismissal.",
                    }
                )

        if not hasattr(self, "announce") or not hasattr(self, "announcements"):
            violations.append(
                {
                    "rule": "A11Y_MISSING_ANNOUNCER",
                    "message": f"Component '{type(self).__name__}' lacks screen reader announcement handler.",
                }
            )

        status_bar_available = hasattr(self, "update_status") or (
            hasattr(self, "app") and self.app and hasattr(self.app, "update_status")
        )
        if not status_bar_available:
            violations.append(
                {
                    "rule": "A11Y_MISSING_STATUS_REGION",
                    "message": f"Component '{type(self).__name__}' or root application lacks visual status region capability.",
                }
            )

        try:
            query_fn = getattr(self, "query", None)
            nodes = list(query_fn("*")) if callable(query_fn) else []
            if nodes:
                headings = [
                    w for w in nodes if isinstance(w, Heading) or hasattr(w, "level")
                ]
                if isinstance(self, ModalScreen):
                    has_h1 = any(getattr(h, "level", None) == 1 for h in headings)
                    if not has_h1:
                        violations.append(
                            {
                                "rule": "A11Y_MISSING_MODAL_H1_HEADING",
                                "message": f"Modal screen '{type(self).__name__}' lacks a top-level semantic h1 heading.",
                            }
                        )
                elif isinstance(self, (App, Screen)):
                    has_h1 = any(getattr(h, "level", None) == 1 for h in headings)
                    if not has_h1:
                        violations.append(
                            {
                                "rule": "A11Y_MISSING_ROOT_H1_HEADING",
                                "message": f"Root screen '{type(self).__name__}' lacks a top-level semantic h1 heading.",
                            }
                        )
                levels = [
                    getattr(h, "level", 1) for h in headings if hasattr(h, "level")
                ]
                prev_level = 0
                for lvl in levels:
                    if lvl > prev_level + 1 and prev_level > 0:
                        violations.append(
                            {
                                "rule": "A11Y_HEADING_HIERARCHY_GAP",
                                "message": f"Heading hierarchy gap detected in '{type(self).__name__}': jumped from h{prev_level} to h{lvl}.",
                            }
                        )
                    prev_level = lvl
        except Exception:
            pass

        speech_binary = self._get_speech_binary()

        return {
            "component": type(self).__name__,
            "compliant": len(violations) == 0,
            "violations_count": len(violations),
            "violations": violations,
            "speech_binary_available": speech_binary is not None,
            "speech_binary": speech_binary,
            "speech_binary_fallback_ready": True,
            "status_bar_available": status_bar_available,
        }

    HELP_URL: str = TROUBLESHOOTING_URL

    def _call_ui(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> None:
        """Safely dispatch a UI callback onto the main Textual thread."""
        app_obj = None
        try:
            app_obj = getattr(self, "app", None)
        except Exception:
            app_obj = None

        if (
            app_obj is not None
            and app_obj is not self
            and hasattr(app_obj, "call_from_thread")
        ):
            thread_id = getattr(app_obj, "_thread_id", None)
            if not isinstance(thread_id, int) or thread_id != threading.get_ident():
                try:
                    app_obj.call_from_thread(func, *args, **kwargs)
                    return
                except Exception as exc:
                    logger.debug(f"call_from_thread failed: {exc}")

        try:
            func(*args, **kwargs)
        except Exception as exc:
            logger.debug(f"Direct UI function call failed: {exc}")

    def _show_help_button(self, help_url: str) -> None:
        """Show the Help button and record contextual help_url."""
        self.help_url = help_url

        def _unhide() -> None:
            try:
                query_one_fn = getattr(self, "query_one", None)
                if callable(query_one_fn):
                    btn = query_one_fn("#btn-help", Button)
                    btn.remove_class("hidden")
            except Exception:
                pass

        self._call_ui(_unhide)

    @on(Button.Pressed, "#btn-help")
    def action_help(self) -> None:
        """Open offline contextual troubleshooting help modal for this screen."""
        url = (
            getattr(self, "help_url", None)
            or getattr(self, "HELP_URL", None)
            or TROUBLESHOOTING_URL
        )
        self.open_help_section(url)

    def open_help_section(self, help_url: str | None = None) -> None:
        """Open local offline troubleshooting help modal for ``help_url``."""
        from app.ui.modals.help import TroubleshootingHelpModal

        target_url = (
            help_url
            or getattr(self, "help_url", None)
            or getattr(self, "HELP_URL", None)
            or TROUBLESHOOTING_URL
        )
        self.announce(f"Opened documentation link: {target_url}")

        app_obj = self._resolve_app_instance()
        push_fn = getattr(app_obj, "push_screen", None) if app_obj is not None else None
        if callable(push_fn):
            try:
                push_fn(TroubleshootingHelpModal(help_url=target_url))
            except Exception:
                logger.debug("Failed pushing TroubleshootingHelpModal", exc_info=True)

action_help()

Open offline contextual troubleshooting help modal for this screen.

Source code in app/ui/a11y.py
447
448
449
450
451
452
453
454
455
@on(Button.Pressed, "#btn-help")
def action_help(self) -> None:
    """Open offline contextual troubleshooting help modal for this screen."""
    url = (
        getattr(self, "help_url", None)
        or getattr(self, "HELP_URL", None)
        or TROUBLESHOOTING_URL
    )
    self.open_help_section(url)

action_open_help_overlay(from_character=False)

Open keyboard shortcut cheat sheet overlay lazily from any screen or modal.

Source code in app/ui/a11y.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def action_open_help_overlay(self, from_character: bool = False) -> None:
    """Open keyboard shortcut cheat sheet overlay lazily from any screen or modal."""
    if from_character and (
        self._is_character_input_focused()
        or not self._character_shortcuts_enabled()
    ):
        return
    from app.ui.modals.help import ShortcutCheatSheetModal

    app_obj = self._resolve_app_instance()
    if app_obj is None:
        return
    if isinstance(getattr(app_obj, "screen", None), ShortcutCheatSheetModal):
        return
    push_fn = getattr(app_obj, "push_screen", None)
    if callable(push_fn):
        push_fn(ShortcutCheatSheetModal())

announce(message, priority='polite', help_url=None)

Emit auditory screen reader announcement and log accessibility event.

Source code in app/ui/a11y.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
def announce(
    self,
    message: str,
    priority: str = "polite",
    help_url: str | None = None,
) -> str:
    """Emit auditory screen reader announcement and log accessibility event."""
    if message is None:
        message = ""
    else:
        try:
            s_msg = str(message)
            message = (
                sanitize_secret_patterns(scrub_user_home_paths(s_msg))
                if s_msg
                else ""
            )
        except Exception:
            try:
                message = str(message)
            except Exception:
                message = ""

    full_msg = (
        f"{message} [Help: {help_url}]"
        if help_url and help_url not in message
        else message
    )
    entry = {
        "message": full_msg,
        "priority": priority,
        "timestamp": time.time(),
        "help_url": help_url,
    }
    self.announcements.append(entry)
    self.last_announcement = full_msg

    forwarded = False
    # Forward to parent app if available
    try:
        app_obj = getattr(self, "_app", None) or getattr(self, "app", None)
        if app_obj and app_obj is not self and hasattr(app_obj, "announce"):
            app_obj.announce(message, priority=priority, help_url=help_url)
            forwarded = True
    except Exception:
        pass

    if not forwarded:
        # Speaking aloud is opt-in: screen-reader users already hear the
        # status bar, and everyone else should not hear every message.
        speech_bin = self._get_speech_binary() if self._speech_enabled() else None

        if speech_bin:
            speech_thread = self._speech_thread
            if speech_thread is None or not speech_thread.is_alive():
                try:

                    def _speak():
                        try:
                            kwargs: dict[str, Any] = {
                                "timeout": 1.0,
                                "stdin": subprocess.DEVNULL,
                                "stdout": subprocess.DEVNULL,
                                "stderr": subprocess.DEVNULL,
                                "check": False,
                            }
                            if sys.platform == "win32":
                                kwargs["creationflags"] = getattr(
                                    subprocess, "CREATE_NO_WINDOW", 0
                                )
                            subprocess.run(
                                [speech_bin, message],
                                **kwargs,
                            )
                        except BaseException as exc:
                            logger.debug(
                                f"Speech synthesis execution failed: {exc}"
                            )
                        finally:
                            if (
                                getattr(self, "_speech_thread", None)
                                is threading.current_thread()
                            ):
                                self._speech_thread = None

                    t = threading.Thread(target=_speak, daemon=True)
                    t.start()
                    self._speech_thread = t
                except Exception as e:
                    logger.debug(f"Speech binary execution failed: {e}")

        # Fallback and update visual status region for every invocation
        if hasattr(self, "update_status") and callable(self.update_status):
            try:
                self.update_status(message)
            except Exception:
                pass

    return message

audit_a11y_compliance()

Audit WCAG 2.1 accessibility compliance for this TUI component.

Verifies: 1. Interactive controls have tooltips or explicit accessibility labels. 2. Modal screens define Escape key bindings for keyboard dismissal. 3. Screen reader announcement logging capability exists. 4. Root application defines visual status region capabilities and speech binary fallback handling.

Source code in app/ui/a11y.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
def audit_a11y_compliance(self) -> dict[str, Any]:
    """Audit WCAG 2.1 accessibility compliance for this TUI component.

    Verifies:
    1. Interactive controls have tooltips or explicit accessibility labels.
    2. Modal screens define Escape key bindings for keyboard dismissal.
    3. Screen reader announcement logging capability exists.
    4. Root application defines visual status region capabilities and speech binary fallback handling.
    """
    violations = []

    try:
        query_fn = getattr(self, "query", None)
        widgets = list(query_fn("*")) if callable(query_fn) else []
        for widget in widgets:
            w_type = type(widget).__name__
            if w_type in (
                "Input",
                "Button",
                "Select",
                "Switch",
                "Tree",
                "Log",
                "DensitySlider",
            ):
                has_tooltip = bool(getattr(widget, "tooltip", None))
                has_label = bool(
                    getattr(widget, "label", None)
                    or getattr(widget, "_text", None)
                    or (
                        getattr(widget, "value", None)
                        if w_type not in ("DensitySlider", "Input")
                        else None
                    )
                    or getattr(widget, "placeholder", None)
                    or getattr(widget, "prompt", None)
                )
                if not (has_tooltip or has_label):
                    violations.append(
                        {
                            "rule": "A11Y001_MISSING_LABEL",
                            "widget_id": getattr(widget, "id", None) or w_type,
                            "message": f"Interactive control '{w_type}' lacks explicit tooltip or accessible text label.",
                        }
                    )
    except Exception:
        pass

    if isinstance(self, ModalScreen):
        bindings = getattr(self, "BINDINGS", [])
        has_escape = any(
            getattr(b, "key", None) == "escape"
            or (isinstance(b, Binding) and b.key == "escape")
            for b in bindings
        )
        if not has_escape:
            violations.append(
                {
                    "rule": "A11Y_MISSING_ESCAPE_BINDING",
                    "message": f"Modal screen '{type(self).__name__}' lacks Escape key binding for accessibility dismissal.",
                }
            )

    if not hasattr(self, "announce") or not hasattr(self, "announcements"):
        violations.append(
            {
                "rule": "A11Y_MISSING_ANNOUNCER",
                "message": f"Component '{type(self).__name__}' lacks screen reader announcement handler.",
            }
        )

    status_bar_available = hasattr(self, "update_status") or (
        hasattr(self, "app") and self.app and hasattr(self.app, "update_status")
    )
    if not status_bar_available:
        violations.append(
            {
                "rule": "A11Y_MISSING_STATUS_REGION",
                "message": f"Component '{type(self).__name__}' or root application lacks visual status region capability.",
            }
        )

    try:
        query_fn = getattr(self, "query", None)
        nodes = list(query_fn("*")) if callable(query_fn) else []
        if nodes:
            headings = [
                w for w in nodes if isinstance(w, Heading) or hasattr(w, "level")
            ]
            if isinstance(self, ModalScreen):
                has_h1 = any(getattr(h, "level", None) == 1 for h in headings)
                if not has_h1:
                    violations.append(
                        {
                            "rule": "A11Y_MISSING_MODAL_H1_HEADING",
                            "message": f"Modal screen '{type(self).__name__}' lacks a top-level semantic h1 heading.",
                        }
                    )
            elif isinstance(self, (App, Screen)):
                has_h1 = any(getattr(h, "level", None) == 1 for h in headings)
                if not has_h1:
                    violations.append(
                        {
                            "rule": "A11Y_MISSING_ROOT_H1_HEADING",
                            "message": f"Root screen '{type(self).__name__}' lacks a top-level semantic h1 heading.",
                        }
                    )
            levels = [
                getattr(h, "level", 1) for h in headings if hasattr(h, "level")
            ]
            prev_level = 0
            for lvl in levels:
                if lvl > prev_level + 1 and prev_level > 0:
                    violations.append(
                        {
                            "rule": "A11Y_HEADING_HIERARCHY_GAP",
                            "message": f"Heading hierarchy gap detected in '{type(self).__name__}': jumped from h{prev_level} to h{lvl}.",
                        }
                    )
                prev_level = lvl
    except Exception:
        pass

    speech_binary = self._get_speech_binary()

    return {
        "component": type(self).__name__,
        "compliant": len(violations) == 0,
        "violations_count": len(violations),
        "violations": violations,
        "speech_binary_available": speech_binary is not None,
        "speech_binary": speech_binary,
        "speech_binary_fallback_ready": True,
        "status_bar_available": status_bar_available,
    }

check_action(action, parameters)

Gate character-triggered help overlay bindings on shortcut setting.

Source code in app/ui/a11y.py
64
65
66
67
68
69
70
71
72
def check_action(self, action: str, parameters: tuple[object, ...]) -> bool | None:
    """Gate character-triggered help overlay bindings on shortcut setting."""
    if action == "open_help_overlay" and parameters and parameters[0] is True:
        if not self._character_shortcuts_enabled():
            return False
    check_fn = getattr(super(), "check_action", None)
    if callable(check_fn):
        return check_fn(action, parameters)
    return True

get_last_announcement()

Get the most recent screen reader announcement text.

Source code in app/ui/a11y.py
264
265
266
def get_last_announcement(self) -> str | None:
    """Get the most recent screen reader announcement text."""
    return self.last_announcement

join_speech_thread(timeout=1.0)

Wait for active speech synthesis thread to finish.

Source code in app/ui/a11y.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def join_speech_thread(self, timeout: float = 1.0) -> None:
    """Wait for active speech synthesis thread to finish."""
    speech_thread = self._speech_thread
    if speech_thread is not None:
        if speech_thread.is_alive():
            try:
                speech_thread.join(timeout=timeout)
            except Exception:
                pass
        if not speech_thread.is_alive():
            self._speech_thread = None
    app_obj = getattr(self, "app", None)
    join_fn = (
        getattr(app_obj, "join_speech_thread", None)
        if app_obj and app_obj is not self
        else None
    )
    if callable(join_fn):
        try:
            join_fn(timeout=timeout)
        except Exception:
            pass

on_unmount()

Lifecycle hook called when component is unmounted from Textual app.

Source code in app/ui/a11y.py
129
130
131
132
133
134
135
136
137
def on_unmount(self) -> None:
    """Lifecycle hook called when component is unmounted from Textual app."""
    self.join_speech_thread(timeout=0.5)
    unmount_fn = getattr(super(), "on_unmount", None)
    if callable(unmount_fn):
        try:
            unmount_fn()
        except Exception:
            pass

open_help_section(help_url=None)

Open local offline troubleshooting help modal for help_url.

Source code in app/ui/a11y.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
def open_help_section(self, help_url: str | None = None) -> None:
    """Open local offline troubleshooting help modal for ``help_url``."""
    from app.ui.modals.help import TroubleshootingHelpModal

    target_url = (
        help_url
        or getattr(self, "help_url", None)
        or getattr(self, "HELP_URL", None)
        or TROUBLESHOOTING_URL
    )
    self.announce(f"Opened documentation link: {target_url}")

    app_obj = self._resolve_app_instance()
    push_fn = getattr(app_obj, "push_screen", None) if app_obj is not None else None
    if callable(push_fn):
        try:
            push_fn(TroubleshootingHelpModal(help_url=target_url))
        except Exception:
            logger.debug("Failed pushing TroubleshootingHelpModal", exc_info=True)

update_status(text)

Update visual status region on self or parent application.

Source code in app/ui/a11y.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def update_status(self, text: str) -> None:
    """Update visual status region on self or parent application."""
    try:
        app_obj = getattr(self, "app", None)
        update_fn = (
            getattr(app_obj, "update_status", None)
            if app_obj and app_obj is not self
            else None
        )
        if callable(update_fn):
            update_fn(text)
    except Exception:
        pass

A11yViolation dataclass

Representation of an accessibility violation in a TUI component.

Source code in app/ui/a11y.py
478
479
480
481
482
483
484
485
486
487
488
@dataclass
class A11yViolation:
    """Representation of an accessibility violation in a TUI component."""

    rule_id: str
    component_id: str
    component_name: str
    viewport_name: str
    viewport_width: int
    locator: str
    message: str

inspect_tui_component(component)

Inspect a TUI App or Modal component for WCAG 2.1 accessibility compliance.

Leverages the component's internal audit hook method 'audit_a11y_compliance' to perform programmatic verification.

Source code in app/ui/a11y.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
def inspect_tui_component(component: Any) -> list[A11yViolation]:
    """Inspect a TUI App or Modal component for WCAG 2.1 accessibility compliance.

    Leverages the component's internal audit hook method 'audit_a11y_compliance'
    to perform programmatic verification.
    """
    violations: list[A11yViolation] = []
    comp_name = type(component).__name__

    if hasattr(component, "audit_a11y_compliance") and callable(
        component.audit_a11y_compliance
    ):
        res = component.audit_a11y_compliance()
        for v in res.get("violations", []):
            violations.append(
                A11yViolation(
                    rule_id=v.get("rule", "A11Y_UNKNOWN"),
                    component_id=comp_name,
                    component_name=comp_name,
                    viewport_name="terminal",
                    viewport_width=80,
                    locator=v.get("widget_id", comp_name),
                    message=v.get("message", "A11y violation detected"),
                )
            )

    return violations

app.ui.ai_runtime

app.ui.ai_runtime

TUI AI runtime polling and safe mock-session auto-rescan helpers.

compute_ai_poll_token(host)

Build an in-memory token of consent, ONNX readiness, and DownloadManager state without disk stat calls.

Source code in app/ui/ai_runtime.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def compute_ai_poll_token(host: Any) -> tuple[Any, ...]:
    """Build an in-memory token of consent, ONNX readiness, and DownloadManager state without disk stat calls."""
    consent = getattr(host.settings, "AI_CONSENT_GRANTED", None) is True
    onnx_ready = _downloader.is_onnxruntime_available()
    reg = SharedModelRegistry._instance
    onnx_health = (
        str(reg.get_model_health("onnx_embeddings").get("status", ""))
        if reg is not None
        else ""
    )
    dm = _downloader.DownloadManager._instance
    if dm is None:
        return (0, consent, onnx_ready, onnx_health, "IDLE", False, 0, "")
    is_downloading = bool(dm.state.get("is_downloading", False))
    raw_progress = float(dm.state.get("progress", 0.0) or 0.0)
    pct = int(round(min(100.0, max(0.0, raw_progress * 100.0))))
    err = str(dm.state.get("error") or "")
    return (
        id(dm),
        consent,
        onnx_ready,
        onnx_health,
        str(dm.status),
        is_downloading,
        pct,
        err,
    )

is_mock_or_degraded_session(host)

Return True when an existing scan session or plan used mock/TF-IDF fallback embeddings.

Source code in app/ui/ai_runtime.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def is_mock_or_degraded_session(host: Any) -> bool:
    """Return True when an existing scan session or plan used mock/TF-IDF fallback embeddings."""
    session = getattr(host, "app_session", None)
    plan = getattr(host, "plan", {})
    has_files = (
        bool(host._has_file_nodes(plan))
        if hasattr(host, "_has_file_nodes")
        else bool(plan)
    )
    if session is None and not has_files:
        return False
    if session is not None:
        if getattr(session, "is_mock", False):
            return True
        analyzer = getattr(session, "analyzer", None)
        emb = getattr(analyzer, "embedding_manager", None)
        if emb is not None:
            if getattr(emb, "is_mock", False) or getattr(emb, "is_degraded", False):
                return True
            return False

    from app.core.shared_registry import SharedModelRegistry

    registry = SharedModelRegistry._instance
    if registry is not None:
        onnx_health = registry.get_model_health("onnx_embeddings")
        if onnx_health.get("status") in ("DEGRADED_FALLBACK", "FAILED"):
            return True
        gen_health = registry.get_model_health("generative_naming")
        if gen_health.get("status") in ("DEGRADED_FALLBACK", "FAILED"):
            return False

    recovery_action = getattr(plan, "recovery_action", None)
    if recovery_action is None and isinstance(plan, dict):
        recovery_action = plan.get("recovery_action")
    if recovery_action == "CONFIGURE_GENERATIVE_MODEL":
        return False

    model_status = getattr(plan, "model_status", None)
    if model_status is None and isinstance(plan, dict):
        model_status = plan.get("model_status")
    return model_status == "DEGRADED_FALLBACK"

plan_has_manual_modifications(host)

Return True if the current plan has manual edits, empty folders, locks, or manual exclusions.

Source code in app/ui/ai_runtime.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def plan_has_manual_modifications(host: Any) -> bool:
    """Return True if the current plan has manual edits, empty folders, locks, or manual exclusions."""
    if (
        bool(getattr(host, "_manual_plan_edits", None))
        or bool(getattr(host, "_manual_empty_folders", None))
        or bool(getattr(host, "locked_files", None))
    ):
        return True

    raw_plan = getattr(host, "plan", None)
    plan_tree = getattr(raw_plan, "plan_tree", None)
    if plan_tree is None:
        plan_tree = getattr(raw_plan, "nodes", None)
    if plan_tree is None:
        plan_tree = getattr(raw_plan, "plan", raw_plan)
    if not isinstance(plan_tree, dict):
        return False

    if collect_empty_plan_folders(plan_tree):
        return True

    def _has_node_override(tree: dict[str, Any]) -> bool:
        for name, node in tree.items():
            if str(name).startswith("__") or not isinstance(node, dict):
                continue
            if _is_leaf_file_entry(node):
                is_auto_skipped_duplicate = (
                    bool(node.get("is_duplicate"))
                    and node.get("duplicate_action") == "skip"
                    and bool(node.get("duplicate_resolved"))
                )
                has_manual_exclusion = (
                    bool(node.get("is_excluded")) or node.get("is_checked") is False
                ) and not is_auto_skipped_duplicate
                if (
                    bool(node.get("is_locked"))
                    or bool(node.get("locked"))
                    or bool(node.get("confirmed"))
                    or bool(node.get("destination_override"))
                    or bool(node.get("is_overridden"))
                    or bool(node.get("manual_edit"))
                    or bool(node.get("excluded"))
                    or has_manual_exclusion
                ):
                    return True
            elif not _is_plan_leaf_node(node) and _has_node_override(node):
                return True
        return False

    return _has_node_override(plan_tree)

poll_ai_provisioning_status(host)

Poll background model download and verification state to refresh status bar badges.

Source code in app/ui/ai_runtime.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
def poll_ai_provisioning_status(host: Any) -> None:
    """Poll background model download and verification state to refresh status bar badges."""
    try:
        poll_token = host._compute_ai_poll_token()
        if (
            getattr(host, "_last_ai_badge", None) is not None
            and getattr(host, "_last_ai_poll_token", None) == poll_token
        ):
            return

        prev_badge = getattr(host, "_last_ai_badge", None)
        prev_state = getattr(host, "_last_ai_state", None)
        runtime = _downloader.get_ai_runtime_state(host.settings)
        new_badge = str(runtime["badge"])
        new_state = str(runtime["state"])
        host._last_ai_badge = new_badge
        host._last_ai_state = new_state
        host._last_ai_poll_token = host._compute_ai_poll_token()

        if prev_badge is not None and prev_badge != new_badge:
            host.update_status()
        if prev_state is not None and prev_state != "active" and new_state == "active":
            if prev_state == "downloading":
                host.announce(
                    "AI model weights verified and active.",
                    priority="polite",
                )
            if host._running_pipeline_worker() == "run_scan_worker":
                host._pending_ai_active_rescan = True
            else:
                host._trigger_ai_active_rescan_if_eligible()
        elif (
            prev_state == "downloading"
            and new_state == "fallback"
            and runtime.get("error")
        ):
            host.announce(
                f"AI model download failed ({runtime['error']}). Using local keyword fallback.",
                priority="assertive",
            )
    except (
        OSError,
        RuntimeError,
        ValueError,
        TypeError,
        AttributeError,
        KeyError,
    ) as exc:
        logger.debug("AI provisioning status poll error: %s", exc)

should_auto_rescan_mock_session(host)

Return True if an unedited mock/fallback plan can be safely upgraded with active AI embeddings.

Source code in app/ui/ai_runtime.py
161
162
163
164
165
166
167
168
169
170
171
172
173
def should_auto_rescan_mock_session(host: Any) -> bool:
    """Return True if an unedited mock/fallback plan can be safely upgraded with active AI embeddings."""
    base_dir = getattr(host, "base_dir", None)
    s_dirs = getattr(host, "source_dirs", None) or ([base_dir] if base_dir else [])
    if not s_dirs or not any(os.path.exists(d) for d in s_dirs):
        return False
    if host._running_pipeline_worker() is not None or getattr(
        host, "_daemon_is_moving", False
    ):
        return False
    if not is_mock_or_degraded_session(host):
        return False
    return not plan_has_manual_modifications(host)

trigger_ai_active_rescan_if_eligible(host)

Re-scan an unedited mock session when verified AI weights and ONNX Runtime are active.

Source code in app/ui/ai_runtime.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def trigger_ai_active_rescan_if_eligible(host: Any) -> None:
    """Re-scan an unedited mock session when verified AI weights and ONNX Runtime are active."""
    host._pending_ai_active_rescan = False
    if _downloader.get_ai_runtime_state(host.settings).get("state") != "active":
        return
    base_dir = getattr(host, "base_dir", None)
    if not getattr(host, "source_dirs", None) and base_dir:
        host.source_dirs = [base_dir]
    if should_auto_rescan_mock_session(host):
        host.announce(
            "Upgrading unedited sorting plan with verified AI embeddings...",
            priority="polite",
        )
        host._start_scan()

app.ui.catalog

app.ui.catalog

Standalone Component Catalog and Accessibility Gate Module for Textual TUI.

Provides a registry of active Textual screens and modals, and CLI entry points for inspecting components and running automated accessibility audits via inspect_tui_component.

get_catalog_registry()

Return list of registered catalog component definitions.

Source code in app/ui/catalog.py
434
435
436
def get_catalog_registry() -> list[dict[str, Any]]:
    """Return list of registered catalog component definitions."""
    return CATALOG_REGISTRY

main(argv=None)

CLI launcher and accessibility gate handler for Component Catalog.

Source code in app/ui/catalog.py
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
def main(argv: list[str] | None = None) -> int:
    """CLI launcher and accessibility gate handler for Component Catalog."""
    parser = argparse.ArgumentParser(
        description="Standalone Textual TUI Component Catalog & Accessibility Gate"
    )
    parser.add_argument(
        "--audit-only",
        action="store_true",
        help="Execute headless accessibility scans against registered TUI components and exit",
    )
    parser.add_argument(
        "--component",
        type=str,
        default=None,
        help="Target component ID or name to inspect or audit",
    )
    parser.add_argument(
        "--list",
        action="store_true",
        help="List all registered catalog components and exit",
    )

    args = parser.parse_args(argv)

    if args.list:
        print("=== Registered Textual TUI Component Catalog ===")
        print(f"{'ID':<30} | {'Type':<8} | {'Name':<35}")
        print("-" * 80)
        for comp in CATALOG_REGISTRY:
            print(f"{comp['id']:<30} | {comp['category']:<8} | {comp['name']:<35}")
        print(f"\nTotal components registered: {len(CATALOG_REGISTRY)}")
        return 0

    if args.audit_only:
        print("Starting headless Textual TUI accessibility audit...")
        with _headless_keyring_guard():
            try:
                total_scans, violations = run_catalog_audit(component_id=args.component)
            except ValueError as err:
                print(f"Error: {err}", file=sys.stderr)
                return 1
            except Exception as err:  # noqa: BLE001
                print(f"Audit execution error: {err}", file=sys.stderr)
                return 1

        if violations:
            print(
                f"\nFAILED: Found {len(violations)} accessibility violation(s) across {total_scans} scanned component(s).",
                file=sys.stderr,
            )
            for v in violations:
                print(
                    f"  [{v.rule_id}] Component '{v.component_id}': {v.message} (locator: {v.locator})",
                    file=sys.stderr,
                )
            return 1
        else:
            print(
                f"\nSUCCESS: All {total_scans} TUI component accessibility scan(s) passed with 0 violations."
            )
            return 0

    # Interactive launch mode
    settings = _build_default_settings()
    if args.component:
        norm_id = args.component.strip().lower()
        matched = [
            c
            for c in CATALOG_REGISTRY
            if c["id"].lower() == norm_id or c["name"].lower() == norm_id
        ]
        if not matched:
            print(
                f"Error: Unknown component identifier: '{args.component}'",
                file=sys.stderr,
            )
            return 1
        comp_def = matched[0]
        comp_instance = comp_def["factory"](settings=settings)
        if comp_def["id"] == "autosorter_tui":
            comp_instance.run()
        else:
            app = AutoSorterTUI(settings=settings)

            def _on_mount() -> None:
                app.push_screen(comp_instance)

            app.on_mount = _on_mount
            app.run()
        return 0

    app = AutoSorterTUI(settings=settings)
    app.run()
    return 0

run_catalog_audit(component_id=None, settings=None)

Execute headless accessibility audit against all or specified component(s).

Source code in app/ui/catalog.py
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
def run_catalog_audit(
    component_id: str | None = None, settings: AppSettings | None = None
) -> tuple[int, list[A11yViolation]]:
    """Execute headless accessibility audit against all or specified component(s)."""
    with _headless_keyring_guard():
        settings_obj = settings or _build_default_settings()
        registry = get_catalog_registry()

        if component_id:
            norm_id = component_id.strip().lower()
            filtered = [
                c
                for c in registry
                if c["id"].lower() == norm_id or c["name"].lower() == norm_id
            ]
            if not filtered:
                raise ValueError(f"Unknown component identifier: '{component_id}'")
            target_components = filtered
        else:
            target_components = registry

        return asyncio.run(_audit_components_async(target_components, settings_obj))

app.ui.heading

app.ui.heading

Centralized native semantic heading helper module for accessible TUI and GUI views.

Heading

Bases: Label

Native semantic heading element providing WCAG 2.1 compliance.

Renders screen headers, modal dialog titles, and card section headers with explicit semantic levels (h1 through h6), role attributes, and reactive update capabilities while preserving Rich/Textual visual layout and styling.

Source code in app/ui/heading.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class Heading(Label):
    """Native semantic heading element providing WCAG 2.1 compliance.

    Renders screen headers, modal dialog titles, and card section headers with explicit
    semantic levels (h1 through h6), role attributes, and reactive update capabilities
    while preserving Rich/Textual visual layout and styling.
    """

    level = reactive(1)

    def __init__(
        self,
        content: RenderableType = "",
        level: int = 1,
        *,
        expand: bool = False,
        shrink: bool = False,
        markup: bool = True,
        name: str | None = None,
        id: str | None = None,
        classes: str | None = None,
        disabled: bool = False,
        tooltip: RenderableType | None = None,
    ) -> None:
        clamped_level = max(1, min(6, int(level)))
        super().__init__(
            content,
            expand=expand,
            shrink=shrink,
            markup=markup,
            name=name,
            id=id,
            classes=classes,
            disabled=disabled,
        )
        self.level = clamped_level
        if tooltip is not None:
            self.tooltip = tooltip

    def validate_level(self, value: int) -> int:
        """Validate and clamp heading level between 1 (h1) and 6 (h6)."""
        return max(1, min(6, int(value)))

    def watch_level(self, old_level: int, new_level: int) -> None:
        """Reactive watcher called when heading level changes."""
        self.refresh()

    @property
    def tag(self) -> str:
        """Return native HTML heading tag name (e.g., 'h1', 'h2')."""
        return f"h{self.level}"

    @property
    def role(self) -> str:
        """Return ARIA role for accessibility tree indexing."""
        return "heading"

    @property
    def aria_level(self) -> str:
        """Return string value of ARIA level attribute."""
        return str(self.level)

aria_level property

Return string value of ARIA level attribute.

role property

Return ARIA role for accessibility tree indexing.

tag property

Return native HTML heading tag name (e.g., 'h1', 'h2').

validate_level(value)

Validate and clamp heading level between 1 (h1) and 6 (h6).

Source code in app/ui/heading.py
49
50
51
def validate_level(self, value: int) -> int:
    """Validate and clamp heading level between 1 (h1) and 6 (h6)."""
    return max(1, min(6, int(value)))

watch_level(old_level, new_level)

Reactive watcher called when heading level changes.

Source code in app/ui/heading.py
53
54
55
def watch_level(self, old_level: int, new_level: int) -> None:
    """Reactive watcher called when heading level changes."""
    self.refresh()

create_heading(text='', level=1, classes=None, id=None, **kwargs)

Centralized helper function to generate reactive semantic Heading instances.

Source code in app/ui/heading.py
77
78
79
80
81
82
83
84
85
def create_heading(
    text: RenderableType = "",
    level: int = 1,
    classes: str | None = None,
    id: str | None = None,
    **kwargs: Any,
) -> Heading:
    """Centralized helper function to generate reactive semantic Heading instances."""
    return Heading(content=text, level=level, classes=classes, id=id, **kwargs)

app.ui.layout

app.ui.layout

Responsive layout behaviour and shared modal base screen for TUI dialogs.

ModalBox

Bases: Vertical

Modal outer container that forwards scroll helpers to an inner .modal-body.

Source code in app/ui/layout.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
class ModalBox(Vertical):
    """Modal outer container that forwards scroll helpers to an inner ``.modal-body``."""

    _explicit_scroll_seq: int = 0

    def _guard_explicit_scroll(
        self,
        targets: list[Widget],
        reapply: Any,
    ) -> None:
        """Cancel stale deferred initial-focus animations that fire after an explicit un-animated scroll."""
        self._explicit_scroll_seq += 1
        seq = self._explicit_scroll_seq

        def _make_checker(remaining: int) -> Any:
            def _check_and_reapply() -> None:
                if seq != self._explicit_scroll_seq or not self.is_mounted:
                    return
                animator = self.app.animator
                animated = [
                    t
                    for t in targets
                    if t.is_mounted
                    and (
                        animator.is_being_animated(t, "scroll_y")
                        or animator.is_being_animated(t, "scroll_x")
                    )
                ]
                if animated:
                    for t in animated:
                        t.scroll_to(
                            x=t.scroll_x,
                            y=t.scroll_y,
                            animate=False,
                            immediate=True,
                        )
                    reapply()
                if remaining > 1:
                    self.call_after_refresh(_make_checker(remaining - 1))

            return _check_and_reapply

        self.call_after_refresh(_make_checker(3))

    def _body_scroll_target(self, widget: Widget | None = None) -> Widget | None:
        """Return inner scrollable ``.modal-body`` when outer box itself does not scroll.

        Parameters
        ----------
        widget : Optional[Widget], optional
            Target descendant widget being scrolled into view.

        Returns
        -------
        Optional[Widget]
            Matching ``.modal-body`` container if separated, otherwise ``None``.
        """
        if self.max_scroll_y > 0:
            return None
        if widget is not None:
            for anc in widget.ancestors:
                if anc is self:
                    break
                if isinstance(anc, Widget) and "modal-body" in anc.classes:
                    return anc
        bodies = list(self.query(".modal-body"))
        for body in bodies:
            if body.display and all(anc.display for anc in body.ancestors):
                return body
        if bodies:
            return bodies[0]
        try:
            return self.query_one(".modal-body", Widget)
        except NoMatches:
            return None

    def scroll_to_widget(self, widget: Widget, *args: Any, **kwargs: Any) -> bool:
        """Scroll inner ``.modal-body`` to bring ``widget`` into view when separated.

        Parameters
        ----------
        widget : Widget
            Descendant widget to scroll into view.
        *args : Any
            Positional arguments forwarded to ``Widget.scroll_to_widget``.
        **kwargs : Any
            Keyword arguments forwarded to ``Widget.scroll_to_widget``.

        Returns
        -------
        bool
            True if scrolling was scheduled or performed.
        """
        is_unanimated = kwargs.get("animate") is False
        if is_unanimated and "immediate" not in kwargs:
            kwargs["immediate"] = True
        target = self._body_scroll_target(widget)
        if target is not None:
            res = target.scroll_to_widget(widget, *args, **kwargs)
            if is_unanimated:
                self._guard_explicit_scroll(
                    [target],
                    lambda: target.scroll_to_widget(widget, *args, **kwargs),
                )
            return res
        res = super().scroll_to_widget(widget, *args, **kwargs)
        if is_unanimated:
            self._guard_explicit_scroll(
                [self],
                lambda: ModalBox.scroll_to_widget(self, widget, *args, **kwargs),
            )
        return res

    def scroll_home(self, *args: Any, **kwargs: Any) -> None:
        """Scroll inner ``.modal-body`` to top when separated from pinned footer.

        Parameters
        ----------
        *args : Any
            Positional arguments forwarded to ``Widget.scroll_home``.
        **kwargs : Any
            Keyword arguments forwarded to ``Widget.scroll_home``.
        """
        is_unanimated = kwargs.get("animate") is False
        if is_unanimated and "immediate" not in kwargs:
            kwargs["immediate"] = True
        bodies = list(self.query(".modal-body"))
        if self.max_scroll_y <= 0 and bodies:
            for body in bodies:
                body.scroll_home(*args, **kwargs)
            if is_unanimated:
                self._guard_explicit_scroll(
                    bodies,
                    lambda: [
                        b.scroll_home(*args, **kwargs) for b in bodies if b.is_mounted
                    ],
                )
            return
        super().scroll_home(*args, **kwargs)
        if is_unanimated:
            self._guard_explicit_scroll(
                [self],
                lambda: Vertical.scroll_home(self, *args, **kwargs),
            )

scroll_home(*args, **kwargs)

Scroll inner .modal-body to top when separated from pinned footer.

Parameters:

Name Type Description Default
*args Any

Positional arguments forwarded to Widget.scroll_home.

()
**kwargs Any

Keyword arguments forwarded to Widget.scroll_home.

{}
Source code in app/ui/layout.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
def scroll_home(self, *args: Any, **kwargs: Any) -> None:
    """Scroll inner ``.modal-body`` to top when separated from pinned footer.

    Parameters
    ----------
    *args : Any
        Positional arguments forwarded to ``Widget.scroll_home``.
    **kwargs : Any
        Keyword arguments forwarded to ``Widget.scroll_home``.
    """
    is_unanimated = kwargs.get("animate") is False
    if is_unanimated and "immediate" not in kwargs:
        kwargs["immediate"] = True
    bodies = list(self.query(".modal-body"))
    if self.max_scroll_y <= 0 and bodies:
        for body in bodies:
            body.scroll_home(*args, **kwargs)
        if is_unanimated:
            self._guard_explicit_scroll(
                bodies,
                lambda: [
                    b.scroll_home(*args, **kwargs) for b in bodies if b.is_mounted
                ],
            )
        return
    super().scroll_home(*args, **kwargs)
    if is_unanimated:
        self._guard_explicit_scroll(
            [self],
            lambda: Vertical.scroll_home(self, *args, **kwargs),
        )

scroll_to_widget(widget, *args, **kwargs)

Scroll inner .modal-body to bring widget into view when separated.

Parameters:

Name Type Description Default
widget Widget

Descendant widget to scroll into view.

required
*args Any

Positional arguments forwarded to Widget.scroll_to_widget.

()
**kwargs Any

Keyword arguments forwarded to Widget.scroll_to_widget.

{}

Returns:

Type Description
bool

True if scrolling was scheduled or performed.

Source code in app/ui/layout.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def scroll_to_widget(self, widget: Widget, *args: Any, **kwargs: Any) -> bool:
    """Scroll inner ``.modal-body`` to bring ``widget`` into view when separated.

    Parameters
    ----------
    widget : Widget
        Descendant widget to scroll into view.
    *args : Any
        Positional arguments forwarded to ``Widget.scroll_to_widget``.
    **kwargs : Any
        Keyword arguments forwarded to ``Widget.scroll_to_widget``.

    Returns
    -------
    bool
        True if scrolling was scheduled or performed.
    """
    is_unanimated = kwargs.get("animate") is False
    if is_unanimated and "immediate" not in kwargs:
        kwargs["immediate"] = True
    target = self._body_scroll_target(widget)
    if target is not None:
        res = target.scroll_to_widget(widget, *args, **kwargs)
        if is_unanimated:
            self._guard_explicit_scroll(
                [target],
                lambda: target.scroll_to_widget(widget, *args, **kwargs),
            )
        return res
    res = super().scroll_to_widget(widget, *args, **kwargs)
    if is_unanimated:
        self._guard_explicit_scroll(
            [self],
            lambda: ModalBox.scroll_to_widget(self, widget, *args, **kwargs),
        )
    return res

ResponsiveLayoutMixin

Toggle narrow and compact classes across responsive breakpoints.

Source code in app/ui/layout.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
class ResponsiveLayoutMixin:
    """Toggle ``narrow`` and ``compact`` classes across responsive breakpoints."""

    NARROW_WIDTH_BREAKPOINT: ClassVar[int] = 80
    COMPACT_WIDTH_BREAKPOINT: ClassVar[int] = 100
    COMPACT_HEIGHT_BREAKPOINT: ClassVar[int] = 30

    def _resolve_viewport_height(self, height: int | None = None) -> int:
        """Resolve effective viewport height from argument or mounted widget size.

        Parameters
        ----------
        height : Optional[int], optional
            Explicit viewport height in rows when known.

        Returns
        -------
        int
            Effective positive terminal height in rows.
        """
        if height is not None and height > 0:
            return height
        size = getattr(self, "size", None)
        size_height = getattr(size, "height", 0)
        if isinstance(size_height, int) and size_height > 0:
            return size_height
        app = getattr(self, "app", None)
        app_size = getattr(app, "size", None)
        app_height = getattr(app_size, "height", 0)
        if isinstance(app_height, int) and app_height > 0:
            return app_height
        return 24

    def _update_layout(self, width: int, height: int | None = None) -> None:
        """Update layout classes based on viewport width and height breakpoints.

        Parameters
        ----------
        width : int
            Current viewport width in columns.
        height : Optional[int], optional
            Current viewport height in rows.
        """
        effective_height = self._resolve_viewport_height(height)
        add_class = getattr(self, "add_class")
        remove_class = getattr(self, "remove_class")
        if width < self.NARROW_WIDTH_BREAKPOINT:
            add_class("narrow")
        else:
            remove_class("narrow")

        if (
            width <= self.COMPACT_WIDTH_BREAKPOINT
            or effective_height <= self.COMPACT_HEIGHT_BREAKPOINT
        ):
            add_class("compact")
        else:
            remove_class("compact")

    def on_resize(self, event: events.Resize) -> None:
        """Handle viewport resize event across width and height dimensions.

        Parameters
        ----------
        event : events.Resize
            Textual resize event carrying updated terminal dimensions.
        """
        try:
            self._update_layout(event.size.width, event.size.height)
        except TypeError:
            self._update_layout(event.size.width)

on_resize(event)

Handle viewport resize event across width and height dimensions.

Parameters:

Name Type Description Default
event Resize

Textual resize event carrying updated terminal dimensions.

required
Source code in app/ui/layout.py
290
291
292
293
294
295
296
297
298
299
300
301
def on_resize(self, event: events.Resize) -> None:
    """Handle viewport resize event across width and height dimensions.

    Parameters
    ----------
    event : events.Resize
        Textual resize event carrying updated terminal dimensions.
    """
    try:
        self._update_layout(event.size.width, event.size.height)
    except TypeError:
        self._update_layout(event.size.width)

ResponsiveModalScreen

Bases: ResponsiveLayoutMixin, A11yMixin, ModalScreen[ScreenResultType]

Shared responsive, accessible modal base screen composing Screen.CSS.

Source code in app/ui/layout.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
class ResponsiveModalScreen(
    ResponsiveLayoutMixin, A11yMixin, ModalScreen[ScreenResultType]
):
    """Shared responsive, accessible modal base screen composing ``Screen.CSS``."""

    CSS: ClassVar[str] = BASE_MODAL_CSS
    MODAL_CSS: ClassVar[str] = ""
    BINDINGS: ClassVar[list[BindingType]] = [
        Binding("escape", "dismiss", "Close dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]
    _watched_toggle_values: dict[str, bool] | None = None
    _pending_watched_toggle_events: dict[str, deque[bool]] | None = None
    _in_watched_toggle_dispatch: bool = False

    def __init_subclass__(cls, **kwargs: Any) -> None:
        """Compose ``BASE_MODAL_CSS`` and subclass ``MODAL_CSS`` into ``Screen.CSS``.

        Parameters
        ----------
        **kwargs : Any
            Keyword arguments forwarded to superclass ``__init_subclass__``.
        """
        if "CSS" not in cls.__dict__:
            parts = [BASE_MODAL_CSS.replace("ResponsiveModalScreen", cls.__name__, 1)]
            for base in reversed(cls.__mro__):
                if issubclass(base, ResponsiveModalScreen):
                    delta = base.__dict__.get("MODAL_CSS", "")
                    if delta:
                        parts.append(delta)
            cls.CSS = "\n".join(parts)

        inherited_handlers = {
            method
            for base in cls.__mro__[1:]
            for entries in base.__dict__.get("_decorated_handlers", {}).values()
            for method, _ in entries
        }
        cls_handlers = cls.__dict__.get("_decorated_handlers", {})
        for base in cls.__mro__[1:]:
            if "_decorated_handlers" in base.__dict__:
                continue
            for attr_name, value in base.__dict__.items():
                if (
                    callable(value)
                    and hasattr(value, "_textual_on")
                    and getattr(cls, attr_name, None) is value
                    and value not in inherited_handlers
                ):
                    for message_type, selectors in getattr(value, "_textual_on"):
                        cls_handlers.setdefault(message_type, []).append(
                            (value, selectors)
                        )
                    inherited_handlers.add(value)

        super().__init_subclass__(**kwargs)

    def on_mount(self) -> None:
        """Apply responsive layout breakpoint classes when the modal mounts."""
        self._update_layout(self.size.width, self.size.height)

    def _watch_toggle_control(
        self,
        control: Any,
        event_handler: Callable[[Any], None],
    ) -> None:
        """Watch a ``Checkbox``, ``Switch``, or ``LabeledSwitch`` value synchronously."""
        target = getattr(control, "switch", control)
        control_id = getattr(target, "id", None) or getattr(control, "id", None)
        changed_cls = getattr(type(target), "Changed", None)
        if not isinstance(control_id, str) or not control_id or changed_cls is None:
            return

        values: dict[str, bool] | None = getattr(self, "_watched_toggle_values", None)
        if values is None:
            values = {}
            self._watched_toggle_values = values
        pending: dict[str, deque[bool]] | None = getattr(
            self, "_pending_watched_toggle_events", None
        )
        if pending is None:
            pending = {}
            self._pending_watched_toggle_events = pending

        values[control_id] = bool(getattr(target, "value", False))

        def _on_watched_value(new_value: object) -> None:
            val = bool(new_value)
            cur_values: dict[str, bool] | None = getattr(
                self, "_watched_toggle_values", None
            )
            if cur_values is None:
                return
            if not self.is_mounted:
                cur_values[control_id] = val
                return
            prevented = getattr(target, "_prevent_message_types", ())
            if changed_cls in prevented:
                cur_values[control_id] = val
                return
            if cur_values.get(control_id) == val:
                return
            cur_values[control_id] = val
            cur_pending: dict[str, deque[bool]] | None = getattr(
                self, "_pending_watched_toggle_events", None
            )
            if cur_pending is not None:
                cur_pending.setdefault(control_id, deque()).append(val)
            prev_flag = bool(getattr(self, "_in_watched_toggle_dispatch", False))
            self._in_watched_toggle_dispatch = True
            try:
                event_handler(changed_cls(target, val))
            finally:
                self._in_watched_toggle_dispatch = prev_flag

        self.watch(target, "value", _on_watched_value, init=False)

    def _should_skip_bubbled_toggle_event(self, event: Any) -> bool:
        """Return True if a bubbled ``Changed`` event was already dispatched synchronously."""
        if getattr(self, "_in_watched_toggle_dispatch", False):
            return False
        widget = (
            getattr(event, "checkbox", None)
            or getattr(event, "switch", None)
            or getattr(event, "control", None)
        )
        control_id = getattr(widget, "id", None) or getattr(
            getattr(event, "control", None), "id", None
        )
        if not isinstance(control_id, str) or not control_id:
            return False
        val = bool(getattr(event, "value", False))
        pending: dict[str, deque[bool]] | None = getattr(
            self, "_pending_watched_toggle_events", None
        )
        if pending is not None:
            queue = pending.get(control_id)
            if queue:
                if queue[0] == val:
                    queue.popleft()
                    return True
                queue.clear()
        values: dict[str, bool] | None = getattr(self, "_watched_toggle_values", None)
        if values is not None:
            values[control_id] = val
        return False

__init_subclass__(**kwargs)

Compose BASE_MODAL_CSS and subclass MODAL_CSS into Screen.CSS.

Parameters:

Name Type Description Default
**kwargs Any

Keyword arguments forwarded to superclass __init_subclass__.

{}
Source code in app/ui/layout.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
def __init_subclass__(cls, **kwargs: Any) -> None:
    """Compose ``BASE_MODAL_CSS`` and subclass ``MODAL_CSS`` into ``Screen.CSS``.

    Parameters
    ----------
    **kwargs : Any
        Keyword arguments forwarded to superclass ``__init_subclass__``.
    """
    if "CSS" not in cls.__dict__:
        parts = [BASE_MODAL_CSS.replace("ResponsiveModalScreen", cls.__name__, 1)]
        for base in reversed(cls.__mro__):
            if issubclass(base, ResponsiveModalScreen):
                delta = base.__dict__.get("MODAL_CSS", "")
                if delta:
                    parts.append(delta)
        cls.CSS = "\n".join(parts)

    inherited_handlers = {
        method
        for base in cls.__mro__[1:]
        for entries in base.__dict__.get("_decorated_handlers", {}).values()
        for method, _ in entries
    }
    cls_handlers = cls.__dict__.get("_decorated_handlers", {})
    for base in cls.__mro__[1:]:
        if "_decorated_handlers" in base.__dict__:
            continue
        for attr_name, value in base.__dict__.items():
            if (
                callable(value)
                and hasattr(value, "_textual_on")
                and getattr(cls, attr_name, None) is value
                and value not in inherited_handlers
            ):
                for message_type, selectors in getattr(value, "_textual_on"):
                    cls_handlers.setdefault(message_type, []).append(
                        (value, selectors)
                    )
                inherited_handlers.add(value)

    super().__init_subclass__(**kwargs)

on_mount()

Apply responsive layout breakpoint classes when the modal mounts.

Source code in app/ui/layout.py
362
363
364
def on_mount(self) -> None:
    """Apply responsive layout breakpoint classes when the modal mounts."""
    self._update_layout(self.size.width, self.size.height)

app.ui.markup_utils

app.ui.markup_utils

Literal square-bracket badge helpers and inspector markup formatting for Textual widgets.

escape_textual_markup(value)

Escape square brackets so Textual markup renders badges and dynamic text literally.

Source code in app/ui/markup_utils.py
10
11
12
def escape_textual_markup(value: object) -> str:
    """Escape square brackets so Textual markup renders badges and dynamic text literally."""
    return str(value).replace("[", "\\[")

format_file_inspector_lines(*, key, path_display, folder, locked, rating, info, lock_error=None, is_collision=False, conflict_policy='rename')

Build Rich/Textual markup lines for a file node in #meta-details with escaped values.

Source code in app/ui/markup_utils.py
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def format_file_inspector_lines(
    *,
    key: object,
    path_display: object,
    folder: object,
    locked: object,
    rating: object,
    info: Mapping[str, Any],
    lock_error: str | None = None,
    is_collision: bool = False,
    conflict_policy: object = "rename",
) -> list[str]:
    """Build Rich/Textual markup lines for a file node in ``#meta-details`` with escaped values."""
    lines: list[str] = [
        format_labeled_markup_line("File", key, label_style="bold accent"),
        format_labeled_markup_line("Path", path_display),
        format_labeled_markup_line("Target Folder", folder),
    ]

    target_fn = info.get("target_filename")
    if target_fn:
        lines.append(format_labeled_markup_line("Target Filename", target_fn))

    explicit_rename_src = info.get("rename_source")
    raw_src_ref = str(
        info.get("source_path") or info.get("filepath") or key or ""
    ).replace("\\", "/")
    if "::" in raw_src_ref:
        raw_src_ref = raw_src_ref.split("::", 1)[1]
    src_basename = os.path.basename(raw_src_ref)

    rename_src_display: str | None = None
    if explicit_rename_src and str(explicit_rename_src).strip():
        rename_src_display = str(explicit_rename_src).strip()
    elif target_fn and src_basename and str(target_fn) != src_basename:
        routed_by_val = str(info.get("routed_by") or "").strip().lower()
        if info.get("is_locked") and info.get("confirmed"):
            rename_src_display = "Manual"
        elif info.get("is_confirmed") and routed_by_val not in (
            "",
            "clustering",
            "historical",
            "keyword",
            "learned",
            "extension",
        ):
            rename_src_display = "Policy Rule"
        else:
            rename_src_display = "Template"

    if rename_src_display:
        lines.append(format_labeled_markup_line("Rename Source", rename_src_display))

    lines.append(format_labeled_markup_line("Locked", locked))
    lines.append(format_labeled_markup_line("ML Rating", rating))

    if lock_error:
        lines.append(
            format_labeled_markup_line(
                "Lock Warning", lock_error, label_style="bold error"
            )
        )

    routing_src = info.get("routed_by")
    if routing_src:
        lines.append(format_labeled_markup_line("Routing Source", routing_src))

    pol_prio = info.get("policy_priority")
    if pol_prio is not None:
        lines.append(format_labeled_markup_line("Policy Priority", pol_prio))

    pol_action = info.get("policy_action")
    if pol_action:
        lines.append(format_labeled_markup_line("Policy Action", pol_action))

    match_val = info.get("match") or info.get("keyword")
    if match_val and str(match_val).strip().lower() != "none":
        match_label = (
            "Cluster Keywords"
            if str(routing_src or "").strip().lower() == "clustering"
            else "Matched Rule"
        )
        lines.append(format_labeled_markup_line(match_label, match_val))

    cat = info.get("category") or info.get("jev_category")
    if cat:
        lines.append(format_labeled_markup_line("Category", cat))

    sens_rating = info.get("sensitivity_rating")
    if sens_rating is not None:
        lines.append(format_labeled_markup_line("Sensitivity Rating", sens_rating))

    sens_score = info.get("sensitivity_score")
    if sens_score is not None:
        try:
            formatted_sens: object = f"{float(sens_score):.2f}"
        except (ValueError, TypeError):
            formatted_sens = sens_score
        lines.append(format_labeled_markup_line("Sensitivity Score", formatted_sens))

    arch_prio = info.get("archival_priority")
    if arch_prio is not None:
        arch_str = (
            f"P{arch_prio}"
            if isinstance(arch_prio, int)
            or (
                isinstance(arch_prio, str)
                and not str(arch_prio).upper().startswith("P")
            )
            else str(arch_prio).upper()
        )
        lines.append(format_labeled_markup_line("Archival Priority", arch_str))

    arch_score = info.get("archival_priority_score")
    if arch_score is not None:
        try:
            formatted_arch: object = f"{float(arch_score):.2f}"
        except (ValueError, TypeError):
            formatted_arch = arch_score
        lines.append(
            format_labeled_markup_line("Archival Priority Score", formatted_arch)
        )

    conf = info.get("confidence")
    if conf is not None:
        try:
            formatted_conf: object = f"{float(conf):.2%}"
        except (ValueError, TypeError):
            formatted_conf = conf
        lines.append(format_labeled_markup_line("Confidence", formatted_conf))

    if is_collision:
        pol_str = str(conflict_policy or "rename").upper()
        lines.append(
            format_labeled_markup_line(
                "Collision Indicator",
                f"[COLLISION: {pol_str}]",
                label_style="bold warning",
            )
        )

    return lines

format_folder_inspector_lines(*, key, folder)

Build Rich/Textual markup lines for a folder node in #meta-details with escaped values.

Source code in app/ui/markup_utils.py
171
172
173
174
175
176
def format_folder_inspector_lines(*, key: object, folder: object) -> list[str]:
    """Build Rich/Textual markup lines for a folder node in ``#meta-details`` with escaped values."""
    return [
        format_labeled_markup_line("Folder Category", key, label_style="bold accent"),
        format_labeled_markup_line("Relative Path", folder),
    ]

format_labeled_markup_line(label, value, *, label_style='bold')

Format a styled Label: value markup line while escaping brackets in value.

Source code in app/ui/markup_utils.py
20
21
22
23
24
def format_labeled_markup_line(
    label: str, value: object, *, label_style: str = "bold"
) -> str:
    """Format a styled ``Label: value`` markup line while escaping brackets in ``value``."""
    return f"[{label_style}]{label}:[/{label_style}] {escape_textual_markup(value)}"

literal_content(text)

Wrap plain text in textual.content.Content so brackets render without markup parsing.

Source code in app/ui/markup_utils.py
15
16
17
def literal_content(text: str) -> Content:
    """Wrap plain text in ``textual.content.Content`` so brackets render without markup parsing."""
    return Content(text)

app.ui.mixins.pipeline

app.ui.mixins.pipeline

Scan, validation and execute workers that drive a sort from the TUI.

SortPipelineMixin

Run the scan, plan validation and move execution workers for the TUI.

Source code in app/ui/mixins/pipeline.py
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
class SortPipelineMixin:
    """Run the scan, plan validation and move execution workers for the TUI."""

    def action_scan_directory(self: TUIHostProtocol) -> None:
        """Trigger directory scanning background worker."""
        if self._is_text_control_focused(allow_tree_search=True):
            return
        if not getattr(self, "source_dirs", None) and self.base_dir:
            self.source_dirs = [self.base_dir]
        if not getattr(self, "source_dirs", None) or not any(
            os.path.exists(d) for d in self.source_dirs
        ):
            self.action_select_dir()
            return
        if self._announce_if_busy("scan"):
            return
        self._start_scan()

    def action_scan_subfolders(
        self: TUIHostProtocol, from_character: bool = False
    ) -> None:
        """Promote Max Scan Depth to at least 5 for this session and rescan subfolders."""
        if from_character:
            tree_focus_fn = getattr(self, "_tree_has_focus", None)
            char_enabled_fn = getattr(self, "_character_shortcuts_enabled", None)
            if (callable(tree_focus_fn) and not tree_focus_fn()) or (
                callable(char_enabled_fn) and not char_enabled_fn()
            ):
                return
        if self._is_text_control_focused(allow_tree_search=True):
            return
        if not getattr(self, "source_dirs", None) and self.base_dir:
            self.source_dirs = [self.base_dir]
        if not getattr(self, "source_dirs", None) or not any(
            os.path.exists(d) for d in self.source_dirs
        ):
            self.action_select_dir()
            return
        if self._announce_if_busy("scan subfolders"):
            return

        raw_depth = getattr(self.settings, "SCAN_MAX_DEPTH", 0)
        curr_depth = (
            raw_depth
            if isinstance(raw_depth, int) and not isinstance(raw_depth, bool)
            else 0
        )
        target_depth = max(5, curr_depth)
        override_fn = getattr(self.settings, "override", None)
        if callable(override_fn):
            override_fn("SCAN_MAX_DEPTH", target_depth)
        else:
            setattr(self.settings, "SCAN_MAX_DEPTH", target_depth)
        get_active_fn = getattr(self, "get_active_settings", None)
        if callable(get_active_fn):
            setattr(self, "_active_folder_settings", get_active_fn())
        self.update_status()
        self.announce(
            f"Scanning subfolders (Max Scan Depth {target_depth}): {', '.join(self.source_dirs)} ..."
        )
        self.run_scan_worker()

    def _start_scan(self: TUIHostProtocol) -> None:
        """Announce and launch the scan worker without the busy guard."""
        if hasattr(self, "selected_paths") and self.selected_paths is not None:
            self.selected_paths.clear()
        self.visual_select_active = False
        self.visual_selected_nodes = []
        self.announce(f"Scanning directories: {', '.join(self.source_dirs)} ...")
        self.run_scan_worker()

    def _running_pipeline_worker(self: TUIHostProtocol) -> str | None:
        """Return the name of a running scan or execute worker, if any."""
        pipeline = getattr(self, "pipeline", None)
        if pipeline is not None and hasattr(pipeline, "state"):
            from app.core.pipeline import PipelineLifecycleState

            if pipeline.state == PipelineLifecycleState.EXECUTING:
                return "run_execute_worker"
            if pipeline.state == PipelineLifecycleState.PLANNING:
                return "run_scan_worker"
            if pipeline.state == PipelineLifecycleState.ROLLING_BACK:
                return "run_execute_worker"
        session = getattr(self, "app_session", None)
        if session is not None and hasattr(session, "lifecycle_state"):
            from app.core.pipeline import PipelineLifecycleState

            if session.lifecycle_state == PipelineLifecycleState.EXECUTING:
                return "run_execute_worker"
            if session.lifecycle_state == PipelineLifecycleState.PLANNING:
                return "run_scan_worker"
            if session.lifecycle_state == PipelineLifecycleState.ROLLING_BACK:
                return "run_execute_worker"
        return None

    def _announce_if_busy(self: TUIHostProtocol, action: str) -> bool:
        """Refuse to start ``action`` while a scan or move is still running.

        Queries the pipeline lifecycle state rather than inspecting thread names.
        Also warns users or prevents conflicts when the watchdog daemon is active.
        """
        pipeline = getattr(self, "pipeline", None)
        session = getattr(self, "app_session", None)
        state = None
        if pipeline is not None and hasattr(pipeline, "state"):
            state = pipeline.state
        elif session is not None and hasattr(session, "lifecycle_state"):
            state = session.lifecycle_state

        if state is not None:
            from app.core.pipeline import PipelineLifecycleState

            if state == PipelineLifecycleState.EXECUTING:
                msg = f"Files are still being moved. Wait for it to finish before you {action}."
                self.announce(msg, priority="assertive")
                return True
            if state == PipelineLifecycleState.PLANNING:
                msg = f"A scan is still running. Wait for it to finish before you {action}."
                self.announce(msg, priority="assertive")
                return True
            if state == PipelineLifecycleState.ROLLING_BACK:
                msg = f"Files are currently being rolled back. Wait for it to finish before you {action}."
                self.announce(msg, priority="assertive")
                return True

        if getattr(self, "_daemon_is_moving", False):
            msg = f"Watchdog daemon is currently moving files. Wait for it to finish or pause monitoring before you {action}."
            self.announce(msg, priority="assertive")
            return True

        return False

    def _handle_pipeline_state_transition(
        self: TUIHostProtocol,
        old_state: Any,
        new_state: Any,
        context: dict[str, Any] | None = None,
    ) -> None:
        """Track pipeline state transitions via registered event hook."""
        logger.debug(f"UI observed pipeline state change: {old_state} -> {new_state}")

    def _handle_pipeline_telemetry(
        self: TUIHostProtocol, event: str, payload: dict[str, Any]
    ) -> None:
        """Handle telemetry events broadcast by the pipeline."""
        logger.debug(f"UI observed pipeline telemetry: {event} {payload}")

    @work(exclusive=True, thread=True)
    def run_scan_worker(self: TUIHostProtocol) -> None:
        """Execute scan and plan generation in worker thread."""
        try:
            from app.core.session import AppSession

            if self.app_session:
                try:
                    self.app_session.close()
                except Exception:
                    pass

            s_dirs = getattr(self, "source_dirs", None) or (
                [self.base_dir] if self.base_dir else []
            )
            self.app_session = AppSession(
                self.settings,
                self.base_dir,
                source_dirs=getattr(self, "source_dirs", None),
            )

            from app.core.pipeline import PipelineLifecycleState, SortPipeline

            self.pipeline = SortPipeline(
                self.app_session,
                base_dir=self.base_dir,
                settings=self.settings,
            )
            self.pipeline.add_state_change_hook(self._handle_pipeline_state_transition)
            self.pipeline.add_telemetry_hook(self._handle_pipeline_telemetry)

            def scan_progress_cb(
                update_or_prog: Any, stage: str | None = None, **kwargs: Any
            ) -> None:
                self.call_from_thread(
                    self._handle_progress_update, update_or_prog, stage, **kwargs
                )

            self.plan = self.pipeline.plan(
                progress_callback=scan_progress_cb,
                cancel_check=lambda: False,
            )
            files = self.pipeline.planned_items

            # Load locks & ratings
            try:
                docs = self.app_session.db.get_all_documents(
                    self.base_dir, source_dirs=s_dirs
                )
                for d in docs:
                    if len(d) > 3 and d[3]:
                        self.locked_files[d[0]] = d[3]
            except Exception:
                pass

            try:
                self._ratings_cache = self.app_session.db.get_all_document_ratings(
                    self.base_dir
                )
            except Exception:
                pass

            try:
                from app.core.db_conn import DB_ERRORS

                loaded_manual: set[str] = set()
                for s_dir in s_dirs:
                    if s_dir:
                        loaded_manual.update(
                            self.app_session.cache_manager.load_manual_folders(
                                str(s_dir)
                            )
                        )
                if loaded_manual:
                    self._manual_empty_folders.update(loaded_manual)
                elif self._manual_empty_folders:
                    for s_dir in s_dirs:
                        if s_dir:
                            self.app_session.cache_manager.save_manual_folders(
                                str(s_dir), self._manual_empty_folders
                            )
            except (*DB_ERRORS, OSError, RuntimeError, ValueError, TypeError) as mf_err:
                logger.debug(f"Manual folder cache sync skipped: {mf_err}")

            self._reapply_manual_plan_edits()
            self.call_from_thread(self.rebuild_tree)
            model_status = getattr(self.plan, "model_status", "HEALTHY")
            invalid_locks = getattr(self.plan, "invalid_locks", {}) or {}
            if not invalid_locks and isinstance(self.plan, dict):
                invalid_locks = self.plan.get("invalid_locks", {}) or {}
            num_invalid = len(invalid_locks)

            if model_status == "DEGRADED_FALLBACK" or (
                isinstance(self.plan, dict)
                and self.plan.get("model_status") == "DEGRADED_FALLBACK"
            ):
                reason = (
                    getattr(self.plan, "degradation_reason", None)
                    or self.plan.get("degradation_reason")
                    or "Model unavailable"
                )
                rec_action = (
                    getattr(self.plan, "recovery_action", None)
                    or self.plan.get("recovery_action")
                    or "Re-download model bundle"
                )
                msg = f"Scan complete (DEGRADED FALLBACK MODE: {reason}. Suggested action: {rec_action}). Analyzed {len(files)} files."
                self.call_from_thread(
                    self.notify,
                    f"Sorting plan generated in degraded fallback mode: {reason}",
                    title=f"Suggested recovery action: {rec_action}",
                    severity="warning",
                )
            else:
                msg = f"Scan complete. Analyzed {len(files)} files into proposed plan."

            if num_invalid > 0:
                lock_str = (
                    "1 bad lock path was skipped"
                    if num_invalid == 1
                    else f"{num_invalid} bad lock paths were skipped"
                )
                msg += f" ({lock_str})."
            self.call_from_thread(self.announce, msg)
        except Exception as e:
            if hasattr(self, "pipeline") and self.pipeline:
                try:
                    self.pipeline.transition_to(PipelineLifecycleState.FAILED)
                except Exception:
                    pass
            logger.error(f"Error in run_scan_worker: {e}")
            self.call_from_thread(self.announce, f"Scan error: {e}")
        finally:
            self.call_from_thread(self.reset_progress_bar)
            if getattr(self, "_pending_ai_active_rescan", False):
                from app.ui.ai_runtime import trigger_ai_active_rescan_if_eligible

                self.call_from_thread(trigger_ai_active_rescan_if_eligible, self)

    def action_execute_sort(self: TUIHostProtocol) -> None:
        """Trigger sorting plan execution worker with pre-move duplicate cluster review."""
        is_resume = bool(getattr(self, "_pending_resume", False))
        if not is_resume and self._is_text_control_focused(allow_tree_search=True):
            return
        if not self.plan or not self.app_session:
            setattr(self, "_pending_resume", False)
            self.announce("No plan available to execute. Run [Ctrl+S] Scan first.")
            return
        if self._announce_if_busy("execute the plan"):
            setattr(self, "_pending_resume", False)
            return

        from app.core.path_utils import collect_empty_plan_folders

        exec_plan = self._get_executable_plan()
        if not self._has_file_nodes(exec_plan) and not collect_empty_plan_folders(
            exec_plan
        ):
            setattr(self, "_pending_resume", False)
            self.announce("No checked files in sorting plan to execute.")
            return

        if is_resume:
            self._pending_flush_trash = False
            self.run_execute_worker()
            return

        if getattr(self, "has_critical_errors", False):
            v_res = getattr(self, "verification_result", None) or {}
            collisions_list = v_res.get("collisions") or []
            has_structural_collision = any(
                c.get("type") in ("parent_directory_collision", "target_is_directory")
                for c in collisions_list
            )
            has_non_collision_critical = bool(
                v_res.get("circular_renames")
                or v_res.get("invalid_renames")
                or v_res.get("long_paths")
                or v_res.get("escaping_paths")
                or has_structural_collision
                or not collisions_list
            )
            if has_non_collision_critical:
                self.announce(
                    "Cannot execute plan: Critical validation errors exist (see Alert Banner)."
                )
                return

        search_inputs = self.query("#tree-search-input")
        raw_filter_query = (
            search_inputs.first(Input).value.strip() if search_inputs else ""
        )
        if raw_filter_query:
            all_exec_files = self._collect_file_nodes_from_dict(exec_plan)
            visible_exec_plan = self._get_executable_plan(visible_only=True)
            visible_exec_files = self._collect_file_nodes_from_dict(visible_exec_plan)
            visible_ids = {id(f) for f in visible_exec_files}
            hidden_exec_files = [f for f in all_exec_files if id(f) not in visible_ids]
            if hidden_exec_files:
                hidden_folders = sorted(
                    {str(f.get("folder") or "Root") for f in hidden_exec_files}
                )

                def _on_filtered_confirm(choice: str | None) -> None:
                    if choice is None:
                        self.announce("Move execution cancelled.")
                        return
                    if choice == "visible":
                        vis_plan_now = self._get_executable_plan(visible_only=True)
                        if not self._has_file_nodes(
                            vis_plan_now
                        ) and not collect_empty_plan_folders(vis_plan_now):
                            self.announce(
                                "No visible included files to execute under active filter."
                            )
                            return
                        SortPipelineMixin._continue_execute_sort(
                            self, visible_only=True
                        )
                    elif choice == "full":
                        SortPipelineMixin._continue_execute_sort(
                            self, visible_only=False
                        )

                self.push_screen(
                    FilteredExecutionConfirmModal(
                        filter_query=raw_filter_query,
                        visible_included_count=len(visible_exec_files),
                        hidden_included_count=len(hidden_exec_files),
                        total_included_count=len(all_exec_files),
                        hidden_folders=hidden_folders,
                    ),
                    _on_filtered_confirm,
                )
                return

        SortPipelineMixin._continue_execute_sort(self, visible_only=False)

    def _continue_execute_sort(
        self: TUIHostProtocol, *, visible_only: bool = False
    ) -> None:
        """Continue plan execution after optional filtered-plan confirmation."""
        from app.core.path_utils import collect_empty_plan_folders

        exec_plan = self._get_executable_plan(visible_only=visible_only)
        base_dir: str = (
            (self.app_session.base_dir if self.app_session else None)
            or self.base_dir
            or "."
        )
        self._pending_flush_trash = False
        from app.core.plan_format import count_plan_actions, normalize_duplicate_mode
        from app.core.verifier import VerificationEngine

        detect_original_by = str(
            getattr(self.settings, "DETECT_ORIGINAL_BY", "first_seen") or "first_seen"
        )
        dup_mode = normalize_duplicate_mode(
            getattr(self.settings, "DUPLICATE_ACTION", "off")
        )

        def _continue_with_collision_check() -> None:
            refreshed_exec = self._get_executable_plan(visible_only=visible_only)
            if not self._has_file_nodes(
                refreshed_exec
            ) and not collect_empty_plan_folders(refreshed_exec):
                self.announce("No remaining checked files to execute after review.")
                return
            normalized_refreshed = self._normalize_plan_for_verification(
                refreshed_exec, base_dir
            )
            collision_groups = VerificationEngine.get_collision_groups(
                base_dir, normalized_refreshed
            )
            if collision_groups:

                def handle_collision_modal_result(
                    col_selections: dict[str, str] | None,
                ) -> None:
                    if col_selections is None:
                        self.announce(
                            "Move execution cancelled during collision resolution."
                        )
                        return

                    VerificationEngine.apply_collision_selections(
                        base_dir,
                        self.plan,
                        col_selections,
                        groups=collision_groups,
                    )
                    final_plan = self._get_executable_plan(visible_only=visible_only)
                    self.announce(
                        "Executing file moves according to plan with collision resolution applied..."
                    )
                    self.run_execute_worker(
                        exec_plan_override=final_plan if visible_only else None,
                        clear_manual_edits=not visible_only,
                    )

                self.push_screen(
                    InteractiveCollisionResolverModal(
                        collision_groups=collision_groups
                    ),
                    handle_collision_modal_result,
                )
            else:
                self.announce("Executing file moves according to plan...")
                self.run_execute_worker(
                    exec_plan_override=refreshed_exec if visible_only else None,
                    clear_manual_edits=not visible_only,
                )

        if dup_mode == "review":
            normalized_exec_plan = self._normalize_plan_for_verification(
                exec_plan, base_dir
            )
            duplicate_groups = VerificationEngine.get_duplicate_groups(
                base_dir,
                normalized_exec_plan,
                detect_original_by=detect_original_by,
            )
            if duplicate_groups:

                def handle_duplicate_modal_result(
                    selections: dict[str, str] | None,
                ) -> None:
                    if selections is None:
                        self.announce(
                            "Move execution cancelled during duplicate review."
                        )
                        return

                    if any(val == "trash" for val in selections.values()):
                        self._pending_flush_trash = True

                    VerificationEngine.apply_deduplication_selections(
                        base_dir,
                        self.plan,
                        selections,
                        groups=duplicate_groups,
                        detect_original_by=detect_original_by,
                    )
                    _continue_with_collision_check()

                self.push_screen(
                    DuplicateReviewModal(duplicate_groups=duplicate_groups),
                    handle_duplicate_modal_result,
                )
                return
        elif dup_mode in ("skip", "stage", "trash"):
            normalized_exec_plan = self._normalize_plan_for_verification(
                exec_plan, base_dir
            )
            unresolved_groups = VerificationEngine.get_duplicate_groups(
                base_dir,
                normalized_exec_plan,
                detect_original_by=detect_original_by,
            )
            if unresolved_groups:
                auto_choice = "keep" if dup_mode == "skip" else dup_mode
                auto_selections = {
                    g["group_id"]: auto_choice for g in unresolved_groups
                }
                VerificationEngine.apply_deduplication_selections(
                    base_dir,
                    self.plan,
                    auto_selections,
                    groups=unresolved_groups,
                    detect_original_by=detect_original_by,
                )
            if (
                dup_mode == "trash"
                and count_plan_actions(
                    self._get_executable_plan(visible_only=visible_only)
                )["trashed"]
                > 0
            ):
                self._pending_flush_trash = True

        _continue_with_collision_check()

    def _normalize_plan_for_verification(
        self: TUIHostProtocol, plan_dict: dict[str, Any], base_dir: str
    ) -> dict[str, Any]:
        """Ensure file nodes in plan dictionary have source_path and relative_source populated."""
        if not isinstance(plan_dict, dict):
            return plan_dict
        normalized: dict[str, Any] = {}
        for k, v in plan_dict.items():
            if isinstance(v, dict):
                if v.get("__type__") == "file":
                    item = dict(v)
                    fp = item.get("filepath")
                    if fp:
                        if not item.get("source_path"):
                            item["source_path"] = fp
                        if not item.get("relative_source") and base_dir:
                            try:
                                item["relative_source"] = os.path.relpath(fp, base_dir)
                            except ValueError:
                                item["relative_source"] = fp
                    normalized[k] = item
                else:
                    normalized[k] = self._normalize_plan_for_verification(v, base_dir)
            else:
                normalized[k] = v
        return normalized

    def _reapply_manual_plan_edits(self: TUIHostProtocol) -> None:
        """Reapply cached manual renames, folder reassignments, and exclusions after rescan."""
        from app.core.path_utils import _disambiguate_key, safe_relpath
        from app.ui.mixins.selection import (
            _make_manual_edit_key,
            _resolve_plan_folder_dict,
            _resolve_source_identity,
        )

        raw_plan: Any = self.plan
        plan_dict = (
            raw_plan.plan
            if hasattr(raw_plan, "plan") and isinstance(raw_plan.plan, dict)
            else raw_plan
        )
        if not isinstance(plan_dict, dict):
            return

        manual_folders = getattr(self, "_manual_empty_folders", set())
        for folder_name in list(manual_folders):
            if folder_name:
                created = _resolve_plan_folder_dict(plan_dict, folder_name, create=True)
                if created is None:
                    plan_dict[folder_name] = {}

        edits_map = getattr(self, "_manual_plan_edits", None)
        if not edits_map:
            return

        by_relpath: dict[str, dict[str, Any]] = {}
        for edit_val in edits_map.values():
            rel_p = edit_val.get("doc_relpath")
            if rel_p and rel_p not in by_relpath:
                by_relpath[rel_p] = edit_val

        collected: list[tuple[str, dict[str, Any], str, dict[str, Any]]] = []

        def _walk_plan(curr: dict[str, Any], folder_path: str = "") -> None:
            for k, v in list(curr.items()):
                if isinstance(v, dict):
                    if v.get("__type__") == "file":
                        collected.append((folder_path, curr, k, v))
                    else:
                        sub = f"{folder_path}/{k}" if folder_path else k
                        _walk_plan(v, sub)

        _walk_plan(plan_dict)

        matched_edit_keys: set[str] = set()
        matched_edit_ids: set[int] = set()
        for current_folder, container, key, file_info in collected:
            db_base, doc_relpath, abs_fp = _resolve_source_identity(
                self,
                file_key=key,
                filepath=file_info.get("filepath"),
                info=file_info,
            )
            if not doc_relpath:
                continue

            scoped_key = _make_manual_edit_key(db_base, doc_relpath)
            edit = edits_map.get(scoped_key) or by_relpath.get(doc_relpath)
            if not edit:
                continue
            matched_edit_keys.add(scoped_key)
            matched_edit_ids.add(id(edit))

            if doc_relpath and not file_info.get("source_path"):
                file_info["source_path"] = doc_relpath
            if abs_fp and not file_info.get("filepath"):
                file_info["filepath"] = abs_fp

            target_folder = current_folder
            if edit.get("folder") and not file_info.get("is_overridden"):
                target_folder = str(edit["folder"])

            manual_tf = edit.get("target_filename")
            dest_key = str(manual_tf) if manual_tf else key

            if target_folder != current_folder or dest_key != key:
                container.pop(key, None)
                dest_container = _resolve_plan_folder_dict(
                    plan_dict, target_folder, create=True
                )
                if dest_container is None:
                    plan_dict[target_folder] = {}
                    dest_container = plan_dict[target_folder]
                if (
                    dest_key in dest_container
                    and dest_container[dest_key] is not file_info
                ):
                    dest_key = _disambiguate_key(dest_container, dest_key, is_file=True)
                dest_container[dest_key] = file_info
                file_info["folder"] = target_folder
                if abs_fp and db_base:
                    dest_base = (
                        os.path.join(db_base, target_folder)
                        if target_folder
                        else db_base
                    )
                    file_info["relative_source"] = safe_relpath(
                        abs_fp, dest_base
                    ).replace("\\", "/")

            if manual_tf:
                file_info["target_filename"] = dest_key
                file_info["rename_source"] = str(edit.get("rename_source") or "Manual")
                file_info["confirmed"] = bool(edit.get("confirmed", True))
                self.locked_files[dest_key] = target_folder
            elif edit.get("reverted_target_name"):
                file_info.pop("target_filename", None)
                file_info.pop("rename_source", None)
                file_info.pop("confirmed", None)
                file_info.pop("is_confirmed", None)
                file_info.pop("user_confirmed", None)

            if "is_locked" in edit:
                is_locked_val = bool(edit["is_locked"])
                file_info["is_locked"] = is_locked_val
                if is_locked_val:
                    self.locked_files[doc_relpath] = target_folder
                else:
                    self.locked_files.pop(doc_relpath, None)

            if "is_excluded" in edit:
                file_info["is_excluded"] = bool(edit["is_excluded"])
            if "is_checked" in edit:
                file_info["is_checked"] = bool(edit["is_checked"])
            if file_info.get("is_excluded"):
                file_info["is_checked"] = False
                if hasattr(self, "excluded_paths") and self.excluded_paths is not None:
                    self.excluded_paths.add(scoped_key)
            elif (
                "is_excluded" in edit
                and hasattr(self, "excluded_paths")
                and self.excluded_paths is not None
            ):
                self.excluded_paths.discard(scoped_key)

        # Re-insert renamed files that were pruned as in-place no-ops before target_filename was applied
        for scoped_key, edit in list(edits_map.items()):
            if scoped_key in matched_edit_keys or id(edit) in matched_edit_ids:
                continue
            manual_tf = edit.get("target_filename")
            target_folder = str(edit.get("folder") or "")
            abs_fp = str(edit.get("abs_filepath") or "")
            doc_relpath = str(edit.get("doc_relpath") or "")
            db_base = str(edit.get("db_base_dir") or self.base_dir or "")
            if not (manual_tf and abs_fp and os.path.lexists(abs_fp)):
                continue
            planned_dst = os.path.normcase(
                os.path.normpath(
                    os.path.abspath(
                        os.path.join(
                            self.base_dir or db_base, target_folder, str(manual_tf)
                        )
                    )
                )
            )
            if planned_dst == os.path.normcase(
                os.path.normpath(os.path.abspath(abs_fp))
            ):
                continue
            dest_container = _resolve_plan_folder_dict(
                plan_dict, target_folder, create=True
            )
            if dest_container is None:
                plan_dict[target_folder] = {}
                dest_container = plan_dict[target_folder]
            dest_key = str(manual_tf)
            if dest_key in dest_container:
                dest_key = _disambiguate_key(dest_container, dest_key, is_file=True)
            dest_base = (
                os.path.join(db_base, target_folder) if target_folder else db_base
            )
            restored_node: dict[str, Any] = {
                "__type__": "file",
                "source_path": doc_relpath,
                "source_root": db_base,
                "filepath": abs_fp,
                "relative_source": safe_relpath(abs_fp, dest_base).replace("\\", "/")
                if db_base
                else doc_relpath,
                "target_filename": dest_key,
                "folder": target_folder,
                "is_locked": bool(edit.get("is_locked", True)),
                "confirmed": bool(edit.get("confirmed", True)),
                "is_excluded": bool(edit.get("is_excluded", False)),
                "is_checked": bool(
                    edit.get("is_checked", not edit.get("is_excluded", False))
                ),
            }
            dest_container[dest_key] = restored_node
            self.locked_files[dest_key] = target_folder
            if doc_relpath and restored_node["is_locked"]:
                self.locked_files[doc_relpath] = target_folder

        def _prune_empty_auto_folders(curr: dict[str, Any], prefix: str = "") -> None:
            for k, v in list(curr.items()):
                if isinstance(v, dict) and v.get("__type__") != "file":
                    full = f"{prefix}/{k}" if prefix else k
                    _prune_empty_auto_folders(v, full)
                    if not v and full not in manual_folders and k not in manual_folders:
                        curr.pop(k, None)

        _prune_empty_auto_folders(plan_dict)

    def run_validation_worker(self: TUIHostProtocol) -> Any:
        """Asynchronously verify plan integrity in background worker thread."""
        epoch = int(getattr(self, "_validation_epoch", 0)) + 1
        setattr(self, "_validation_epoch", epoch)
        return _start_validation_worker(self, epoch)

    def _update_validation_state(self: TUIHostProtocol, result: dict[str, Any]) -> None:
        """Update UI controls, alert banner, and tree highlights based on validation result."""
        epoch = int(getattr(self, "_validation_epoch", 0)) + 1
        setattr(self, "_validation_epoch", epoch)
        self.verification_result = result or {}

        collisions = result.get("collisions", [])
        recoverable_types = ("target_collision", "duplicate_target")
        critical_collisions = [
            c for c in collisions if c.get("type") not in recoverable_types
        ]
        recoverable_collisions = list(
            (result.get("recoverable_collisions") or [])
            if "recoverable_collisions" in result
            else [c for c in collisions if c.get("type") in recoverable_types]
        )
        circular = result.get("circular_renames", [])
        invalid = result.get("invalid_renames", [])
        long_paths = result.get("long_paths", [])
        escaping = result.get("escaping_paths", [])

        broken_links = result.get("broken_links", [])
        unconfirmed = result.get("unconfirmed_renames", [])

        has_critical = bool(
            result.get("has_critical_errors")
            if "has_critical_errors" in result
            else (critical_collisions or circular or invalid or long_paths or escaping)
        )
        has_warnings = bool(recoverable_collisions or broken_links or unconfirmed)

        self.has_critical_errors = has_critical

        # Build path sets for tree node highlighting
        crit_paths = set()
        for c in critical_collisions:
            if c.get("path"):
                crit_paths.add(os.path.normpath(c["path"]))
            if c.get("source"):
                crit_paths.add(os.path.normpath(c["source"]))
            for s in c.get("sources", []):
                crit_paths.add(os.path.normpath(s))
        for r in circular:
            if r.get("path"):
                crit_paths.add(os.path.normpath(r["path"]))
            for p in r.get("cycle", []):
                crit_paths.add(os.path.normpath(p))
        for inv in invalid:
            if inv.get("path"):
                crit_paths.add(os.path.normpath(inv["path"]))
            if inv.get("source"):
                crit_paths.add(os.path.normpath(inv["source"]))
        for lp in long_paths:
            if lp.get("path"):
                crit_paths.add(os.path.normpath(lp["path"]))
            if lp.get("source"):
                crit_paths.add(os.path.normpath(lp["source"]))
        for ep in escaping:
            if ep.get("path"):
                crit_paths.add(os.path.normpath(ep["path"]))
            if ep.get("source"):
                crit_paths.add(os.path.normpath(ep["source"]))

        warn_paths = set()
        for rc in recoverable_collisions:
            if rc.get("path"):
                warn_paths.add(os.path.normpath(rc["path"]))
            if rc.get("source"):
                warn_paths.add(os.path.normpath(rc["source"]))
            for s in rc.get("sources", []):
                warn_paths.add(os.path.normpath(s))
        for bl in broken_links:
            if bl.get("path"):
                warn_paths.add(os.path.normpath(bl["path"]))
        for unc in unconfirmed:
            if unc.get("path"):
                warn_paths.add(os.path.normpath(unc["path"]))
            if unc.get("source"):
                warn_paths.add(os.path.normpath(unc["source"]))

        collision_paths = set()
        for c in list(collisions) + list(recoverable_collisions):
            if c.get("path"):
                collision_paths.add(os.path.normpath(c["path"]))
            if c.get("source"):
                collision_paths.add(os.path.normpath(c["source"]))
            for s in c.get("sources", []):
                collision_paths.add(os.path.normpath(s))

        self.critical_error_paths = crit_paths
        self.warning_paths = warn_paths
        self.collision_paths = collision_paths

        # Update Execute Button
        try:
            from app.core.path_utils import collect_empty_plan_folders

            btn_exec = self.query_one("#btn-execute", Button)
            exec_plan = self._get_executable_plan()
            has_exec_work = self._has_file_nodes(exec_plan) or bool(
                collect_empty_plan_folders(exec_plan)
            )

            if has_critical or not has_exec_work:
                btn_exec.disabled = True
                if has_critical:
                    btn_exec.tooltip = "Execution disabled: Plan contains blocking critical validation errors"
                elif not self.plan:
                    btn_exec.tooltip = EXECUTE_NEEDS_SCAN_TOOLTIP
                else:
                    btn_exec.tooltip = (
                        "Execution disabled: No files selected to execute"
                    )
            else:
                btn_exec.disabled = False
                btn_exec.tooltip = "Execute file sorting plan [Ctrl+E]"
        except Exception:
            pass

        # Update Alert Banner
        try:
            alert_banner = self.query_one("#alert-banner", Static)
            if has_critical:
                alert_banner.display = True
                alert_banner.remove_class("alert-warning")
                alert_banner.add_class("alert-critical")

                msgs = []
                if critical_collisions:
                    msgs.append(
                        "⛔ CRITICAL FILE COLLISION(S) / STRUCTURAL DIRECTORY COLLISION(S) DETECTED:"
                    )
                    for c in critical_collisions:
                        dst_p = c.get("path", "")
                        msgs.append(
                            f"  • Destination: {dst_p} ({c.get('message', 'Collision')})"
                        )
                if circular:
                    msgs.append("⛔ CIRCULAR RENAMING DEPENDENCY DETECTED:")
                    for r in circular:
                        msgs.append(f"  • {r.get('message')}")
                if invalid:
                    msgs.append("⛔ INVALID FILENAME / STRUCTURE:")
                    for inv in invalid:
                        msgs.append(f"  • {inv.get('message')}")
                if long_paths:
                    msgs.append("⛔ EXCEEDS PATH LENGTH LIMIT:")
                    for lp in long_paths:
                        msgs.append(f"  • {lp.get('message')}")
                if escaping:
                    msgs.append("⛔ PATH TRAVERSAL / ESCAPING TARGET DETECTED:")
                    for ep in escaping:
                        msgs.append(f"  • {ep.get('message')}")

                alert_str = "\n".join(msgs)
                alert_banner.update(alert_str)
                self.announce(f"Alert Banner: {alert_str}")
            elif has_warnings:
                alert_banner.display = True
                alert_banner.remove_class("alert-critical")
                alert_banner.add_class("alert-warning")

                msgs = ["⚠️ NON-FATAL WARNING(S) REPORTED (Execution unblocked):"]
                for rc in recoverable_collisions:
                    dst_p = rc.get("path", "")
                    msgs.append(
                        f"  • Recoverable collision at {dst_p} ({rc.get('message', 'Collision')} — resolve on [Ctrl+E])"
                    )
                for bl in broken_links:
                    msgs.append(f"  • {bl.get('message')}")
                for unc in unconfirmed:
                    msgs.append(f"  • {unc.get('message')}")

                alert_str = "\n".join(msgs)
                alert_banner.update(alert_str)
            else:
                alert_banner.display = False
                alert_banner.update("")
        except Exception as e:
            logger.debug(f"Error updating alert banner: {e}")

        # Update node styling in tree view
        self._apply_tree_node_styles()

    @work(exclusive=True, thread=True, group="execute")
    def run_execute_worker(
        self: TUIHostProtocol,
        exec_plan_override: dict[str, Any] | None = None,
        *,
        clear_manual_edits: bool = True,
    ) -> None:
        """Execute moves in worker thread."""
        try:

            def move_progress_cb(
                update_or_prog: Any, stage: str | None = None, **kwargs: Any
            ) -> None:
                self.call_from_thread(
                    self._handle_progress_update, update_or_prog, stage, **kwargs
                )

            exec_plan = (
                exec_plan_override
                if exec_plan_override is not None
                else self._get_executable_plan()
            )
            from app.core.pipeline import PipelineLifecycleState, SortPipeline

            if (
                not hasattr(self, "pipeline")
                or self.pipeline is None
                or getattr(self.pipeline, "session", None) != self.app_session
            ):
                self.pipeline = SortPipeline(self.app_session)
                self.pipeline.add_state_change_hook(
                    self._handle_pipeline_state_transition
                )
                self.pipeline.add_telemetry_hook(self._handle_pipeline_telemetry)

            if self.pipeline.state != PipelineLifecycleState.PLANNED:
                self.pipeline.transition_to(PipelineLifecycleState.PLANNED)

            flush_trash = bool(self._pending_flush_trash)
            self._pending_flush_trash = False
            resume_exec = bool(getattr(self, "_pending_resume", False))
            setattr(self, "_pending_resume", False)

            settings_model = getattr(self.settings, "_settings_model", None)
            fields_set = getattr(settings_model, "model_fields_set", set()) or set()
            configured_policy = getattr(self.settings, "MOVE_ERROR_POLICY", None)
            if "MOVE_ERROR_POLICY" in fields_set and configured_policy:
                effective_error_policy = str(configured_policy)
            elif (
                isinstance(configured_policy, str)
                and configured_policy.strip().lower() != "rollback"
            ):
                effective_error_policy = configured_policy
            else:
                effective_error_policy = "partial_commit"

            result = self.pipeline.execute(
                exec_plan,
                progress_callback=move_progress_cb,
                resume=resume_exec,
                flush_trash=flush_trash,
                flush_trashed_only=flush_trash,
                error_policy=effective_error_policy,
            )
            summary = result.summary
            if not (isinstance(summary, dict) and summary.get("cancelled")):
                if clear_manual_edits:
                    self._clear_manual_plan_edits()
                elif (
                    hasattr(self, "selected_paths") and self.selected_paths is not None
                ):
                    self.selected_paths.clear()
            if result.failed:
                msg = (
                    f"Execution completed with {len(result.failed)} failed item(s). "
                    f"Verified moves preserved; retry available in verification report."
                )
            else:
                reversible_count = (
                    len(result.moved) + len(result.quarantined) + len(result.staged)
                )
                if (
                    reversible_count == 0
                    and isinstance(summary, dict)
                    and not (summary.get("audit_report") or {}).get("records")
                ):
                    raw_moves = int(summary.get("moves") or 0)
                    reversible_count = max(0, raw_moves - len(result.trashed))
                undo_hint = " [Ctrl+Z] Undo available." if reversible_count > 0 else ""
                msg = (
                    f"Execution completed successfully! {result.describe()}{undo_hint} "
                    f"Summary: {summary}"
                )
            self.call_from_thread(self.announce, msg)
            from app.core.plan_format import format_trash_handoff_warning

            warn_msg = format_trash_handoff_warning(
                summary.get("trash_handoff") if isinstance(summary, dict) else None
            )
            if warn_msg:
                from app.ui.notifications import notify

                self.call_from_thread(self.announce, warn_msg)
                self.call_from_thread(lambda: notify(warn_msg, type="warning"))

            from app.core.audit_reporter import resolve_audit_report

            sess_base = self.app_session.base_dir if self.app_session else None
            base_dir: str = (
                sess_base
                if isinstance(sess_base, str) and sess_base
                else (self.base_dir or ".")
            )
            sess_id = (
                summary.get("session_id")
                if isinstance(summary, dict)
                else result.session_id
            )
            audit_report = resolve_audit_report(
                summary.get("audit_report") if isinstance(summary, dict) else None,
                base_dir,
                exec_plan,
                session_id=sess_id,
            )

            if audit_report:
                self.call_from_thread(self.action_open_audit_report, audit_report)
            # Rescan last: the scan worker replaces the AppSession this worker uses.
            self.call_from_thread(self._start_scan)
        except Exception as e:
            logger.error(f"Error executing moves: {e}")
            self.call_from_thread(self.announce, f"Execution error: {e}")
        finally:
            self.call_from_thread(self.reset_progress_bar)

action_execute_sort()

Trigger sorting plan execution worker with pre-move duplicate cluster review.

Source code in app/ui/mixins/pipeline.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def action_execute_sort(self: TUIHostProtocol) -> None:
    """Trigger sorting plan execution worker with pre-move duplicate cluster review."""
    is_resume = bool(getattr(self, "_pending_resume", False))
    if not is_resume and self._is_text_control_focused(allow_tree_search=True):
        return
    if not self.plan or not self.app_session:
        setattr(self, "_pending_resume", False)
        self.announce("No plan available to execute. Run [Ctrl+S] Scan first.")
        return
    if self._announce_if_busy("execute the plan"):
        setattr(self, "_pending_resume", False)
        return

    from app.core.path_utils import collect_empty_plan_folders

    exec_plan = self._get_executable_plan()
    if not self._has_file_nodes(exec_plan) and not collect_empty_plan_folders(
        exec_plan
    ):
        setattr(self, "_pending_resume", False)
        self.announce("No checked files in sorting plan to execute.")
        return

    if is_resume:
        self._pending_flush_trash = False
        self.run_execute_worker()
        return

    if getattr(self, "has_critical_errors", False):
        v_res = getattr(self, "verification_result", None) or {}
        collisions_list = v_res.get("collisions") or []
        has_structural_collision = any(
            c.get("type") in ("parent_directory_collision", "target_is_directory")
            for c in collisions_list
        )
        has_non_collision_critical = bool(
            v_res.get("circular_renames")
            or v_res.get("invalid_renames")
            or v_res.get("long_paths")
            or v_res.get("escaping_paths")
            or has_structural_collision
            or not collisions_list
        )
        if has_non_collision_critical:
            self.announce(
                "Cannot execute plan: Critical validation errors exist (see Alert Banner)."
            )
            return

    search_inputs = self.query("#tree-search-input")
    raw_filter_query = (
        search_inputs.first(Input).value.strip() if search_inputs else ""
    )
    if raw_filter_query:
        all_exec_files = self._collect_file_nodes_from_dict(exec_plan)
        visible_exec_plan = self._get_executable_plan(visible_only=True)
        visible_exec_files = self._collect_file_nodes_from_dict(visible_exec_plan)
        visible_ids = {id(f) for f in visible_exec_files}
        hidden_exec_files = [f for f in all_exec_files if id(f) not in visible_ids]
        if hidden_exec_files:
            hidden_folders = sorted(
                {str(f.get("folder") or "Root") for f in hidden_exec_files}
            )

            def _on_filtered_confirm(choice: str | None) -> None:
                if choice is None:
                    self.announce("Move execution cancelled.")
                    return
                if choice == "visible":
                    vis_plan_now = self._get_executable_plan(visible_only=True)
                    if not self._has_file_nodes(
                        vis_plan_now
                    ) and not collect_empty_plan_folders(vis_plan_now):
                        self.announce(
                            "No visible included files to execute under active filter."
                        )
                        return
                    SortPipelineMixin._continue_execute_sort(
                        self, visible_only=True
                    )
                elif choice == "full":
                    SortPipelineMixin._continue_execute_sort(
                        self, visible_only=False
                    )

            self.push_screen(
                FilteredExecutionConfirmModal(
                    filter_query=raw_filter_query,
                    visible_included_count=len(visible_exec_files),
                    hidden_included_count=len(hidden_exec_files),
                    total_included_count=len(all_exec_files),
                    hidden_folders=hidden_folders,
                ),
                _on_filtered_confirm,
            )
            return

    SortPipelineMixin._continue_execute_sort(self, visible_only=False)

action_scan_directory()

Trigger directory scanning background worker.

Source code in app/ui/mixins/pipeline.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def action_scan_directory(self: TUIHostProtocol) -> None:
    """Trigger directory scanning background worker."""
    if self._is_text_control_focused(allow_tree_search=True):
        return
    if not getattr(self, "source_dirs", None) and self.base_dir:
        self.source_dirs = [self.base_dir]
    if not getattr(self, "source_dirs", None) or not any(
        os.path.exists(d) for d in self.source_dirs
    ):
        self.action_select_dir()
        return
    if self._announce_if_busy("scan"):
        return
    self._start_scan()

action_scan_subfolders(from_character=False)

Promote Max Scan Depth to at least 5 for this session and rescan subfolders.

Source code in app/ui/mixins/pipeline.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def action_scan_subfolders(
    self: TUIHostProtocol, from_character: bool = False
) -> None:
    """Promote Max Scan Depth to at least 5 for this session and rescan subfolders."""
    if from_character:
        tree_focus_fn = getattr(self, "_tree_has_focus", None)
        char_enabled_fn = getattr(self, "_character_shortcuts_enabled", None)
        if (callable(tree_focus_fn) and not tree_focus_fn()) or (
            callable(char_enabled_fn) and not char_enabled_fn()
        ):
            return
    if self._is_text_control_focused(allow_tree_search=True):
        return
    if not getattr(self, "source_dirs", None) and self.base_dir:
        self.source_dirs = [self.base_dir]
    if not getattr(self, "source_dirs", None) or not any(
        os.path.exists(d) for d in self.source_dirs
    ):
        self.action_select_dir()
        return
    if self._announce_if_busy("scan subfolders"):
        return

    raw_depth = getattr(self.settings, "SCAN_MAX_DEPTH", 0)
    curr_depth = (
        raw_depth
        if isinstance(raw_depth, int) and not isinstance(raw_depth, bool)
        else 0
    )
    target_depth = max(5, curr_depth)
    override_fn = getattr(self.settings, "override", None)
    if callable(override_fn):
        override_fn("SCAN_MAX_DEPTH", target_depth)
    else:
        setattr(self.settings, "SCAN_MAX_DEPTH", target_depth)
    get_active_fn = getattr(self, "get_active_settings", None)
    if callable(get_active_fn):
        setattr(self, "_active_folder_settings", get_active_fn())
    self.update_status()
    self.announce(
        f"Scanning subfolders (Max Scan Depth {target_depth}): {', '.join(self.source_dirs)} ..."
    )
    self.run_scan_worker()

run_execute_worker(exec_plan_override=None, *, clear_manual_edits=True)

Execute moves in worker thread.

Source code in app/ui/mixins/pipeline.py
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
@work(exclusive=True, thread=True, group="execute")
def run_execute_worker(
    self: TUIHostProtocol,
    exec_plan_override: dict[str, Any] | None = None,
    *,
    clear_manual_edits: bool = True,
) -> None:
    """Execute moves in worker thread."""
    try:

        def move_progress_cb(
            update_or_prog: Any, stage: str | None = None, **kwargs: Any
        ) -> None:
            self.call_from_thread(
                self._handle_progress_update, update_or_prog, stage, **kwargs
            )

        exec_plan = (
            exec_plan_override
            if exec_plan_override is not None
            else self._get_executable_plan()
        )
        from app.core.pipeline import PipelineLifecycleState, SortPipeline

        if (
            not hasattr(self, "pipeline")
            or self.pipeline is None
            or getattr(self.pipeline, "session", None) != self.app_session
        ):
            self.pipeline = SortPipeline(self.app_session)
            self.pipeline.add_state_change_hook(
                self._handle_pipeline_state_transition
            )
            self.pipeline.add_telemetry_hook(self._handle_pipeline_telemetry)

        if self.pipeline.state != PipelineLifecycleState.PLANNED:
            self.pipeline.transition_to(PipelineLifecycleState.PLANNED)

        flush_trash = bool(self._pending_flush_trash)
        self._pending_flush_trash = False
        resume_exec = bool(getattr(self, "_pending_resume", False))
        setattr(self, "_pending_resume", False)

        settings_model = getattr(self.settings, "_settings_model", None)
        fields_set = getattr(settings_model, "model_fields_set", set()) or set()
        configured_policy = getattr(self.settings, "MOVE_ERROR_POLICY", None)
        if "MOVE_ERROR_POLICY" in fields_set and configured_policy:
            effective_error_policy = str(configured_policy)
        elif (
            isinstance(configured_policy, str)
            and configured_policy.strip().lower() != "rollback"
        ):
            effective_error_policy = configured_policy
        else:
            effective_error_policy = "partial_commit"

        result = self.pipeline.execute(
            exec_plan,
            progress_callback=move_progress_cb,
            resume=resume_exec,
            flush_trash=flush_trash,
            flush_trashed_only=flush_trash,
            error_policy=effective_error_policy,
        )
        summary = result.summary
        if not (isinstance(summary, dict) and summary.get("cancelled")):
            if clear_manual_edits:
                self._clear_manual_plan_edits()
            elif (
                hasattr(self, "selected_paths") and self.selected_paths is not None
            ):
                self.selected_paths.clear()
        if result.failed:
            msg = (
                f"Execution completed with {len(result.failed)} failed item(s). "
                f"Verified moves preserved; retry available in verification report."
            )
        else:
            reversible_count = (
                len(result.moved) + len(result.quarantined) + len(result.staged)
            )
            if (
                reversible_count == 0
                and isinstance(summary, dict)
                and not (summary.get("audit_report") or {}).get("records")
            ):
                raw_moves = int(summary.get("moves") or 0)
                reversible_count = max(0, raw_moves - len(result.trashed))
            undo_hint = " [Ctrl+Z] Undo available." if reversible_count > 0 else ""
            msg = (
                f"Execution completed successfully! {result.describe()}{undo_hint} "
                f"Summary: {summary}"
            )
        self.call_from_thread(self.announce, msg)
        from app.core.plan_format import format_trash_handoff_warning

        warn_msg = format_trash_handoff_warning(
            summary.get("trash_handoff") if isinstance(summary, dict) else None
        )
        if warn_msg:
            from app.ui.notifications import notify

            self.call_from_thread(self.announce, warn_msg)
            self.call_from_thread(lambda: notify(warn_msg, type="warning"))

        from app.core.audit_reporter import resolve_audit_report

        sess_base = self.app_session.base_dir if self.app_session else None
        base_dir: str = (
            sess_base
            if isinstance(sess_base, str) and sess_base
            else (self.base_dir or ".")
        )
        sess_id = (
            summary.get("session_id")
            if isinstance(summary, dict)
            else result.session_id
        )
        audit_report = resolve_audit_report(
            summary.get("audit_report") if isinstance(summary, dict) else None,
            base_dir,
            exec_plan,
            session_id=sess_id,
        )

        if audit_report:
            self.call_from_thread(self.action_open_audit_report, audit_report)
        # Rescan last: the scan worker replaces the AppSession this worker uses.
        self.call_from_thread(self._start_scan)
    except Exception as e:
        logger.error(f"Error executing moves: {e}")
        self.call_from_thread(self.announce, f"Execution error: {e}")
    finally:
        self.call_from_thread(self.reset_progress_bar)

run_scan_worker()

Execute scan and plan generation in worker thread.

Source code in app/ui/mixins/pipeline.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
@work(exclusive=True, thread=True)
def run_scan_worker(self: TUIHostProtocol) -> None:
    """Execute scan and plan generation in worker thread."""
    try:
        from app.core.session import AppSession

        if self.app_session:
            try:
                self.app_session.close()
            except Exception:
                pass

        s_dirs = getattr(self, "source_dirs", None) or (
            [self.base_dir] if self.base_dir else []
        )
        self.app_session = AppSession(
            self.settings,
            self.base_dir,
            source_dirs=getattr(self, "source_dirs", None),
        )

        from app.core.pipeline import PipelineLifecycleState, SortPipeline

        self.pipeline = SortPipeline(
            self.app_session,
            base_dir=self.base_dir,
            settings=self.settings,
        )
        self.pipeline.add_state_change_hook(self._handle_pipeline_state_transition)
        self.pipeline.add_telemetry_hook(self._handle_pipeline_telemetry)

        def scan_progress_cb(
            update_or_prog: Any, stage: str | None = None, **kwargs: Any
        ) -> None:
            self.call_from_thread(
                self._handle_progress_update, update_or_prog, stage, **kwargs
            )

        self.plan = self.pipeline.plan(
            progress_callback=scan_progress_cb,
            cancel_check=lambda: False,
        )
        files = self.pipeline.planned_items

        # Load locks & ratings
        try:
            docs = self.app_session.db.get_all_documents(
                self.base_dir, source_dirs=s_dirs
            )
            for d in docs:
                if len(d) > 3 and d[3]:
                    self.locked_files[d[0]] = d[3]
        except Exception:
            pass

        try:
            self._ratings_cache = self.app_session.db.get_all_document_ratings(
                self.base_dir
            )
        except Exception:
            pass

        try:
            from app.core.db_conn import DB_ERRORS

            loaded_manual: set[str] = set()
            for s_dir in s_dirs:
                if s_dir:
                    loaded_manual.update(
                        self.app_session.cache_manager.load_manual_folders(
                            str(s_dir)
                        )
                    )
            if loaded_manual:
                self._manual_empty_folders.update(loaded_manual)
            elif self._manual_empty_folders:
                for s_dir in s_dirs:
                    if s_dir:
                        self.app_session.cache_manager.save_manual_folders(
                            str(s_dir), self._manual_empty_folders
                        )
        except (*DB_ERRORS, OSError, RuntimeError, ValueError, TypeError) as mf_err:
            logger.debug(f"Manual folder cache sync skipped: {mf_err}")

        self._reapply_manual_plan_edits()
        self.call_from_thread(self.rebuild_tree)
        model_status = getattr(self.plan, "model_status", "HEALTHY")
        invalid_locks = getattr(self.plan, "invalid_locks", {}) or {}
        if not invalid_locks and isinstance(self.plan, dict):
            invalid_locks = self.plan.get("invalid_locks", {}) or {}
        num_invalid = len(invalid_locks)

        if model_status == "DEGRADED_FALLBACK" or (
            isinstance(self.plan, dict)
            and self.plan.get("model_status") == "DEGRADED_FALLBACK"
        ):
            reason = (
                getattr(self.plan, "degradation_reason", None)
                or self.plan.get("degradation_reason")
                or "Model unavailable"
            )
            rec_action = (
                getattr(self.plan, "recovery_action", None)
                or self.plan.get("recovery_action")
                or "Re-download model bundle"
            )
            msg = f"Scan complete (DEGRADED FALLBACK MODE: {reason}. Suggested action: {rec_action}). Analyzed {len(files)} files."
            self.call_from_thread(
                self.notify,
                f"Sorting plan generated in degraded fallback mode: {reason}",
                title=f"Suggested recovery action: {rec_action}",
                severity="warning",
            )
        else:
            msg = f"Scan complete. Analyzed {len(files)} files into proposed plan."

        if num_invalid > 0:
            lock_str = (
                "1 bad lock path was skipped"
                if num_invalid == 1
                else f"{num_invalid} bad lock paths were skipped"
            )
            msg += f" ({lock_str})."
        self.call_from_thread(self.announce, msg)
    except Exception as e:
        if hasattr(self, "pipeline") and self.pipeline:
            try:
                self.pipeline.transition_to(PipelineLifecycleState.FAILED)
            except Exception:
                pass
        logger.error(f"Error in run_scan_worker: {e}")
        self.call_from_thread(self.announce, f"Scan error: {e}")
    finally:
        self.call_from_thread(self.reset_progress_bar)
        if getattr(self, "_pending_ai_active_rescan", False):
            from app.ui.ai_runtime import trigger_ai_active_rescan_if_eligible

            self.call_from_thread(trigger_ai_active_rescan_if_eligible, self)

run_validation_worker()

Asynchronously verify plan integrity in background worker thread.

Source code in app/ui/mixins/pipeline.py
830
831
832
833
834
def run_validation_worker(self: TUIHostProtocol) -> Any:
    """Asynchronously verify plan integrity in background worker thread."""
    epoch = int(getattr(self, "_validation_epoch", 0)) + 1
    setattr(self, "_validation_epoch", epoch)
    return _start_validation_worker(self, epoch)

app.ui.mixins.selection

app.ui.mixins.selection

Plan tree selection, include/exclude, reassign, rename, lock and rating actions.

SelectionActionsMixin

Key-bound actions that select, edit and rate nodes in the plan tree.

Source code in app/ui/mixins/selection.py
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
class SelectionActionsMixin:
    """Key-bound actions that select, edit and rate nodes in the plan tree."""

    def register_visual_selected_node(
        self: TUIHostProtocol, node: TreeNode[Any]
    ) -> None:
        """Register node into visual range selection list when visual selection is active."""
        if not self.visual_select_active or not node:
            return
        if node not in self.visual_selected_nodes:
            self.visual_selected_nodes.append(node)

    def extend_shift_range_selection(
        self: TUIHostProtocol,
        anchor_node: TreeNode[Any] | None,
        target_node: TreeNode[Any] | None,
    ) -> None:
        """Extend transient edit selection across ``anchor_node`` and ``target_node`` [Shift+Up/Down]."""
        if not hasattr(self, "selected_paths") or self.selected_paths is None:
            self.selected_paths = set()
        query = self._get_current_search_query()
        added_any = False
        for node in (anchor_node, target_node):
            if node is None:
                continue
            data = getattr(node, "data", None)
            if not isinstance(data, dict) or data.get("is_empty_state"):
                continue
            if data.get("is_file"):
                info = data.get("info")
                file_infos = [info] if isinstance(info, dict) else []
            else:
                file_infos = collect_scoped_file_nodes(
                    self,
                    data.get("info", {}),
                    current_folder=str(data.get("folder") or ""),
                    query=query,
                )
            for fi in file_infos:
                _, found_k = _find_key_for_info(self.plan, fi)
                pid = resolve_file_selection_id(
                    self,
                    fi,
                    str(fi.get("key") or found_k or ""),
                    str(fi.get("folder") or ""),
                )
                if pid:
                    self.selected_paths.add(pid)
                    fi["is_selected"] = True
                    added_any = True
        if added_any:
            self.refresh_tree_selection_markers()
            self.announce(
                f"Extended selection to {len(self.selected_paths)} file item(s)."
            )

    def action_visual_range_select(self: TUIHostProtocol) -> None:
        """Toggle visual range selection mode [V]."""
        if self._is_text_control_focused():
            return
        self.visual_select_active = not self.visual_select_active
        if self.visual_select_active:
            self.visual_selected_nodes = []
            node = self._get_active_node()
            if node:
                self.visual_selected_nodes.append(node)
            self.refresh_tree_selection_markers()
            self.announce(
                "Visual range selection mode enabled. Move cursor [j/k/Up/Down] to extend range."
            )
        else:
            self.visual_selected_nodes = []
            self.refresh_tree_selection_markers()
            self.announce("Visual range selection mode disabled.")

    def action_toggle_selection(self: TUIHostProtocol) -> None:
        """Toggle transient edit selection ``[●]``/``[ ]`` for active node, folder, or visual range [Space]."""
        if self._is_text_control_focused():
            return
        if not hasattr(self, "selected_paths") or self.selected_paths is None:
            self.selected_paths = set()

        nodes_to_toggle = []
        if self.visual_select_active and self.visual_selected_nodes:
            nodes_to_toggle = list(self.visual_selected_nodes)
            self.visual_select_active = False
            self.visual_selected_nodes = []
        else:
            active_node = self._get_active_node()
            if active_node:
                nodes_to_toggle = [active_node]

        if not nodes_to_toggle:
            self.announce("Select a tree node to toggle edit selection [Space].")
            return

        query = self._get_current_search_query()
        file_infos_to_toggle: list[dict[str, Any]] = []
        seen_ids: set[int] = set()
        for n in nodes_to_toggle:
            data = getattr(n, "data", None)
            if not data or not isinstance(data, dict) or data.get("is_empty_state"):
                continue
            if data.get("is_file"):
                fi = data["info"]
                if isinstance(fi, dict) and id(fi) not in seen_ids:
                    seen_ids.add(id(fi))
                    file_infos_to_toggle.append(fi)
            else:
                info_dict = data.get("info", {})
                for fi in collect_scoped_file_nodes(
                    self,
                    info_dict,
                    current_folder=str(data.get("folder") or ""),
                    query=query,
                ):
                    if id(fi) not in seen_ids:
                        seen_ids.add(id(fi))
                        file_infos_to_toggle.append(fi)

        if not file_infos_to_toggle:
            self.announce("No file nodes found to toggle.")
            return

        toggle_pids: list[tuple[dict[str, Any], str]] = []
        for fi in file_infos_to_toggle:
            _, found_k = _find_key_for_info(self.plan, fi)
            pid = resolve_file_selection_id(
                self,
                fi,
                str(fi.get("key") or found_k or ""),
                str(fi.get("folder") or ""),
            )
            toggle_pids.append((fi, pid))

        all_selected = all(pid in self.selected_paths for _, pid in toggle_pids)
        new_selected = not all_selected

        for fi, pid in toggle_pids:
            fi["is_selected"] = new_selected
            if new_selected:
                self.selected_paths.add(pid)
            else:
                self.selected_paths.discard(pid)

        self.rebuild_tree(run_validation=False)
        status_str = "selected [●]" if new_selected else "unselected [ ]"
        self.announce(
            f"Toggled {len(file_infos_to_toggle)} document item(s) to {status_str}."
        )

    def _commit_visual_range_selection(self: TUIHostProtocol) -> list[dict[str, Any]]:
        """Commit active ``visual_selected_nodes`` into ``selected_paths`` and clear visual mode."""
        if not (self.visual_select_active and self.visual_selected_nodes):
            return []
        if not hasattr(self, "selected_paths") or self.selected_paths is None:
            self.selected_paths = set()
        query = self._get_current_search_query()
        committed: list[dict[str, Any]] = []
        seen_ids: set[int] = set()
        for n in list(self.visual_selected_nodes):
            data = getattr(n, "data", None)
            if not isinstance(data, dict) or data.get("is_empty_state"):
                continue
            if data.get("is_file"):
                fi = data.get("info")
                candidates = [fi] if isinstance(fi, dict) else []
            else:
                candidates = collect_scoped_file_nodes(
                    self,
                    data.get("info", {}),
                    current_folder=str(data.get("folder") or ""),
                    query=query,
                )
            for fi in candidates:
                if id(fi) not in seen_ids:
                    seen_ids.add(id(fi))
                    _, found_k = _find_key_for_info(self.plan, fi)
                    pid = resolve_file_selection_id(
                        self,
                        fi,
                        str(fi.get("key") or found_k or ""),
                        str(fi.get("folder") or ""),
                    )
                    if pid:
                        self.selected_paths.add(pid)
                    fi["is_selected"] = True
                    committed.append(fi)
        self.visual_select_active = False
        self.visual_selected_nodes = []
        return committed

    def _resolve_target_file_infos(
        self: TUIHostProtocol, *, include_excluded_on_root: bool = False
    ) -> list[dict[str, Any]]:
        """Resolve edit targets from ``selected_paths``/visual range, else focused file/folder subtree."""
        if not hasattr(self, "selected_paths") or self.selected_paths is None:
            self.selected_paths = set()
        committed_visual = SelectionActionsMixin._commit_visual_range_selection(self)
        query = self._get_current_search_query()
        visible_files = collect_scoped_file_nodes(self, self.plan, query=query)

        if self.selected_paths:
            selected_visible: list[dict[str, Any]] = []
            for f in visible_files:
                _, found_k = _find_key_for_info(self.plan, f)
                pid = resolve_file_selection_id(
                    self,
                    f,
                    str(f.get("key") or found_k or ""),
                    str(f.get("folder") or ""),
                )
                if pid in self.selected_paths or bool(f.get("is_selected")):
                    selected_visible.append(f)
            if selected_visible:
                return selected_visible
            if committed_visual:
                return committed_visual
            if not query:
                all_plan_files = self._collect_file_nodes_from_dict(self.plan)
                selected_all = [
                    f
                    for f in all_plan_files
                    if resolve_file_selection_id(
                        self,
                        f,
                        str(f.get("key") or ""),
                        str(f.get("folder") or ""),
                    )
                    in self.selected_paths
                ]
                if selected_all:
                    return selected_all

        active_node = self._get_active_node()
        if active_node is not None:
            data = getattr(active_node, "data", None)
            if isinstance(data, dict) and not data.get("is_empty_state"):
                if data.get("is_file"):
                    info = data["info"]
                    if (
                        query
                        and visible_files
                        and all(info is not f for f in visible_files)
                    ):
                        return []
                    return [info]
                folder_files = collect_scoped_file_nodes(
                    self,
                    data.get("info", {}),
                    current_folder=str(data.get("folder") or ""),
                    query=query,
                )
                return folder_files

        if include_excluded_on_root:
            return visible_files
        included_visible = [
            f
            for f in visible_files
            if f.get("is_checked", True) and not f.get("is_excluded", False)
        ]
        return included_visible if included_visible else visible_files

    def _get_target_file_infos(self: TUIHostProtocol) -> list[dict[str, Any]]:
        """Return selected file info dicts, or focused file/folder subtree when none selected."""
        return SelectionActionsMixin._resolve_target_file_infos(self)

    def action_exclude_selected(self: TUIHostProtocol) -> None:
        """Exclude selected items or focused file/folder from sorting plan [X]."""
        if self._is_text_control_focused():
            return
        if not hasattr(self, "excluded_paths") or self.excluded_paths is None:
            self.excluded_paths = set()

        target_files = self._get_target_file_infos()
        if not target_files:
            self.announce("No file items available to exclude.")
            return

        for fi in target_files:
            fi["is_checked"] = False
            fi["is_excluded"] = True
            _, found_k = _find_key_for_info(self.plan, fi)
            pid = resolve_file_selection_id(
                self,
                fi,
                str(fi.get("key") or found_k or ""),
                str(fi.get("folder") or ""),
            )
            if pid:
                self.excluded_paths.add(pid)
            db_b, doc_rel, abs_fp = _resolve_source_identity(
                self, file_key=found_k, filepath=fi.get("filepath"), info=fi
            )
            _record_manual_edit(
                self,
                db_b,
                doc_rel,
                abs_fp,
                is_checked=False,
                is_excluded=True,
            )

        self.rebuild_tree()
        self.announce(f"Excluded {len(target_files)} file(s) from sorting plan.")

    def action_include_selected(self: TUIHostProtocol) -> None:
        """Include selected items or focused file/folder in sorting plan [I]."""
        if self._is_text_control_focused():
            return
        if not hasattr(self, "excluded_paths") or self.excluded_paths is None:
            self.excluded_paths = set()

        target_files = SelectionActionsMixin._resolve_target_file_infos(
            self, include_excluded_on_root=True
        )
        if not target_files:
            self.announce("No file items available to include.")
            return

        for fi in target_files:
            fi["is_checked"] = True
            fi["is_excluded"] = False
            _, found_k = _find_key_for_info(self.plan, fi)
            pid = resolve_file_selection_id(
                self,
                fi,
                str(fi.get("key") or found_k or ""),
                str(fi.get("folder") or ""),
            )
            if pid:
                self.excluded_paths.discard(pid)
            db_b, doc_rel, abs_fp = _resolve_source_identity(
                self, file_key=found_k, filepath=fi.get("filepath"), info=fi
            )
            _record_manual_edit(
                self,
                db_b,
                doc_rel,
                abs_fp,
                is_checked=True,
                is_excluded=False,
            )

        self.rebuild_tree()
        self.announce(f"Included {len(target_files)} file(s) in sorting plan.")

    def action_reassign_selected(self: TUIHostProtocol) -> None:
        """Bulk reassign checked file items or active node to target category [R]."""
        if self._is_text_control_focused():
            return

        target_files = self._get_target_file_infos()
        if not target_files:
            self.announce("No file items available to reassign.")
            return

        from app.core.scanner import discover_existing_folders

        plan_folders = _collect_plan_folders(self.plan)
        disk_folders = discover_existing_folders(
            getattr(self, "base_dir", None),
            settings=getattr(self, "settings", None),
        )
        existing_folders: list[str] = []
        seen_folders: set[str] = set()
        for folder in plan_folders + disk_folders:
            if folder and folder.lower() not in seen_folders:
                seen_folders.add(folder.lower())
                existing_folders.append(folder)

        def on_reassigned(raw_target_folder: str | None) -> None:
            if not raw_target_folder:
                return

            from app.core.metadata import derive_learned_pattern_for_files
            from app.core.path_utils import (
                _disambiguate_key,
                _is_absolute_path,
                prune_empty_plan_ancestors,
            )

            has_explicit_rule_choice = hasattr(raw_target_folder, "learn_rule")
            explicit_learn_rule = bool(getattr(raw_target_folder, "learn_rule", False))
            explicit_learned_pattern = str(
                getattr(raw_target_folder, "learned_pattern", "") or ""
            ).strip()
            target_folder = str(raw_target_folder)

            host: Any = self
            can_learn_rule = False
            if not _is_absolute_path(target_folder):
                try:
                    target_folder = _normalize_validated_folder(target_folder)
                    can_learn_rule = True
                except ValueError as err:
                    host.announce(
                        f"Invalid destination folder: {err}", priority="assertive"
                    )
                    return

            from app.config import resolve_scoped_settings

            settings_obj = getattr(host, "settings", None)
            scoped_learned_updates: dict[str, dict[str, str]] = {}
            manual_folders = getattr(host, "_manual_empty_folders", set())

            fallback_shared_pattern = ""
            if not has_explicit_rule_choice and can_learn_rule:
                cand_names = [
                    str(
                        fi.get("source_path")
                        or fi.get("source")
                        or fi.get("filepath")
                        or fi.get("target_filename")
                        or fi.get("key")
                        or ""
                    )
                    for fi in target_files
                    if isinstance(fi, dict)
                ]
                fallback_shared_pattern, _stops, is_gen_only = (
                    derive_learned_pattern_for_files(cand_names)
                )
                if is_gen_only:
                    fallback_shared_pattern = ""

            reassigned_count = 0
            for fi in target_files:
                found_folder, old_container, _ = _find_file_in_plan(
                    host.plan,
                    str(fi.get("target_filename") or fi.get("key") or ""),
                    target_info=fi,
                )
                file_key = None
                if old_container is not None:
                    for k, v in list(old_container.items()):
                        if v is fi:
                            file_key = k
                            break
                if not file_key:
                    file_key = fi.get("target_filename") or fi.get("key")
                old_folder = found_folder or fi.get("folder", "")
                if old_container is None and old_folder:
                    old_container = _resolve_plan_folder_dict(host.plan, old_folder)

                if file_key and old_container is not None:
                    db_base, doc_relpath, abs_fp = _resolve_source_identity(
                        host,
                        file_key=str(file_key),
                        filepath=fi.get("filepath"),
                        info=fi,
                    )
                    if doc_relpath and not fi.get("source_path"):
                        fi["source_path"] = doc_relpath
                    if abs_fp and not fi.get("filepath"):
                        fi["filepath"] = abs_fp

                    old_container.pop(file_key, None)
                    if old_folder and old_folder != target_folder:
                        prune_empty_plan_ancestors(
                            host.plan, old_folder, preserve_folders=manual_folders
                        )
                    target_container = _resolve_plan_folder_dict(
                        host.plan, target_folder, create=True
                    )
                    if target_container is None:
                        host.plan[target_folder] = {}
                        target_container = host.plan[target_folder]

                    # Non-clobbering mutation with automatic numeric disambiguation
                    if (
                        file_key in target_container
                        and target_container[file_key] is not fi
                    ):
                        dest_key = _disambiguate_key(
                            target_container, file_key, is_file=True
                        )
                        fi["target_filename"] = dest_key
                        fi["confirmed"] = True
                    else:
                        dest_key = file_key

                    target_container[dest_key] = fi
                    fi["folder"] = target_folder
                    fi["is_locked"] = True
                    _update_node_relative_source(fi, db_base, abs_fp, target_folder)
                    host.locked_files[dest_key] = target_folder

                    if doc_relpath:
                        host.locked_files[doc_relpath] = target_folder
                        persisted_tf = (
                            str(fi["target_filename"])
                            if fi.get("target_filename")
                            else None
                        )
                        if host.app_session:
                            host.app_session.db.set_user_verified_target_path(
                                db_base,
                                doc_relpath,
                                target_folder,
                                target_name=persisted_tf,
                            )
                        edit_kwargs: dict[str, Any] = {
                            "folder": target_folder,
                            "is_locked": True,
                        }
                        if fi.get("target_filename"):
                            edit_kwargs["target_filename"] = fi["target_filename"]
                            edit_kwargs["confirmed"] = True
                        _record_manual_edit(
                            host, db_base, doc_relpath, abs_fp, **edit_kwargs
                        )

                    if can_learn_rule and settings_obj is not None:
                        pattern_to_save = ""
                        if has_explicit_rule_choice:
                            if explicit_learn_rule and explicit_learned_pattern:
                                pattern_to_save = explicit_learned_pattern.lower()
                        else:
                            pattern_to_save = fallback_shared_pattern
                        if pattern_to_save:
                            scope_dir = str(
                                db_base or getattr(host, "base_dir", "") or ""
                            )
                            scoped_learned_updates.setdefault(scope_dir, {})[
                                pattern_to_save
                            ] = target_folder

                    reassigned_count += 1

            saved_rule_patterns: list[str] = []
            if scoped_learned_updates and settings_obj is not None:
                for scope_dir, updates in scoped_learned_updates.items():
                    scoped_view = resolve_scoped_settings(
                        settings_obj,
                        scope_dir if scope_dir else None,
                        fallback_to_global=True,
                    )
                    learned_rules = dict(
                        getattr(scoped_view, "LEARNED_RULES", {}) or {}
                    )
                    dis_learned = dict(
                        getattr(scoped_view, "DISABLED_LEARNED_RULES", {}) or {}
                    )
                    dis_changed = False
                    for pat, dest in updates.items():
                        learned_rules[pat] = dest
                        if pat not in saved_rule_patterns:
                            saved_rule_patterns.append(pat)
                        if pat in dis_learned:
                            dis_learned.pop(pat, None)
                            dis_changed = True
                    scoped_view.LEARNED_RULES = learned_rules
                    if dis_changed:
                        scoped_view.DISABLED_LEARNED_RULES = dis_learned
                if hasattr(settings_obj, "flush"):
                    settings_obj.flush()

            host.rebuild_tree()
            if saved_rule_patterns:
                host.announce(
                    f"Reassigned {reassigned_count} file(s) to folder '{target_folder}' "
                    f"and saved filename rule '{saved_rule_patterns[0]}' (priority 90)."
                )
            else:
                host.announce(
                    f"Reassigned {reassigned_count} file(s) to folder '{target_folder}'."
                )

        self.push_screen(
            ReassignModal(
                existing_folders,
                count=len(target_files),
                plan=self.plan,
                base_dir=self.base_dir,
                target_files=target_files,
                settings=getattr(self, "settings", None),
            ),
            on_reassigned,
        )

    def action_toggle_select_all(self: TUIHostProtocol) -> None:
        """Toggle Select All / Deselect All transient edit selection in plan [A]."""
        if self._is_text_control_focused():
            return
        if not hasattr(self, "selected_paths") or self.selected_paths is None:
            self.selected_paths = set()

        all_files = self._collect_file_nodes_from_dict(self.plan)
        if not all_files:
            self.announce("No file items available to select/deselect.")
            return

        query = self._get_current_search_query()
        if query:
            target_files = self._collect_visible_file_nodes_from_dict(
                self.plan, query=query
            )
        else:
            target_files = all_files

        if not target_files:
            self.announce(
                f"No visible file items matching '{query}' to select/deselect."
            )
            return

        target_pids: list[tuple[dict[str, Any], str]] = []
        for f in target_files:
            _, found_k = _find_key_for_info(self.plan, f)
            pid = resolve_file_selection_id(
                self,
                f,
                str(f.get("key") or found_k or ""),
                str(f.get("folder") or ""),
            )
            target_pids.append((f, pid))

        all_selected = all(pid in self.selected_paths for _, pid in target_pids)
        new_state = not all_selected

        for f, pid in target_pids:
            f["is_selected"] = new_state
            if new_state:
                self.selected_paths.add(pid)
            else:
                self.selected_paths.discard(pid)

        self.rebuild_tree(run_validation=False)

        if query:
            hidden_count = len(all_files) - len(target_files)
            status_str = "Selected" if new_state else "Deselected"
            if hidden_count > 0:
                self.announce(
                    f"{status_str} {len(target_files)} visible file item(s) ({hidden_count} hidden files unchanged)."
                )
            else:
                self.announce(f"{status_str} {len(target_files)} visible file item(s).")
        else:
            status_str = "Selected all" if new_state else "Deselected all"
            self.announce(f"{status_str} {len(all_files)} file item(s).")

    def action_invert_selection(self: TUIHostProtocol) -> None:
        """Invert transient edit selection across visible file items in ``#plan-tree``."""
        if not hasattr(self, "selected_paths") or self.selected_paths is None:
            self.selected_paths = set()

        all_files = self._collect_file_nodes_from_dict(self.plan)
        if not all_files:
            self.announce("No file items available to invert selection.")
            return

        query = self._get_current_search_query()
        target_files = (
            self._collect_visible_file_nodes_from_dict(self.plan, query=query)
            if query
            else all_files
        )
        if not target_files:
            self.announce(
                f"No visible file items matching '{query}' to invert selection."
            )
            return

        now_selected = 0
        for f in target_files:
            _, found_k = _find_key_for_info(self.plan, f)
            pid = resolve_file_selection_id(
                self,
                f,
                str(f.get("key") or found_k or ""),
                str(f.get("folder") or ""),
            )
            if pid in self.selected_paths:
                self.selected_paths.discard(pid)
                f["is_selected"] = False
            else:
                self.selected_paths.add(pid)
                f["is_selected"] = True
                now_selected += 1

        self.rebuild_tree(run_validation=False)
        self.announce(
            f"Inverted selection: {now_selected} of {len(target_files)} visible file item(s) selected."
        )

    def _get_executable_plan(
        self: TUIHostProtocol,
        plan_dict: dict[str, Any] | None = None,
        _prefix: str = "",
        *,
        visible_only: bool = False,
        _visible_ids: set[int] | None = None,
    ) -> dict[str, Any]:
        """Return filtered plan dictionary containing included files and manual empty folders."""
        root_call = plan_dict is None
        if plan_dict is None:
            plan_dict = self.plan

        query = self._get_current_search_query() if visible_only else ""
        if visible_only and query and root_call and _visible_ids is None:
            _visible_ids = {
                id(f)
                for f in self._collect_visible_file_nodes_from_dict(
                    plan_dict, query=query
                )
            }

        manual_folders: set[str] = set(
            getattr(self, "_manual_empty_folders", None) or set()
        )
        result: dict[str, Any] = {}
        for k, v in plan_dict.items():
            if isinstance(v, dict) and v.get("__type__") == "file":
                if _visible_ids is not None and id(v) not in _visible_ids:
                    continue
                is_checked = v.get("is_checked", True)
                is_excluded = v.get("is_excluded", False)
                is_neg_rated = str(v.get("rating") or "").lower() == "negative"
                if is_checked and not is_excluded and not is_neg_rated:
                    result[k] = v
            elif isinstance(v, dict):
                sub_path = f"{_prefix}/{k}" if _prefix else k
                sub = SelectionActionsMixin._get_executable_plan(
                    self,
                    v,
                    _prefix=sub_path,
                    visible_only=visible_only,
                    _visible_ids=_visible_ids,
                )
                manual_match = sub_path in manual_folders and (
                    not query
                    or (
                        not _is_structured_tree_query(query)
                        and query in sub_path.lower()
                    )
                )
                if sub or manual_match:
                    result[k] = sub
            else:
                result[k] = v
        return result

    def action_toggle_lock(self: TUIHostProtocol) -> None:
        """Toggle node lock state for selected files or focused file/folder [Ctrl+L]."""
        if self._is_text_control_focused(allow_tree_search=True):
            return

        SelectionActionsMixin._commit_visual_range_selection(self)
        node = self._get_active_node()
        has_selection = bool(getattr(self, "selected_paths", None))

        target_files: list[dict[str, Any]] = []
        if has_selection:
            target_files = self._get_target_file_infos()
        elif (
            node and isinstance(node.data, dict) and not node.data.get("is_empty_state")
        ):
            if node.data.get("is_file"):
                info_obj = node.data.get("info")
                if isinstance(info_obj, dict):
                    target_files = [info_obj]
            else:
                query = self._get_current_search_query()
                target_files = collect_scoped_file_nodes(
                    self,
                    node.data.get("info", {}),
                    current_folder=str(node.data.get("folder") or ""),
                    query=query,
                )

        if not target_files:
            self.announce("Select a file or folder node to toggle lock [Ctrl+L].")
            return

        def _is_info_locked(fi: dict[str, Any]) -> bool:
            _, found_k = _find_key_for_info(self.plan, fi)
            fkey = str(fi.get("key") or found_k or "")
            fp = str(fi.get("filepath") or "")
            _, d_rel, _ = _resolve_source_identity(
                self, file_key=fkey, filepath=fp or None, info=fi
            )
            return (
                bool(fi.get("is_locked"))
                or (bool(fkey) and fkey in self.locked_files)
                or (bool(fp) and fp in self.locked_files)
                or (bool(d_rel) and d_rel in self.locked_files)
                or (
                    not has_selection
                    and len(target_files) == 1
                    and node is not None
                    and isinstance(node.data, dict)
                    and node.data.get("is_file")
                    and bool(node.data.get("is_locked"))
                )
            )

        all_locked = all(_is_info_locked(fi) for fi in target_files)
        should_lock = not all_locked

        last_key = ""
        last_folder = ""
        for fi in target_files:
            found_folder, found_k = _find_key_for_info(self.plan, fi)
            file_key = str(
                found_k
                or fi.get("key")
                or (
                    node.data.get("key")
                    if (
                        not has_selection
                        and len(target_files) == 1
                        and node
                        and isinstance(node.data, dict)
                    )
                    else ""
                )
                or ""
            )
            folder = str(
                found_folder
                or fi.get("folder")
                or (
                    node.data.get("folder")
                    if (
                        not has_selection
                        and len(target_files) == 1
                        and node
                        and isinstance(node.data, dict)
                    )
                    else ""
                )
                or ""
            )
            filepath = str(
                fi.get("filepath")
                or (
                    node.data.get("filepath")
                    if (
                        not has_selection
                        and len(target_files) == 1
                        and node
                        and isinstance(node.data, dict)
                    )
                    else ""
                )
                or ""
            )
            last_key = file_key
            last_folder = folder
            db_base, doc_relpath, abs_fp = _resolve_source_identity(
                self, file_key=file_key, filepath=filepath or None, info=fi
            )
            if not should_lock:
                self.locked_files.pop(file_key, None)
                if filepath:
                    self.locked_files.pop(filepath, None)
                if doc_relpath:
                    self.locked_files.pop(doc_relpath, None)
                fi["is_locked"] = False
                if self.app_session and doc_relpath:
                    self.app_session.db.set_user_verified_target_path(
                        db_base, doc_relpath, None
                    )
                _record_manual_edit(
                    self,
                    db_base,
                    doc_relpath,
                    abs_fp,
                    folder=None,
                    target_filename=None,
                    is_locked=False,
                )
            else:
                if file_key:
                    self.locked_files[file_key] = folder
                if doc_relpath:
                    self.locked_files[doc_relpath] = folder
                fi["is_locked"] = True
                locked_tf = (
                    str(fi["target_filename"]) if fi.get("target_filename") else None
                )
                if self.app_session and doc_relpath:
                    self.app_session.db.set_user_verified_target_path(
                        db_base, doc_relpath, folder, target_name=locked_tf
                    )
                edit_kwargs: dict[str, Any] = {"folder": folder, "is_locked": True}
                if locked_tf:
                    edit_kwargs["target_filename"] = locked_tf
                    edit_kwargs["confirmed"] = True
                _record_manual_edit(self, db_base, doc_relpath, abs_fp, **edit_kwargs)

        if (
            node is not None
            and isinstance(node.data, dict)
            and node.data.get("is_file")
            and node.data.get("info") in target_files
        ):
            node.data["is_locked"] = should_lock

        if len(target_files) == 1:
            msg = (
                f"Locked file '{last_key}' to folder '{last_folder}'"
                if should_lock
                else f"Unlocked file '{last_key}'"
            )
        else:
            action_word = "Locked" if should_lock else "Unlocked"
            msg = f"{action_word} {len(target_files)} file(s) in sorting plan."

        self.announce(msg)
        self.rebuild_tree()

    def _get_checked_file_keys(self: TUIHostProtocol) -> list[str]:
        """Collect keys of checked, non-excluded file nodes."""
        entries = self._get_checked_file_entries()
        return [e["key"] for e in entries if e.get("key")]

    def _get_checked_file_entries(self: TUIHostProtocol) -> list[dict[str, Any]]:
        """Collect full metadata entries for checked, non-excluded file nodes."""
        entries: list[dict[str, Any]] = []

        # 1. First attempt to gather from tree widget to preserve visual display order
        try:
            from textual.widgets import Tree

            from app.core.pattern_formatter import resolve_disk_file_date

            tree = self.query_one("#plan-tree", Tree)
            seen_ids = set()

            def _resolve_fp_and_date(
                key_val: str,
                folder_val: str,
                info_dict: dict[str, Any],
                explicit_fp: str | None = None,
            ) -> tuple[str | None, str]:
                fp = _resolve_source_disk_path(
                    getattr(self, "base_dir", None),
                    key_val,
                    folder_val,
                    info_dict,
                    explicit_fp=explicit_fp,
                )
                f_date = str(
                    info_dict.get("date")
                    or info_dict.get("file_date")
                    or resolve_disk_file_date(
                        fp, base_dir=getattr(self, "base_dir", None)
                    )
                    or ""
                )
                return fp, f_date

            def _walk(node: TreeNode) -> None:
                data = getattr(node, "data", None)
                if data and isinstance(data, dict) and data.get("is_file"):
                    info = data.get("info", {})
                    if not isinstance(info, dict):
                        info = {}
                    is_checked = data.get("is_checked", True)
                    is_excluded = data.get("is_excluded", False)
                    if is_checked and not is_excluded:
                        info_id = id(info) if info else id(data)
                        if info_id not in seen_ids:
                            seen_ids.add(info_id)
                            entry_key = (
                                data.get("key") or info.get("target_filename") or ""
                            )
                            entry_folder = str(
                                data.get("folder") or info.get("folder", "")
                            )
                            resolved_fp, resolved_date = _resolve_fp_and_date(
                                str(entry_key),
                                entry_folder,
                                info,
                                data.get("filepath"),
                            )
                            _, doc_rel, _ = _resolve_source_identity(
                                self,
                                file_key=str(entry_key),
                                filepath=resolved_fp,
                                info=info,
                            )
                            entries.append(
                                {
                                    "key": entry_key,
                                    "folder": data.get("folder")
                                    or info.get("folder", ""),
                                    "info": info,
                                    "filepath": resolved_fp,
                                    "source_path": info.get("source_path") or doc_rel,
                                    "date": resolved_date,
                                    "file_date": resolved_date,
                                    "category": data.get("folder")
                                    or info.get("folder", ""),
                                }
                            )
                for child in node.children:
                    _walk(child)

            _walk(tree.root)
            if entries:
                return entries
        except Exception:
            pass

        # 2. Fall back to traversing self.plan dictionary
        if not hasattr(self, "plan") or not isinstance(self.plan, dict):
            return entries

        from app.core.pattern_formatter import resolve_disk_file_date

        seen_plan_ids = set()

        def _walk_plan(d: dict[str, Any], current_folder: str = "") -> None:
            for k, v in d.items():
                if isinstance(v, dict):
                    if v.get("__type__") == "file":
                        is_checked = v.get("is_checked", True)
                        is_excluded = v.get("is_excluded", False)
                        if is_checked and not is_excluded:
                            v_id = id(v)
                            if v_id not in seen_plan_ids:
                                seen_plan_ids.add(v_id)
                                fp = _resolve_source_disk_path(
                                    getattr(self, "base_dir", None),
                                    k,
                                    str(v.get("folder") or current_folder),
                                    v,
                                    explicit_fp=v.get("filepath"),
                                )
                                resolved_date = str(
                                    v.get("date")
                                    or v.get("file_date")
                                    or resolve_disk_file_date(
                                        fp, base_dir=getattr(self, "base_dir", None)
                                    )
                                    or ""
                                )
                                _, doc_rel_p, _ = _resolve_source_identity(
                                    self,
                                    file_key=k,
                                    filepath=fp,
                                    info=v,
                                )
                                entries.append(
                                    {
                                        "key": k,
                                        "folder": v.get("folder") or current_folder,
                                        "info": v,
                                        "filepath": fp,
                                        "source_path": v.get("source_path")
                                        or doc_rel_p,
                                        "date": resolved_date,
                                        "file_date": resolved_date,
                                        "category": v.get("folder") or current_folder,
                                    }
                                )
                    else:
                        sub = f"{current_folder}/{k}" if current_folder else k
                        _walk_plan(v, sub)

        _walk_plan(self.plan)
        return entries

    def _get_selected_file_entries(self: TUIHostProtocol) -> list[dict[str, Any]]:
        """Collect metadata entries for files in ``selected_paths`` (scoped to active filter)."""
        selected_set: set[str] = set(getattr(self, "selected_paths", None) or set())
        if not selected_set:
            return []

        from textual.widgets import Tree

        from app.core.pattern_formatter import resolve_disk_file_date

        entries: list[dict[str, Any]] = []
        query = self._get_current_search_query()
        visible_id_set: set[int] | None = None
        if query and isinstance(self.plan, dict):
            visible_id_set = {
                id(f)
                for f in self._collect_visible_file_nodes_from_dict(
                    self.plan, query=query
                )
            }

        tree_matches = self.query("#plan-tree")
        if tree_matches:
            tree = tree_matches.first(Tree)
            seen_ids: set[int] = set()

            def _walk_sel(node: TreeNode[Any]) -> None:
                data = getattr(node, "data", None)
                if isinstance(data, dict) and data.get("is_file"):
                    info = data.get("info")
                    info_dict = info if isinstance(info, dict) else {}
                    if (
                        visible_id_set is not None
                        and id(info_dict) not in visible_id_set
                    ):
                        return
                    entry_key = str(
                        data.get("key") or info_dict.get("target_filename") or ""
                    )
                    entry_folder = str(
                        data.get("folder") or info_dict.get("folder", "")
                    )
                    pid = resolve_file_selection_id(
                        self, info_dict, entry_key, entry_folder
                    )
                    if pid in selected_set or bool(info_dict.get("is_selected")):
                        info_id = id(info_dict) if info_dict else id(data)
                        if info_id not in seen_ids:
                            seen_ids.add(info_id)
                            resolved_fp = _resolve_source_disk_path(
                                getattr(self, "base_dir", None),
                                entry_key,
                                entry_folder,
                                info_dict,
                                explicit_fp=data.get("filepath"),
                            )
                            resolved_date = str(
                                info_dict.get("date")
                                or info_dict.get("file_date")
                                or resolve_disk_file_date(
                                    resolved_fp,
                                    base_dir=getattr(self, "base_dir", None),
                                )
                                or ""
                            )
                            _, doc_rel, _ = _resolve_source_identity(
                                self,
                                file_key=entry_key,
                                filepath=resolved_fp,
                                info=info_dict,
                            )
                            entries.append(
                                {
                                    "key": entry_key,
                                    "folder": entry_folder,
                                    "info": info_dict,
                                    "filepath": resolved_fp,
                                    "source_path": info_dict.get("source_path")
                                    or doc_rel,
                                    "date": resolved_date,
                                    "file_date": resolved_date,
                                    "category": entry_folder,
                                    "node_data": data,
                                }
                            )
                for child in node.children:
                    _walk_sel(child)

            _walk_sel(tree.root)
            if entries:
                return entries

        if not isinstance(self.plan, dict):
            return entries

        seen_plan_ids: set[int] = set()

        def _walk_plan_sel(d: dict[str, Any], current_folder: str = "") -> None:
            for k, v in d.items():
                if isinstance(v, dict):
                    if v.get("__type__") == "file":
                        if visible_id_set is not None and id(v) not in visible_id_set:
                            continue
                        pid = resolve_file_selection_id(
                            self, v, k, str(v.get("folder") or current_folder)
                        )
                        if pid in selected_set or bool(v.get("is_selected")):
                            vid = id(v)
                            if vid not in seen_plan_ids:
                                seen_plan_ids.add(vid)
                                fp = _resolve_source_disk_path(
                                    getattr(self, "base_dir", None),
                                    k,
                                    str(v.get("folder") or current_folder),
                                    v,
                                    explicit_fp=v.get("filepath"),
                                )
                                resolved_date = str(
                                    v.get("date")
                                    or v.get("file_date")
                                    or resolve_disk_file_date(
                                        fp,
                                        base_dir=getattr(self, "base_dir", None),
                                    )
                                    or ""
                                )
                                _, doc_rel_p, _ = _resolve_source_identity(
                                    self, file_key=k, filepath=fp, info=v
                                )
                                fld = str(v.get("folder") or current_folder)
                                entries.append(
                                    {
                                        "key": k,
                                        "folder": fld,
                                        "info": v,
                                        "filepath": fp,
                                        "source_path": v.get("source_path")
                                        or doc_rel_p,
                                        "date": resolved_date,
                                        "file_date": resolved_date,
                                        "category": fld,
                                    }
                                )
                    else:
                        sub = f"{current_folder}/{k}" if current_folder else k
                        _walk_plan_sel(v, sub)

        _walk_plan_sel(self.plan)
        return entries

    def action_rename_node(self: TUIHostProtocol) -> None:
        """Rename selected file(s) or focused file/folder category node [F2]."""
        if self._is_text_control_focused(allow_tree_search=True):
            return

        SelectionActionsMixin._commit_visual_range_selection(self)
        selected_entries = SelectionActionsMixin._get_selected_file_entries(self)
        selected_keys = [e["key"] for e in selected_entries if e.get("key")]
        node = self._get_active_node()

        # If no edit selection is active and a folder category node is focused, rename folder
        if (
            not selected_keys
            and node
            and node.data
            and not node.data.get("is_file")
            and not node.data.get("is_empty_state")
        ):
            data = node.data
            old_name = str(data.get("key") or "")
            old_folder_path = str(data.get("folder") or old_name)
            modal = RenameModal(
                title=f"Rename Folder: {old_folder_path}",
                current_name=old_name,
                category=old_folder_path,
                is_folder=True,
                plan=self.plan,
                base_dir=self.base_dir,
            )

            def on_folder_renamed(new_name: str | Any | None) -> None:
                if not new_name:
                    return

                from app.core.path_utils import (
                    _is_absolute_path,
                    _merge_plan_dicts,
                    prune_empty_plan_ancestors,
                )

                dest_override = getattr(new_name, "destination_override", None)
                if isinstance(new_name, tuple):
                    new_name_str = str(new_name[0])
                else:
                    new_name_str = str(new_name)
                raw_target = str(dest_override if dest_override else new_name_str)
                if not raw_target:
                    return

                if dest_override or _is_absolute_path(raw_target):
                    eff_folder_path = (
                        raw_target
                        if _is_absolute_path(raw_target)
                        else raw_target.replace("\\", "/").strip("/")
                    )
                elif "/" in raw_target or "\\" in raw_target:
                    eff_folder_path = raw_target.replace("\\", "/").strip("/")
                elif (
                    "/" in old_folder_path
                    and not _is_absolute_path(old_folder_path)
                    and old_folder_path not in self.plan
                ):
                    parent_prefix = old_folder_path.rsplit("/", 1)[0]
                    eff_folder_path = f"{parent_prefix}/{raw_target}"
                else:
                    eff_folder_path = raw_target

                if not _is_absolute_path(eff_folder_path):
                    try:
                        eff_folder_path = _normalize_validated_folder(eff_folder_path)
                    except ValueError as err:
                        self.announce(
                            f"Invalid folder path: {err}", priority="assertive"
                        )
                        return

                if not eff_folder_path or eff_folder_path == old_folder_path:
                    return

                manual_folders = getattr(self, "_manual_empty_folders", set())
                old_content: dict[str, Any] | None = None
                popped_parent_prefix = ""
                if old_folder_path in self.plan and isinstance(
                    self.plan[old_folder_path], dict
                ):
                    old_content = self.plan.pop(old_folder_path)
                elif "/" in old_folder_path and not _is_absolute_path(old_folder_path):
                    parent_prefix, leaf_name = old_folder_path.rsplit("/", 1)
                    parent_dict = _resolve_plan_folder_dict(self.plan, parent_prefix)
                    if parent_dict is not None and isinstance(
                        parent_dict.get(leaf_name), dict
                    ):
                        old_content = parent_dict.pop(leaf_name)
                        popped_parent_prefix = parent_prefix
                elif old_name in self.plan and isinstance(self.plan[old_name], dict):
                    old_content = self.plan.pop(old_name)

                if old_content is None:
                    return

                if manual_folders:
                    updated_manual: set[str] = set()
                    changed_manual = False
                    for mf in manual_folders:
                        if mf == old_folder_path:
                            updated_manual.add(eff_folder_path)
                            changed_manual = True
                        elif mf.startswith(f"{old_folder_path}/"):
                            suffix = mf[len(old_folder_path) + 1 :]
                            updated_manual.add(f"{eff_folder_path}/{suffix}")
                            changed_manual = True
                        else:
                            updated_manual.add(mf)
                    if changed_manual:
                        self._manual_empty_folders = updated_manual
                        manual_folders = updated_manual
                        _persist_manual_folders_to_cache(self)

                if popped_parent_prefix:
                    prune_empty_plan_ancestors(
                        self.plan,
                        popped_parent_prefix,
                        preserve_folders=manual_folders,
                    )

                def _recursively_update_folder(
                    content_dict: dict[str, Any], parent_folder: str
                ) -> None:
                    for k, v in content_dict.items():
                        if isinstance(v, dict):
                            if v.get("__type__") == "file":
                                db_b, doc_rel, abs_fp = _resolve_source_identity(
                                    self,
                                    file_key=k,
                                    filepath=v.get("filepath"),
                                    info=v,
                                )
                                if doc_rel and not v.get("source_path"):
                                    v["source_path"] = doc_rel
                                if abs_fp and not v.get("filepath"):
                                    v["filepath"] = abs_fp
                                v["folder"] = parent_folder
                                v["is_locked"] = True
                                _update_node_relative_source(
                                    v, db_b, abs_fp, parent_folder
                                )
                                self.locked_files[k] = parent_folder
                                if doc_rel:
                                    self.locked_files[doc_rel] = parent_folder
                                    persisted_tf = (
                                        str(v["target_filename"])
                                        if v.get("target_filename")
                                        else None
                                    )
                                    if self.app_session:
                                        self.app_session.db.set_user_verified_target_path(
                                            db_b,
                                            doc_rel,
                                            parent_folder,
                                            target_name=persisted_tf,
                                        )
                                    edit_kwargs: dict[str, Any] = {
                                        "folder": parent_folder,
                                        "is_locked": True,
                                    }
                                    if persisted_tf:
                                        edit_kwargs["target_filename"] = persisted_tf
                                        edit_kwargs["confirmed"] = True
                                    _record_manual_edit(
                                        self,
                                        db_b,
                                        doc_rel,
                                        abs_fp,
                                        **edit_kwargs,
                                    )
                            else:
                                sub = f"{parent_folder}/{k}" if parent_folder else k
                                _recursively_update_folder(v, sub)

                existing_dest = _resolve_plan_folder_dict(
                    self.plan, eff_folder_path, create=False
                )
                remapped_rules = _remap_learned_rules_for_folder_rename(
                    getattr(self, "settings", None),
                    old_folder_path,
                    eff_folder_path,
                    base_dir=getattr(self, "base_dir", None),
                )
                remap_suffix = (
                    f" (updated {remapped_rules} learned rule(s))"
                    if remapped_rules > 0
                    else ""
                )
                if existing_dest is not None:
                    _merge_plan_dicts(existing_dest, old_content)
                    _recursively_update_folder(existing_dest, eff_folder_path)
                    self.rebuild_tree(run_validation=True)
                    self.announce(
                        f"Merged folder category '{old_folder_path}' into '{eff_folder_path}'{remap_suffix}"
                    )
                else:
                    dest_dict = _resolve_plan_folder_dict(
                        self.plan, eff_folder_path, create=True
                    )
                    if dest_dict is None:
                        self.plan[eff_folder_path] = old_content
                        dest_dict = self.plan[eff_folder_path]
                    else:
                        dest_dict.update(old_content)
                    _recursively_update_folder(dest_dict, eff_folder_path)
                    self.rebuild_tree(run_validation=True)
                    self.announce(
                        f"Renamed folder category '{old_folder_path}' -> '{eff_folder_path}'{remap_suffix}"
                    )

            self.push_screen(modal, on_folder_renamed)
            return

        checked_entries = selected_entries
        checked_keys = selected_keys

        # Branch to batch rename when multiple files are selected for edit
        if len(checked_keys) > 1:
            first_folder = checked_entries[0].get("folder", "")
            default_batch_pattern = (
                str(
                    getattr(getattr(self, "settings", None), "RENAME_PATTERN", "") or ""
                ).strip()
                or "{category}_{original}"
            )
            modal = RenameModal(
                title=f"Batch Rename ({len(checked_entries)} files)",
                current_name=default_batch_pattern,
                category=first_folder,
                file_date=str(checked_entries[0].get("date") or ""),
                is_folder=False,
                plan=self.plan,
                base_dir=self.base_dir,
                files=checked_entries,
            )

            def on_batch_renamed(result: str | RenameResult | None) -> None:
                if not result:
                    return

                from app.core.path_utils import (
                    _disambiguate_key,
                    _is_absolute_path,
                    prune_empty_plan_ancestors,
                )

                dest_override = getattr(result, "destination_override", None)
                if dest_override and not _is_absolute_path(str(dest_override)):
                    try:
                        dest_override = _normalize_validated_folder(str(dest_override))
                    except ValueError as err:
                        self.announce(
                            f"Invalid destination folder: {err}", priority="assertive"
                        )
                        return
                batch_items = getattr(result, "batch_items", None)

                if not batch_items:
                    pattern_str = str(result)
                    previews = modal.get_batch_previews(pattern_str)
                    batch_items = []
                    for idx, entry in enumerate(checked_entries):
                        _meta, fallback, key, folder, info = (
                            modal._extract_file_metadata(entry, modal.seq + idx)
                        )
                        target_fn = previews[idx] if idx < len(previews) else fallback
                        target_fld = dest_override if dest_override else folder
                        batch_items.append(
                            {
                                "key": key,
                                "folder": target_fld,
                                "new_name": target_fn,
                                "info": info or entry.get("info", {}),
                                "old_folder": entry.get("folder", ""),
                                "filepath": entry.get("filepath"),
                            }
                        )

                manual_folders = getattr(self, "_manual_empty_folders", set())
                renamed_count = 0
                for item in batch_items:
                    old_name = str(item.get("key") or item.get("old_name") or "")
                    new_filename = str(item.get("new_name") or "")
                    old_folder = str(item.get("old_folder") or item.get("folder") or "")
                    target_folder = str(
                        dest_override
                        if dest_override
                        else (item.get("folder") or old_folder)
                    )
                    if target_folder and not _is_absolute_path(target_folder):
                        try:
                            target_folder = _normalize_validated_folder(target_folder)
                        except ValueError:
                            continue
                    data_info = item.get("info")

                    if not old_name or not new_filename:
                        continue

                    old_container = _resolve_plan_folder_dict(self.plan, old_folder)
                    if old_container is None or old_name not in old_container:
                        found_folder, found_container, found_val = _find_file_in_plan(
                            self.plan,
                            old_name,
                            target_info=data_info
                            if isinstance(data_info, dict)
                            else None,
                        )
                        if found_container is not None:
                            old_container = found_container
                            if not item.get("folder") and not dest_override:
                                target_folder = found_folder
                            old_folder = found_folder
                            if not isinstance(data_info, dict) and isinstance(
                                found_val, dict
                            ):
                                data_info = found_val

                    if not isinstance(data_info, dict) and old_container is not None:
                        existing_val = old_container.get(old_name)
                        if isinstance(existing_val, dict):
                            data_info = existing_val

                    raw_item_fp = item.get("filepath")
                    db_base, doc_relpath, abs_fp = _resolve_source_identity(
                        self,
                        file_key=old_name,
                        filepath=raw_item_fp if isinstance(raw_item_fp, str) else None,
                        info=data_info if isinstance(data_info, dict) else None,
                    )

                    # Remove from old location in self.plan
                    if old_container is not None and old_name in old_container:
                        old_container.pop(old_name, None)
                        if old_folder and old_folder != target_folder:
                            prune_empty_plan_ancestors(
                                self.plan, old_folder, preserve_folders=manual_folders
                            )

                    target_container = _resolve_plan_folder_dict(
                        self.plan, target_folder, create=True
                    )
                    if target_container is None:
                        self.plan[target_folder] = {}
                        target_container = self.plan[target_folder]

                    # Collision check & numeric disambiguation
                    if (
                        new_filename in target_container
                        and target_container[new_filename] is not data_info
                    ):
                        new_filename = _disambiguate_key(
                            target_container, new_filename, is_file=True
                        )

                    if isinstance(data_info, dict):
                        if doc_relpath and not data_info.get("source_path"):
                            data_info["source_path"] = doc_relpath
                        if abs_fp and not data_info.get("filepath"):
                            data_info["filepath"] = abs_fp
                        target_container[new_filename] = data_info
                        data_info["key"] = new_filename
                        data_info["target_filename"] = new_filename
                        data_info["rename_source"] = "Manual"
                        data_info["folder"] = target_folder
                        data_info["is_locked"] = True
                        data_info["confirmed"] = True
                        _update_node_relative_source(
                            data_info, db_base, abs_fp, target_folder
                        )
                    else:
                        new_info: dict[str, Any] = {
                            "__type__": "file",
                            "key": new_filename,
                            "target_filename": new_filename,
                            "rename_source": "Manual",
                            "folder": target_folder,
                            "is_locked": True,
                            "confirmed": True,
                        }
                        if doc_relpath:
                            new_info["source_path"] = doc_relpath
                        if abs_fp:
                            new_info["filepath"] = abs_fp
                        _update_node_relative_source(
                            new_info, db_base, abs_fp, target_folder
                        )
                        target_container[new_filename] = new_info

                    if old_name != new_filename:
                        self.locked_files.pop(old_name, None)
                    self.locked_files[new_filename] = target_folder
                    if doc_relpath:
                        self.locked_files[doc_relpath] = target_folder
                        if self.app_session:
                            self.app_session.db.set_user_verified_target_path(
                                db_base,
                                doc_relpath,
                                target_folder,
                                target_name=new_filename,
                            )
                        _record_manual_edit(
                            self,
                            db_base,
                            doc_relpath,
                            abs_fp,
                            target_filename=new_filename,
                            rename_source="Manual",
                            reverted_target_name=False,
                            folder=target_folder,
                            is_locked=True,
                            confirmed=True,
                        )
                    renamed_count += 1

                self.rebuild_tree(run_validation=True)
                self.announce(f"Batch renamed {renamed_count} files [Locked]")

            self.push_screen(modal, on_batch_renamed)
            return

        # Single file rename workflow (either 1 selected file or focused file node)
        raw_data: dict[str, Any] | None = None
        if len(checked_entries) == 1:
            single_entry = checked_entries[0]
            existing_node_data = single_entry.get("node_data")
            if isinstance(existing_node_data, dict):
                raw_data = existing_node_data
            else:
                raw_data = {
                    "is_file": True,
                    "key": single_entry.get("key"),
                    "folder": single_entry.get("folder", ""),
                    "filepath": single_entry.get("filepath"),
                    "date": single_entry.get("date"),
                    "file_date": single_entry.get("file_date"),
                    "info": single_entry.get("info", {}),
                }
        elif (
            node and isinstance(node.data, dict) and not node.data.get("is_empty_state")
        ):
            raw_data = node.data

        if not raw_data:
            self.announce("Select a file or folder node to rename [F2].")
            return

        data: dict[str, Any] = raw_data
        is_file = data.get("is_file")
        old_name = str(data.get("key") or "")

        if is_file:
            from app.core.pattern_formatter import resolve_disk_file_date

            folder_cat = data.get("folder", "")
            raw_info = data.get("info")
            info_dict: dict[str, Any] = raw_info if isinstance(raw_info, dict) else {}
            filepath = _resolve_source_disk_path(
                getattr(self, "base_dir", None),
                str(old_name or ""),
                str(folder_cat or ""),
                info_dict,
                explicit_fp=data.get("filepath"),
            )
            _, doc_relpath_init, _ = _resolve_source_identity(
                self,
                file_key=str(old_name or ""),
                filepath=filepath,
                info=info_dict,
            )
            orig_basename = os.path.basename(
                str(doc_relpath_init or filepath or old_name or "").replace("\\", "/")
            )
            orig_stem, orig_ext = os.path.splitext(orig_basename)
            active_target_name = str(info_dict.get("target_filename") or old_name or "")
            active_stem, active_ext = os.path.splitext(active_target_name)
            ext = active_ext or orig_ext

            resolved_file_date = str(
                data.get("file_date")
                or data.get("date")
                or info_dict.get("file_date")
                or info_dict.get("date")
                or resolve_disk_file_date(filepath, base_dir=self.base_dir)
                or ""
            )
            modal = RenameModal(
                title=f"Rename File: {orig_basename or old_name}",
                current_name=active_stem,
                extension=ext,
                category=folder_cat,
                file_date=resolved_file_date,
                is_folder=False,
                plan=self.plan,
                base_dir=self.base_dir,
                source_path=filepath,
                original_name=orig_stem,
            )

            def on_renamed(new_formatted: str | Any | None) -> None:
                if not new_formatted:
                    return

                from app.core.path_utils import (
                    _disambiguate_key,
                    _is_absolute_path,
                    prune_empty_plan_ancestors,
                )

                is_reset = bool(getattr(new_formatted, "is_reset", False))
                dest_override = getattr(new_formatted, "destination_override", None)
                if isinstance(new_formatted, tuple):
                    new_formatted_str, dest_override = new_formatted
                else:
                    new_formatted_str = str(new_formatted)

                if dest_override and not _is_absolute_path(str(dest_override)):
                    try:
                        dest_override = _normalize_validated_folder(str(dest_override))
                    except ValueError as err:
                        self.announce(
                            f"Invalid destination folder: {err}", priority="assertive"
                        )
                        return

                if ext and not new_formatted_str.endswith(ext):
                    new_filename = f"{new_formatted_str}{ext}"
                else:
                    new_filename = new_formatted_str

                target_folder = str(dest_override if dest_override else folder_cat)
                if target_folder and not _is_absolute_path(target_folder):
                    try:
                        target_folder = _normalize_validated_folder(target_folder)
                    except ValueError as err:
                        self.announce(
                            f"Invalid destination folder: {err}", priority="assertive"
                        )
                        return

                is_revert = is_reset or (
                    not dest_override
                    and bool(orig_basename)
                    and new_filename == orig_basename
                )
                if is_revert:
                    existing_tf = info_dict.get("target_filename")
                    has_active_rename = (old_name != orig_basename) or (
                        bool(existing_tf) and str(existing_tf) != orig_basename
                    )
                    if not has_active_rename:
                        return

                    old_folder = str(folder_cat or "")
                    old_container = _resolve_plan_folder_dict(self.plan, old_folder)
                    if old_container is None or old_name not in old_container:
                        found_folder, found_container, _ = _find_file_in_plan(
                            self.plan,
                            old_name,
                            target_info=data.get("info")
                            if isinstance(data.get("info"), dict)
                            else None,
                        )
                        if found_container is not None:
                            old_container = found_container
                            old_folder = found_folder

                    file_info = data.get("info")
                    db_base, doc_relpath, abs_fp = _resolve_source_identity(
                        self,
                        file_key=old_name,
                        filepath=filepath,
                        info=file_info if isinstance(file_info, dict) else None,
                    )
                    restored_key = orig_basename
                    if old_container is not None:
                        if old_name in old_container and old_name != restored_key:
                            old_container.pop(old_name, None)
                        if (
                            restored_key in old_container
                            and old_container[restored_key] is not file_info
                        ):
                            restored_key = _disambiguate_key(
                                old_container, restored_key, is_file=True
                            )
                        if isinstance(file_info, dict):
                            old_container[restored_key] = file_info

                    if isinstance(file_info, dict):
                        if doc_relpath and not file_info.get("source_path"):
                            file_info["source_path"] = doc_relpath
                        if abs_fp and not file_info.get("filepath"):
                            file_info["filepath"] = abs_fp
                        file_info["key"] = restored_key
                        file_info.pop("target_filename", None)
                        file_info.pop("rename_source", None)
                        file_info.pop("confirmed", None)
                        file_info.pop("is_confirmed", None)
                        file_info.pop("user_confirmed", None)

                    if old_name and old_name != restored_key:
                        self.locked_files.pop(old_name, None)
                    if doc_relpath:
                        if self.app_session:
                            self.app_session.db.set_user_verified_target_name(
                                db_base,
                                doc_relpath,
                                None,
                            )
                        _record_manual_edit(
                            self,
                            db_base,
                            doc_relpath,
                            abs_fp,
                            target_filename=None,
                            rename_source=None,
                            confirmed=False,
                            reverted_target_name=True,
                        )
                    data["key"] = restored_key
                    self.rebuild_tree(run_validation=True)
                    self.announce(f"Restored original filename '{restored_key}'")
                    return

                if (
                    not dest_override
                    and new_filename == old_name
                    and bool(info_dict.get("confirmed"))
                ):
                    return

                manual_folders = getattr(self, "_manual_empty_folders", set())
                old_folder = str(folder_cat or "")

                # Remove from old location in self.plan
                old_container = _resolve_plan_folder_dict(self.plan, old_folder)
                if old_container is None or old_name not in old_container:
                    found_folder, found_container, _ = _find_file_in_plan(
                        self.plan,
                        old_name,
                        target_info=data.get("info")
                        if isinstance(data.get("info"), dict)
                        else None,
                    )
                    if found_container is not None:
                        old_container = found_container
                        old_folder = found_folder
                if old_container is not None and old_name in old_container:
                    old_container.pop(old_name, None)
                    if old_folder and old_folder != target_folder:
                        prune_empty_plan_ancestors(
                            self.plan, old_folder, preserve_folders=manual_folders
                        )

                target_container = _resolve_plan_folder_dict(
                    self.plan, target_folder, create=True
                )
                if target_container is None:
                    self.plan[target_folder] = {}
                    target_container = self.plan[target_folder]

                # Collision check & numeric disambiguation
                file_info = data.get("info")
                db_base, doc_relpath, abs_fp = _resolve_source_identity(
                    self,
                    file_key=old_name,
                    filepath=filepath,
                    info=file_info if isinstance(file_info, dict) else None,
                )
                if (
                    new_filename in target_container
                    and target_container[new_filename] is not file_info
                ):
                    new_filename = _disambiguate_key(
                        target_container, new_filename, is_file=True
                    )

                if isinstance(file_info, dict):
                    if doc_relpath and not file_info.get("source_path"):
                        file_info["source_path"] = doc_relpath
                    if abs_fp and not file_info.get("filepath"):
                        file_info["filepath"] = abs_fp
                    target_container[new_filename] = file_info
                    file_info["key"] = new_filename
                    file_info["target_filename"] = new_filename
                    file_info["rename_source"] = "Manual"
                    file_info["folder"] = target_folder
                    file_info["is_locked"] = True
                    file_info["confirmed"] = True
                    _update_node_relative_source(
                        file_info, db_base, abs_fp, target_folder
                    )
                else:
                    file_info = {
                        "__type__": "file",
                        "key": new_filename,
                        "target_filename": new_filename,
                        "rename_source": "Manual",
                        "folder": target_folder,
                        "is_locked": True,
                        "confirmed": True,
                    }
                    if doc_relpath:
                        file_info["source_path"] = doc_relpath
                    if abs_fp:
                        file_info["filepath"] = abs_fp
                    _update_node_relative_source(
                        file_info, db_base, abs_fp, target_folder
                    )
                    data["info"] = file_info
                    target_container[new_filename] = file_info
                if old_name and old_name != new_filename:
                    self.locked_files.pop(old_name, None)
                data["key"] = new_filename
                data["folder"] = target_folder
                data["is_locked"] = True
                self.locked_files[new_filename] = target_folder
                if doc_relpath:
                    self.locked_files[doc_relpath] = target_folder
                    if self.app_session:
                        self.app_session.db.set_user_verified_target_path(
                            db_base,
                            doc_relpath,
                            target_folder,
                            target_name=new_filename,
                        )
                    _record_manual_edit(
                        self,
                        db_base,
                        doc_relpath,
                        abs_fp,
                        target_filename=new_filename,
                        rename_source="Manual",
                        reverted_target_name=False,
                        folder=target_folder,
                        is_locked=True,
                        confirmed=True,
                    )
                self.rebuild_tree(run_validation=True)
                self.announce(f"Renamed target file to '{new_filename}' [Locked]")

            self.push_screen(modal, on_renamed)

    def action_new_folder(self: TUIHostProtocol) -> None:
        """Create a new folder category node [Ctrl+N]."""
        if self._is_text_control_focused(allow_tree_search=True):
            return

        def on_created(folder_name: str | None) -> None:
            if not folder_name:
                return
            try:
                clean_folder = _normalize_validated_folder(folder_name)
            except ValueError as err:
                self.announce(
                    f"Invalid folder name '{folder_name}': {err}",
                    priority="assertive",
                )
                return

            existing = _resolve_plan_folder_dict(self.plan, clean_folder, create=False)
            if existing is None:
                created = _resolve_plan_folder_dict(
                    self.plan, clean_folder, create=True
                )
                if created is None:
                    self.plan[clean_folder] = {}
                self._manual_empty_folders.add(clean_folder)
                _persist_manual_folders_to_cache(self)
                self.rebuild_tree()
                self.announce(f"Created new folder category: '{clean_folder}'")
            else:
                self._manual_empty_folders.add(clean_folder)
                _persist_manual_folders_to_cache(self)
                self.announce(f"Folder category '{clean_folder}' already exists.")

        self.push_screen(NewFolderModal(), on_created)

    def action_rate_positive(self: TUIHostProtocol) -> None:
        """Set positive ML rating feedback [+] for selected node."""
        if self._is_text_control_focused():
            return
        self._set_rating_for_selected("positive")

    def action_rate_negative(self: TUIHostProtocol) -> None:
        """Set negative ML rating feedback [-] for selected node."""
        if self._is_text_control_focused():
            return
        self._set_rating_for_selected("negative")

    def _set_rating_for_selected(self: TUIHostProtocol, rating: str) -> None:
        host: Any = self
        if not hasattr(host, "excluded_paths") or host.excluded_paths is None:
            host.excluded_paths = set()

        SelectionActionsMixin._commit_visual_range_selection(host)
        node = host._get_active_node()
        has_selection = bool(getattr(host, "selected_paths", None))

        target_files: list[dict[str, Any]] = []
        if has_selection:
            target_files = host._get_target_file_infos()
        elif (
            node and isinstance(node.data, dict) and not node.data.get("is_empty_state")
        ):
            if node.data.get("is_file"):
                info_obj = node.data.get("info")
                if isinstance(info_obj, dict):
                    target_files = [info_obj]
            else:
                query = host._get_current_search_query()
                target_files = collect_scoped_file_nodes(
                    host,
                    node.data.get("info", {}),
                    current_folder=str(node.data.get("folder") or ""),
                    query=query,
                )

        if not target_files:
            host.announce("Select a file or folder node to rate [+][-].")
            return

        from app.core.path_utils import safe_relpath

        def _resolve_rating_context(
            fi: dict[str, Any],
        ) -> tuple[str, str, str, str, Any]:
            found_folder, found_k = _find_key_for_info(host.plan, fi)
            fkey = str(
                found_k
                or fi.get("key")
                or (
                    node.data.get("key")
                    if (
                        not has_selection
                        and len(target_files) == 1
                        and node
                        and isinstance(node.data, dict)
                    )
                    else ""
                )
                or ""
            )
            ffolder = str(
                found_folder
                or fi.get("folder")
                or (
                    node.data.get("folder")
                    if (
                        not has_selection
                        and len(target_files) == 1
                        and node
                        and isinstance(node.data, dict)
                    )
                    else ""
                )
                or ""
            )
            fp = str(
                fi.get("filepath")
                or (
                    node.data.get("filepath")
                    if (
                        not has_selection
                        and len(target_files) == 1
                        and node
                        and isinstance(node.data, dict)
                    )
                    else ""
                )
                or ""
            )
            raw_src = fi.get("source_path") or fkey or fp
            if isinstance(raw_src, str) and "::" in raw_src:
                raw_src = raw_src.split("::", 1)[1]
            if (
                getattr(host, "base_dir", None)
                and isinstance(raw_src, str)
                and os.path.isabs(raw_src)
            ):
                rel = safe_relpath(raw_src, host.base_dir)
                doc_rel = (
                    rel.replace("\\", "/")
                    if not rel.startswith("..")
                    else str(fkey or fp)
                )
            else:
                doc_rel = str(raw_src).replace("\\", "/")
            curr = (
                (host._ratings_cache.get(fp) if fp else None)
                or (host._ratings_cache.get(doc_rel) if doc_rel else None)
                or fi.get("rating")
                or (
                    node.data.get("rating")
                    if (
                        not has_selection
                        and len(target_files) == 1
                        and node
                        and isinstance(node.data, dict)
                        and node.data.get("is_file")
                    )
                    else None
                )
            )
            return fkey, ffolder, fp, doc_rel if doc_rel else "", curr

        contexts = [(fi, *_resolve_rating_context(fi)) for fi in target_files]
        all_already_rated = all(ctx[5] == rating for ctx in contexts)
        rating_to_set = None if all_already_rated else rating

        last_key = ""
        for fi, fkey, current_folder, filepath, doc_relpath, current in contexts:
            last_key = fkey
            if rating_to_set:
                if filepath:
                    host._ratings_cache[filepath] = rating_to_set
                if doc_relpath:
                    host._ratings_cache[doc_relpath] = rating_to_set
            else:
                if filepath:
                    host._ratings_cache.pop(filepath, None)
                if doc_relpath:
                    host._ratings_cache.pop(doc_relpath, None)
            fi["rating"] = rating_to_set

            pid = resolve_file_selection_id(host, fi, fkey, current_folder)
            db_b, doc_rel_ident, abs_fp = _resolve_source_identity(
                host,
                file_key=fkey,
                filepath=filepath or None,
                info=fi,
            )
            if rating_to_set == "negative":
                if fkey:
                    host.locked_files.pop(fkey, None)
                if doc_relpath:
                    host.locked_files.pop(doc_relpath, None)
                if filepath:
                    host.locked_files.pop(filepath, None)
                fi["is_locked"] = False
                fi["is_checked"] = False
                fi["is_excluded"] = True
                if pid:
                    host.excluded_paths.add(pid)
                _record_manual_edit(
                    host,
                    db_b,
                    doc_rel_ident or doc_relpath,
                    abs_fp,
                    is_checked=False,
                    is_excluded=True,
                    is_locked=False,
                )
            elif current == "negative" and rating_to_set != "negative":
                fi["is_excluded"] = False
                fi["is_checked"] = True
                if pid:
                    host.excluded_paths.discard(pid)
                _record_manual_edit(
                    host,
                    db_b,
                    doc_rel_ident or doc_relpath,
                    abs_fp,
                    is_checked=True,
                    is_excluded=False,
                )

            if host.app_session and doc_relpath:
                host.app_session.db.set_document_rating(
                    host.base_dir, doc_relpath, rating_to_set
                )
                if rating_to_set == "negative" and current_folder:
                    host.app_session.db.set_user_verified_target_path(
                        host.base_dir, doc_relpath, f"!{current_folder}"
                    )
                elif current == "negative" and rating_to_set != "negative":
                    restored_target = (
                        current_folder
                        if rating_to_set == "positive" and current_folder
                        else None
                    )
                    host.app_session.db.set_user_verified_target_path(
                        host.base_dir, doc_relpath, restored_target
                    )

        if (
            node is not None
            and isinstance(node.data, dict)
            and node.data.get("is_file")
            and node.data.get("info") in target_files
        ):
            node.data["rating"] = rating_to_set
            if rating_to_set == "negative":
                node.data["is_locked"] = False
                node.data["is_checked"] = False
                node.data["is_excluded"] = True
            elif node.data.get("is_excluded"):
                node.data["is_excluded"] = False
                node.data["is_checked"] = True

        host.rebuild_tree()
        if len(target_files) == 1:
            msg = f"Set rating '{rating_to_set or 'cleared'}' for '{last_key}'"
        else:
            msg = f"Set rating '{rating_to_set or 'cleared'}' for {len(target_files)} file(s)."
        host.announce(msg)

action_exclude_selected()

Exclude selected items or focused file/folder from sorting plan [X].

Source code in app/ui/mixins/selection.py
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
def action_exclude_selected(self: TUIHostProtocol) -> None:
    """Exclude selected items or focused file/folder from sorting plan [X]."""
    if self._is_text_control_focused():
        return
    if not hasattr(self, "excluded_paths") or self.excluded_paths is None:
        self.excluded_paths = set()

    target_files = self._get_target_file_infos()
    if not target_files:
        self.announce("No file items available to exclude.")
        return

    for fi in target_files:
        fi["is_checked"] = False
        fi["is_excluded"] = True
        _, found_k = _find_key_for_info(self.plan, fi)
        pid = resolve_file_selection_id(
            self,
            fi,
            str(fi.get("key") or found_k or ""),
            str(fi.get("folder") or ""),
        )
        if pid:
            self.excluded_paths.add(pid)
        db_b, doc_rel, abs_fp = _resolve_source_identity(
            self, file_key=found_k, filepath=fi.get("filepath"), info=fi
        )
        _record_manual_edit(
            self,
            db_b,
            doc_rel,
            abs_fp,
            is_checked=False,
            is_excluded=True,
        )

    self.rebuild_tree()
    self.announce(f"Excluded {len(target_files)} file(s) from sorting plan.")

action_include_selected()

Include selected items or focused file/folder in sorting plan [I].

Source code in app/ui/mixins/selection.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
def action_include_selected(self: TUIHostProtocol) -> None:
    """Include selected items or focused file/folder in sorting plan [I]."""
    if self._is_text_control_focused():
        return
    if not hasattr(self, "excluded_paths") or self.excluded_paths is None:
        self.excluded_paths = set()

    target_files = SelectionActionsMixin._resolve_target_file_infos(
        self, include_excluded_on_root=True
    )
    if not target_files:
        self.announce("No file items available to include.")
        return

    for fi in target_files:
        fi["is_checked"] = True
        fi["is_excluded"] = False
        _, found_k = _find_key_for_info(self.plan, fi)
        pid = resolve_file_selection_id(
            self,
            fi,
            str(fi.get("key") or found_k or ""),
            str(fi.get("folder") or ""),
        )
        if pid:
            self.excluded_paths.discard(pid)
        db_b, doc_rel, abs_fp = _resolve_source_identity(
            self, file_key=found_k, filepath=fi.get("filepath"), info=fi
        )
        _record_manual_edit(
            self,
            db_b,
            doc_rel,
            abs_fp,
            is_checked=True,
            is_excluded=False,
        )

    self.rebuild_tree()
    self.announce(f"Included {len(target_files)} file(s) in sorting plan.")

action_invert_selection()

Invert transient edit selection across visible file items in #plan-tree.

Source code in app/ui/mixins/selection.py
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
def action_invert_selection(self: TUIHostProtocol) -> None:
    """Invert transient edit selection across visible file items in ``#plan-tree``."""
    if not hasattr(self, "selected_paths") or self.selected_paths is None:
        self.selected_paths = set()

    all_files = self._collect_file_nodes_from_dict(self.plan)
    if not all_files:
        self.announce("No file items available to invert selection.")
        return

    query = self._get_current_search_query()
    target_files = (
        self._collect_visible_file_nodes_from_dict(self.plan, query=query)
        if query
        else all_files
    )
    if not target_files:
        self.announce(
            f"No visible file items matching '{query}' to invert selection."
        )
        return

    now_selected = 0
    for f in target_files:
        _, found_k = _find_key_for_info(self.plan, f)
        pid = resolve_file_selection_id(
            self,
            f,
            str(f.get("key") or found_k or ""),
            str(f.get("folder") or ""),
        )
        if pid in self.selected_paths:
            self.selected_paths.discard(pid)
            f["is_selected"] = False
        else:
            self.selected_paths.add(pid)
            f["is_selected"] = True
            now_selected += 1

    self.rebuild_tree(run_validation=False)
    self.announce(
        f"Inverted selection: {now_selected} of {len(target_files)} visible file item(s) selected."
    )

action_new_folder()

Create a new folder category node [Ctrl+N].

Source code in app/ui/mixins/selection.py
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
def action_new_folder(self: TUIHostProtocol) -> None:
    """Create a new folder category node [Ctrl+N]."""
    if self._is_text_control_focused(allow_tree_search=True):
        return

    def on_created(folder_name: str | None) -> None:
        if not folder_name:
            return
        try:
            clean_folder = _normalize_validated_folder(folder_name)
        except ValueError as err:
            self.announce(
                f"Invalid folder name '{folder_name}': {err}",
                priority="assertive",
            )
            return

        existing = _resolve_plan_folder_dict(self.plan, clean_folder, create=False)
        if existing is None:
            created = _resolve_plan_folder_dict(
                self.plan, clean_folder, create=True
            )
            if created is None:
                self.plan[clean_folder] = {}
            self._manual_empty_folders.add(clean_folder)
            _persist_manual_folders_to_cache(self)
            self.rebuild_tree()
            self.announce(f"Created new folder category: '{clean_folder}'")
        else:
            self._manual_empty_folders.add(clean_folder)
            _persist_manual_folders_to_cache(self)
            self.announce(f"Folder category '{clean_folder}' already exists.")

    self.push_screen(NewFolderModal(), on_created)

action_rate_negative()

Set negative ML rating feedback [-] for selected node.

Source code in app/ui/mixins/selection.py
2384
2385
2386
2387
2388
def action_rate_negative(self: TUIHostProtocol) -> None:
    """Set negative ML rating feedback [-] for selected node."""
    if self._is_text_control_focused():
        return
    self._set_rating_for_selected("negative")

action_rate_positive()

Set positive ML rating feedback [+] for selected node.

Source code in app/ui/mixins/selection.py
2378
2379
2380
2381
2382
def action_rate_positive(self: TUIHostProtocol) -> None:
    """Set positive ML rating feedback [+] for selected node."""
    if self._is_text_control_focused():
        return
    self._set_rating_for_selected("positive")

action_reassign_selected()

Bulk reassign checked file items or active node to target category [R].

Source code in app/ui/mixins/selection.py
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
def action_reassign_selected(self: TUIHostProtocol) -> None:
    """Bulk reassign checked file items or active node to target category [R]."""
    if self._is_text_control_focused():
        return

    target_files = self._get_target_file_infos()
    if not target_files:
        self.announce("No file items available to reassign.")
        return

    from app.core.scanner import discover_existing_folders

    plan_folders = _collect_plan_folders(self.plan)
    disk_folders = discover_existing_folders(
        getattr(self, "base_dir", None),
        settings=getattr(self, "settings", None),
    )
    existing_folders: list[str] = []
    seen_folders: set[str] = set()
    for folder in plan_folders + disk_folders:
        if folder and folder.lower() not in seen_folders:
            seen_folders.add(folder.lower())
            existing_folders.append(folder)

    def on_reassigned(raw_target_folder: str | None) -> None:
        if not raw_target_folder:
            return

        from app.core.metadata import derive_learned_pattern_for_files
        from app.core.path_utils import (
            _disambiguate_key,
            _is_absolute_path,
            prune_empty_plan_ancestors,
        )

        has_explicit_rule_choice = hasattr(raw_target_folder, "learn_rule")
        explicit_learn_rule = bool(getattr(raw_target_folder, "learn_rule", False))
        explicit_learned_pattern = str(
            getattr(raw_target_folder, "learned_pattern", "") or ""
        ).strip()
        target_folder = str(raw_target_folder)

        host: Any = self
        can_learn_rule = False
        if not _is_absolute_path(target_folder):
            try:
                target_folder = _normalize_validated_folder(target_folder)
                can_learn_rule = True
            except ValueError as err:
                host.announce(
                    f"Invalid destination folder: {err}", priority="assertive"
                )
                return

        from app.config import resolve_scoped_settings

        settings_obj = getattr(host, "settings", None)
        scoped_learned_updates: dict[str, dict[str, str]] = {}
        manual_folders = getattr(host, "_manual_empty_folders", set())

        fallback_shared_pattern = ""
        if not has_explicit_rule_choice and can_learn_rule:
            cand_names = [
                str(
                    fi.get("source_path")
                    or fi.get("source")
                    or fi.get("filepath")
                    or fi.get("target_filename")
                    or fi.get("key")
                    or ""
                )
                for fi in target_files
                if isinstance(fi, dict)
            ]
            fallback_shared_pattern, _stops, is_gen_only = (
                derive_learned_pattern_for_files(cand_names)
            )
            if is_gen_only:
                fallback_shared_pattern = ""

        reassigned_count = 0
        for fi in target_files:
            found_folder, old_container, _ = _find_file_in_plan(
                host.plan,
                str(fi.get("target_filename") or fi.get("key") or ""),
                target_info=fi,
            )
            file_key = None
            if old_container is not None:
                for k, v in list(old_container.items()):
                    if v is fi:
                        file_key = k
                        break
            if not file_key:
                file_key = fi.get("target_filename") or fi.get("key")
            old_folder = found_folder or fi.get("folder", "")
            if old_container is None and old_folder:
                old_container = _resolve_plan_folder_dict(host.plan, old_folder)

            if file_key and old_container is not None:
                db_base, doc_relpath, abs_fp = _resolve_source_identity(
                    host,
                    file_key=str(file_key),
                    filepath=fi.get("filepath"),
                    info=fi,
                )
                if doc_relpath and not fi.get("source_path"):
                    fi["source_path"] = doc_relpath
                if abs_fp and not fi.get("filepath"):
                    fi["filepath"] = abs_fp

                old_container.pop(file_key, None)
                if old_folder and old_folder != target_folder:
                    prune_empty_plan_ancestors(
                        host.plan, old_folder, preserve_folders=manual_folders
                    )
                target_container = _resolve_plan_folder_dict(
                    host.plan, target_folder, create=True
                )
                if target_container is None:
                    host.plan[target_folder] = {}
                    target_container = host.plan[target_folder]

                # Non-clobbering mutation with automatic numeric disambiguation
                if (
                    file_key in target_container
                    and target_container[file_key] is not fi
                ):
                    dest_key = _disambiguate_key(
                        target_container, file_key, is_file=True
                    )
                    fi["target_filename"] = dest_key
                    fi["confirmed"] = True
                else:
                    dest_key = file_key

                target_container[dest_key] = fi
                fi["folder"] = target_folder
                fi["is_locked"] = True
                _update_node_relative_source(fi, db_base, abs_fp, target_folder)
                host.locked_files[dest_key] = target_folder

                if doc_relpath:
                    host.locked_files[doc_relpath] = target_folder
                    persisted_tf = (
                        str(fi["target_filename"])
                        if fi.get("target_filename")
                        else None
                    )
                    if host.app_session:
                        host.app_session.db.set_user_verified_target_path(
                            db_base,
                            doc_relpath,
                            target_folder,
                            target_name=persisted_tf,
                        )
                    edit_kwargs: dict[str, Any] = {
                        "folder": target_folder,
                        "is_locked": True,
                    }
                    if fi.get("target_filename"):
                        edit_kwargs["target_filename"] = fi["target_filename"]
                        edit_kwargs["confirmed"] = True
                    _record_manual_edit(
                        host, db_base, doc_relpath, abs_fp, **edit_kwargs
                    )

                if can_learn_rule and settings_obj is not None:
                    pattern_to_save = ""
                    if has_explicit_rule_choice:
                        if explicit_learn_rule and explicit_learned_pattern:
                            pattern_to_save = explicit_learned_pattern.lower()
                    else:
                        pattern_to_save = fallback_shared_pattern
                    if pattern_to_save:
                        scope_dir = str(
                            db_base or getattr(host, "base_dir", "") or ""
                        )
                        scoped_learned_updates.setdefault(scope_dir, {})[
                            pattern_to_save
                        ] = target_folder

                reassigned_count += 1

        saved_rule_patterns: list[str] = []
        if scoped_learned_updates and settings_obj is not None:
            for scope_dir, updates in scoped_learned_updates.items():
                scoped_view = resolve_scoped_settings(
                    settings_obj,
                    scope_dir if scope_dir else None,
                    fallback_to_global=True,
                )
                learned_rules = dict(
                    getattr(scoped_view, "LEARNED_RULES", {}) or {}
                )
                dis_learned = dict(
                    getattr(scoped_view, "DISABLED_LEARNED_RULES", {}) or {}
                )
                dis_changed = False
                for pat, dest in updates.items():
                    learned_rules[pat] = dest
                    if pat not in saved_rule_patterns:
                        saved_rule_patterns.append(pat)
                    if pat in dis_learned:
                        dis_learned.pop(pat, None)
                        dis_changed = True
                scoped_view.LEARNED_RULES = learned_rules
                if dis_changed:
                    scoped_view.DISABLED_LEARNED_RULES = dis_learned
            if hasattr(settings_obj, "flush"):
                settings_obj.flush()

        host.rebuild_tree()
        if saved_rule_patterns:
            host.announce(
                f"Reassigned {reassigned_count} file(s) to folder '{target_folder}' "
                f"and saved filename rule '{saved_rule_patterns[0]}' (priority 90)."
            )
        else:
            host.announce(
                f"Reassigned {reassigned_count} file(s) to folder '{target_folder}'."
            )

    self.push_screen(
        ReassignModal(
            existing_folders,
            count=len(target_files),
            plan=self.plan,
            base_dir=self.base_dir,
            target_files=target_files,
            settings=getattr(self, "settings", None),
        ),
        on_reassigned,
    )

action_rename_node()

Rename selected file(s) or focused file/folder category node [F2].

Source code in app/ui/mixins/selection.py
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
def action_rename_node(self: TUIHostProtocol) -> None:
    """Rename selected file(s) or focused file/folder category node [F2]."""
    if self._is_text_control_focused(allow_tree_search=True):
        return

    SelectionActionsMixin._commit_visual_range_selection(self)
    selected_entries = SelectionActionsMixin._get_selected_file_entries(self)
    selected_keys = [e["key"] for e in selected_entries if e.get("key")]
    node = self._get_active_node()

    # If no edit selection is active and a folder category node is focused, rename folder
    if (
        not selected_keys
        and node
        and node.data
        and not node.data.get("is_file")
        and not node.data.get("is_empty_state")
    ):
        data = node.data
        old_name = str(data.get("key") or "")
        old_folder_path = str(data.get("folder") or old_name)
        modal = RenameModal(
            title=f"Rename Folder: {old_folder_path}",
            current_name=old_name,
            category=old_folder_path,
            is_folder=True,
            plan=self.plan,
            base_dir=self.base_dir,
        )

        def on_folder_renamed(new_name: str | Any | None) -> None:
            if not new_name:
                return

            from app.core.path_utils import (
                _is_absolute_path,
                _merge_plan_dicts,
                prune_empty_plan_ancestors,
            )

            dest_override = getattr(new_name, "destination_override", None)
            if isinstance(new_name, tuple):
                new_name_str = str(new_name[0])
            else:
                new_name_str = str(new_name)
            raw_target = str(dest_override if dest_override else new_name_str)
            if not raw_target:
                return

            if dest_override or _is_absolute_path(raw_target):
                eff_folder_path = (
                    raw_target
                    if _is_absolute_path(raw_target)
                    else raw_target.replace("\\", "/").strip("/")
                )
            elif "/" in raw_target or "\\" in raw_target:
                eff_folder_path = raw_target.replace("\\", "/").strip("/")
            elif (
                "/" in old_folder_path
                and not _is_absolute_path(old_folder_path)
                and old_folder_path not in self.plan
            ):
                parent_prefix = old_folder_path.rsplit("/", 1)[0]
                eff_folder_path = f"{parent_prefix}/{raw_target}"
            else:
                eff_folder_path = raw_target

            if not _is_absolute_path(eff_folder_path):
                try:
                    eff_folder_path = _normalize_validated_folder(eff_folder_path)
                except ValueError as err:
                    self.announce(
                        f"Invalid folder path: {err}", priority="assertive"
                    )
                    return

            if not eff_folder_path or eff_folder_path == old_folder_path:
                return

            manual_folders = getattr(self, "_manual_empty_folders", set())
            old_content: dict[str, Any] | None = None
            popped_parent_prefix = ""
            if old_folder_path in self.plan and isinstance(
                self.plan[old_folder_path], dict
            ):
                old_content = self.plan.pop(old_folder_path)
            elif "/" in old_folder_path and not _is_absolute_path(old_folder_path):
                parent_prefix, leaf_name = old_folder_path.rsplit("/", 1)
                parent_dict = _resolve_plan_folder_dict(self.plan, parent_prefix)
                if parent_dict is not None and isinstance(
                    parent_dict.get(leaf_name), dict
                ):
                    old_content = parent_dict.pop(leaf_name)
                    popped_parent_prefix = parent_prefix
            elif old_name in self.plan and isinstance(self.plan[old_name], dict):
                old_content = self.plan.pop(old_name)

            if old_content is None:
                return

            if manual_folders:
                updated_manual: set[str] = set()
                changed_manual = False
                for mf in manual_folders:
                    if mf == old_folder_path:
                        updated_manual.add(eff_folder_path)
                        changed_manual = True
                    elif mf.startswith(f"{old_folder_path}/"):
                        suffix = mf[len(old_folder_path) + 1 :]
                        updated_manual.add(f"{eff_folder_path}/{suffix}")
                        changed_manual = True
                    else:
                        updated_manual.add(mf)
                if changed_manual:
                    self._manual_empty_folders = updated_manual
                    manual_folders = updated_manual
                    _persist_manual_folders_to_cache(self)

            if popped_parent_prefix:
                prune_empty_plan_ancestors(
                    self.plan,
                    popped_parent_prefix,
                    preserve_folders=manual_folders,
                )

            def _recursively_update_folder(
                content_dict: dict[str, Any], parent_folder: str
            ) -> None:
                for k, v in content_dict.items():
                    if isinstance(v, dict):
                        if v.get("__type__") == "file":
                            db_b, doc_rel, abs_fp = _resolve_source_identity(
                                self,
                                file_key=k,
                                filepath=v.get("filepath"),
                                info=v,
                            )
                            if doc_rel and not v.get("source_path"):
                                v["source_path"] = doc_rel
                            if abs_fp and not v.get("filepath"):
                                v["filepath"] = abs_fp
                            v["folder"] = parent_folder
                            v["is_locked"] = True
                            _update_node_relative_source(
                                v, db_b, abs_fp, parent_folder
                            )
                            self.locked_files[k] = parent_folder
                            if doc_rel:
                                self.locked_files[doc_rel] = parent_folder
                                persisted_tf = (
                                    str(v["target_filename"])
                                    if v.get("target_filename")
                                    else None
                                )
                                if self.app_session:
                                    self.app_session.db.set_user_verified_target_path(
                                        db_b,
                                        doc_rel,
                                        parent_folder,
                                        target_name=persisted_tf,
                                    )
                                edit_kwargs: dict[str, Any] = {
                                    "folder": parent_folder,
                                    "is_locked": True,
                                }
                                if persisted_tf:
                                    edit_kwargs["target_filename"] = persisted_tf
                                    edit_kwargs["confirmed"] = True
                                _record_manual_edit(
                                    self,
                                    db_b,
                                    doc_rel,
                                    abs_fp,
                                    **edit_kwargs,
                                )
                        else:
                            sub = f"{parent_folder}/{k}" if parent_folder else k
                            _recursively_update_folder(v, sub)

            existing_dest = _resolve_plan_folder_dict(
                self.plan, eff_folder_path, create=False
            )
            remapped_rules = _remap_learned_rules_for_folder_rename(
                getattr(self, "settings", None),
                old_folder_path,
                eff_folder_path,
                base_dir=getattr(self, "base_dir", None),
            )
            remap_suffix = (
                f" (updated {remapped_rules} learned rule(s))"
                if remapped_rules > 0
                else ""
            )
            if existing_dest is not None:
                _merge_plan_dicts(existing_dest, old_content)
                _recursively_update_folder(existing_dest, eff_folder_path)
                self.rebuild_tree(run_validation=True)
                self.announce(
                    f"Merged folder category '{old_folder_path}' into '{eff_folder_path}'{remap_suffix}"
                )
            else:
                dest_dict = _resolve_plan_folder_dict(
                    self.plan, eff_folder_path, create=True
                )
                if dest_dict is None:
                    self.plan[eff_folder_path] = old_content
                    dest_dict = self.plan[eff_folder_path]
                else:
                    dest_dict.update(old_content)
                _recursively_update_folder(dest_dict, eff_folder_path)
                self.rebuild_tree(run_validation=True)
                self.announce(
                    f"Renamed folder category '{old_folder_path}' -> '{eff_folder_path}'{remap_suffix}"
                )

        self.push_screen(modal, on_folder_renamed)
        return

    checked_entries = selected_entries
    checked_keys = selected_keys

    # Branch to batch rename when multiple files are selected for edit
    if len(checked_keys) > 1:
        first_folder = checked_entries[0].get("folder", "")
        default_batch_pattern = (
            str(
                getattr(getattr(self, "settings", None), "RENAME_PATTERN", "") or ""
            ).strip()
            or "{category}_{original}"
        )
        modal = RenameModal(
            title=f"Batch Rename ({len(checked_entries)} files)",
            current_name=default_batch_pattern,
            category=first_folder,
            file_date=str(checked_entries[0].get("date") or ""),
            is_folder=False,
            plan=self.plan,
            base_dir=self.base_dir,
            files=checked_entries,
        )

        def on_batch_renamed(result: str | RenameResult | None) -> None:
            if not result:
                return

            from app.core.path_utils import (
                _disambiguate_key,
                _is_absolute_path,
                prune_empty_plan_ancestors,
            )

            dest_override = getattr(result, "destination_override", None)
            if dest_override and not _is_absolute_path(str(dest_override)):
                try:
                    dest_override = _normalize_validated_folder(str(dest_override))
                except ValueError as err:
                    self.announce(
                        f"Invalid destination folder: {err}", priority="assertive"
                    )
                    return
            batch_items = getattr(result, "batch_items", None)

            if not batch_items:
                pattern_str = str(result)
                previews = modal.get_batch_previews(pattern_str)
                batch_items = []
                for idx, entry in enumerate(checked_entries):
                    _meta, fallback, key, folder, info = (
                        modal._extract_file_metadata(entry, modal.seq + idx)
                    )
                    target_fn = previews[idx] if idx < len(previews) else fallback
                    target_fld = dest_override if dest_override else folder
                    batch_items.append(
                        {
                            "key": key,
                            "folder": target_fld,
                            "new_name": target_fn,
                            "info": info or entry.get("info", {}),
                            "old_folder": entry.get("folder", ""),
                            "filepath": entry.get("filepath"),
                        }
                    )

            manual_folders = getattr(self, "_manual_empty_folders", set())
            renamed_count = 0
            for item in batch_items:
                old_name = str(item.get("key") or item.get("old_name") or "")
                new_filename = str(item.get("new_name") or "")
                old_folder = str(item.get("old_folder") or item.get("folder") or "")
                target_folder = str(
                    dest_override
                    if dest_override
                    else (item.get("folder") or old_folder)
                )
                if target_folder and not _is_absolute_path(target_folder):
                    try:
                        target_folder = _normalize_validated_folder(target_folder)
                    except ValueError:
                        continue
                data_info = item.get("info")

                if not old_name or not new_filename:
                    continue

                old_container = _resolve_plan_folder_dict(self.plan, old_folder)
                if old_container is None or old_name not in old_container:
                    found_folder, found_container, found_val = _find_file_in_plan(
                        self.plan,
                        old_name,
                        target_info=data_info
                        if isinstance(data_info, dict)
                        else None,
                    )
                    if found_container is not None:
                        old_container = found_container
                        if not item.get("folder") and not dest_override:
                            target_folder = found_folder
                        old_folder = found_folder
                        if not isinstance(data_info, dict) and isinstance(
                            found_val, dict
                        ):
                            data_info = found_val

                if not isinstance(data_info, dict) and old_container is not None:
                    existing_val = old_container.get(old_name)
                    if isinstance(existing_val, dict):
                        data_info = existing_val

                raw_item_fp = item.get("filepath")
                db_base, doc_relpath, abs_fp = _resolve_source_identity(
                    self,
                    file_key=old_name,
                    filepath=raw_item_fp if isinstance(raw_item_fp, str) else None,
                    info=data_info if isinstance(data_info, dict) else None,
                )

                # Remove from old location in self.plan
                if old_container is not None and old_name in old_container:
                    old_container.pop(old_name, None)
                    if old_folder and old_folder != target_folder:
                        prune_empty_plan_ancestors(
                            self.plan, old_folder, preserve_folders=manual_folders
                        )

                target_container = _resolve_plan_folder_dict(
                    self.plan, target_folder, create=True
                )
                if target_container is None:
                    self.plan[target_folder] = {}
                    target_container = self.plan[target_folder]

                # Collision check & numeric disambiguation
                if (
                    new_filename in target_container
                    and target_container[new_filename] is not data_info
                ):
                    new_filename = _disambiguate_key(
                        target_container, new_filename, is_file=True
                    )

                if isinstance(data_info, dict):
                    if doc_relpath and not data_info.get("source_path"):
                        data_info["source_path"] = doc_relpath
                    if abs_fp and not data_info.get("filepath"):
                        data_info["filepath"] = abs_fp
                    target_container[new_filename] = data_info
                    data_info["key"] = new_filename
                    data_info["target_filename"] = new_filename
                    data_info["rename_source"] = "Manual"
                    data_info["folder"] = target_folder
                    data_info["is_locked"] = True
                    data_info["confirmed"] = True
                    _update_node_relative_source(
                        data_info, db_base, abs_fp, target_folder
                    )
                else:
                    new_info: dict[str, Any] = {
                        "__type__": "file",
                        "key": new_filename,
                        "target_filename": new_filename,
                        "rename_source": "Manual",
                        "folder": target_folder,
                        "is_locked": True,
                        "confirmed": True,
                    }
                    if doc_relpath:
                        new_info["source_path"] = doc_relpath
                    if abs_fp:
                        new_info["filepath"] = abs_fp
                    _update_node_relative_source(
                        new_info, db_base, abs_fp, target_folder
                    )
                    target_container[new_filename] = new_info

                if old_name != new_filename:
                    self.locked_files.pop(old_name, None)
                self.locked_files[new_filename] = target_folder
                if doc_relpath:
                    self.locked_files[doc_relpath] = target_folder
                    if self.app_session:
                        self.app_session.db.set_user_verified_target_path(
                            db_base,
                            doc_relpath,
                            target_folder,
                            target_name=new_filename,
                        )
                    _record_manual_edit(
                        self,
                        db_base,
                        doc_relpath,
                        abs_fp,
                        target_filename=new_filename,
                        rename_source="Manual",
                        reverted_target_name=False,
                        folder=target_folder,
                        is_locked=True,
                        confirmed=True,
                    )
                renamed_count += 1

            self.rebuild_tree(run_validation=True)
            self.announce(f"Batch renamed {renamed_count} files [Locked]")

        self.push_screen(modal, on_batch_renamed)
        return

    # Single file rename workflow (either 1 selected file or focused file node)
    raw_data: dict[str, Any] | None = None
    if len(checked_entries) == 1:
        single_entry = checked_entries[0]
        existing_node_data = single_entry.get("node_data")
        if isinstance(existing_node_data, dict):
            raw_data = existing_node_data
        else:
            raw_data = {
                "is_file": True,
                "key": single_entry.get("key"),
                "folder": single_entry.get("folder", ""),
                "filepath": single_entry.get("filepath"),
                "date": single_entry.get("date"),
                "file_date": single_entry.get("file_date"),
                "info": single_entry.get("info", {}),
            }
    elif (
        node and isinstance(node.data, dict) and not node.data.get("is_empty_state")
    ):
        raw_data = node.data

    if not raw_data:
        self.announce("Select a file or folder node to rename [F2].")
        return

    data: dict[str, Any] = raw_data
    is_file = data.get("is_file")
    old_name = str(data.get("key") or "")

    if is_file:
        from app.core.pattern_formatter import resolve_disk_file_date

        folder_cat = data.get("folder", "")
        raw_info = data.get("info")
        info_dict: dict[str, Any] = raw_info if isinstance(raw_info, dict) else {}
        filepath = _resolve_source_disk_path(
            getattr(self, "base_dir", None),
            str(old_name or ""),
            str(folder_cat or ""),
            info_dict,
            explicit_fp=data.get("filepath"),
        )
        _, doc_relpath_init, _ = _resolve_source_identity(
            self,
            file_key=str(old_name or ""),
            filepath=filepath,
            info=info_dict,
        )
        orig_basename = os.path.basename(
            str(doc_relpath_init or filepath or old_name or "").replace("\\", "/")
        )
        orig_stem, orig_ext = os.path.splitext(orig_basename)
        active_target_name = str(info_dict.get("target_filename") or old_name or "")
        active_stem, active_ext = os.path.splitext(active_target_name)
        ext = active_ext or orig_ext

        resolved_file_date = str(
            data.get("file_date")
            or data.get("date")
            or info_dict.get("file_date")
            or info_dict.get("date")
            or resolve_disk_file_date(filepath, base_dir=self.base_dir)
            or ""
        )
        modal = RenameModal(
            title=f"Rename File: {orig_basename or old_name}",
            current_name=active_stem,
            extension=ext,
            category=folder_cat,
            file_date=resolved_file_date,
            is_folder=False,
            plan=self.plan,
            base_dir=self.base_dir,
            source_path=filepath,
            original_name=orig_stem,
        )

        def on_renamed(new_formatted: str | Any | None) -> None:
            if not new_formatted:
                return

            from app.core.path_utils import (
                _disambiguate_key,
                _is_absolute_path,
                prune_empty_plan_ancestors,
            )

            is_reset = bool(getattr(new_formatted, "is_reset", False))
            dest_override = getattr(new_formatted, "destination_override", None)
            if isinstance(new_formatted, tuple):
                new_formatted_str, dest_override = new_formatted
            else:
                new_formatted_str = str(new_formatted)

            if dest_override and not _is_absolute_path(str(dest_override)):
                try:
                    dest_override = _normalize_validated_folder(str(dest_override))
                except ValueError as err:
                    self.announce(
                        f"Invalid destination folder: {err}", priority="assertive"
                    )
                    return

            if ext and not new_formatted_str.endswith(ext):
                new_filename = f"{new_formatted_str}{ext}"
            else:
                new_filename = new_formatted_str

            target_folder = str(dest_override if dest_override else folder_cat)
            if target_folder and not _is_absolute_path(target_folder):
                try:
                    target_folder = _normalize_validated_folder(target_folder)
                except ValueError as err:
                    self.announce(
                        f"Invalid destination folder: {err}", priority="assertive"
                    )
                    return

            is_revert = is_reset or (
                not dest_override
                and bool(orig_basename)
                and new_filename == orig_basename
            )
            if is_revert:
                existing_tf = info_dict.get("target_filename")
                has_active_rename = (old_name != orig_basename) or (
                    bool(existing_tf) and str(existing_tf) != orig_basename
                )
                if not has_active_rename:
                    return

                old_folder = str(folder_cat or "")
                old_container = _resolve_plan_folder_dict(self.plan, old_folder)
                if old_container is None or old_name not in old_container:
                    found_folder, found_container, _ = _find_file_in_plan(
                        self.plan,
                        old_name,
                        target_info=data.get("info")
                        if isinstance(data.get("info"), dict)
                        else None,
                    )
                    if found_container is not None:
                        old_container = found_container
                        old_folder = found_folder

                file_info = data.get("info")
                db_base, doc_relpath, abs_fp = _resolve_source_identity(
                    self,
                    file_key=old_name,
                    filepath=filepath,
                    info=file_info if isinstance(file_info, dict) else None,
                )
                restored_key = orig_basename
                if old_container is not None:
                    if old_name in old_container and old_name != restored_key:
                        old_container.pop(old_name, None)
                    if (
                        restored_key in old_container
                        and old_container[restored_key] is not file_info
                    ):
                        restored_key = _disambiguate_key(
                            old_container, restored_key, is_file=True
                        )
                    if isinstance(file_info, dict):
                        old_container[restored_key] = file_info

                if isinstance(file_info, dict):
                    if doc_relpath and not file_info.get("source_path"):
                        file_info["source_path"] = doc_relpath
                    if abs_fp and not file_info.get("filepath"):
                        file_info["filepath"] = abs_fp
                    file_info["key"] = restored_key
                    file_info.pop("target_filename", None)
                    file_info.pop("rename_source", None)
                    file_info.pop("confirmed", None)
                    file_info.pop("is_confirmed", None)
                    file_info.pop("user_confirmed", None)

                if old_name and old_name != restored_key:
                    self.locked_files.pop(old_name, None)
                if doc_relpath:
                    if self.app_session:
                        self.app_session.db.set_user_verified_target_name(
                            db_base,
                            doc_relpath,
                            None,
                        )
                    _record_manual_edit(
                        self,
                        db_base,
                        doc_relpath,
                        abs_fp,
                        target_filename=None,
                        rename_source=None,
                        confirmed=False,
                        reverted_target_name=True,
                    )
                data["key"] = restored_key
                self.rebuild_tree(run_validation=True)
                self.announce(f"Restored original filename '{restored_key}'")
                return

            if (
                not dest_override
                and new_filename == old_name
                and bool(info_dict.get("confirmed"))
            ):
                return

            manual_folders = getattr(self, "_manual_empty_folders", set())
            old_folder = str(folder_cat or "")

            # Remove from old location in self.plan
            old_container = _resolve_plan_folder_dict(self.plan, old_folder)
            if old_container is None or old_name not in old_container:
                found_folder, found_container, _ = _find_file_in_plan(
                    self.plan,
                    old_name,
                    target_info=data.get("info")
                    if isinstance(data.get("info"), dict)
                    else None,
                )
                if found_container is not None:
                    old_container = found_container
                    old_folder = found_folder
            if old_container is not None and old_name in old_container:
                old_container.pop(old_name, None)
                if old_folder and old_folder != target_folder:
                    prune_empty_plan_ancestors(
                        self.plan, old_folder, preserve_folders=manual_folders
                    )

            target_container = _resolve_plan_folder_dict(
                self.plan, target_folder, create=True
            )
            if target_container is None:
                self.plan[target_folder] = {}
                target_container = self.plan[target_folder]

            # Collision check & numeric disambiguation
            file_info = data.get("info")
            db_base, doc_relpath, abs_fp = _resolve_source_identity(
                self,
                file_key=old_name,
                filepath=filepath,
                info=file_info if isinstance(file_info, dict) else None,
            )
            if (
                new_filename in target_container
                and target_container[new_filename] is not file_info
            ):
                new_filename = _disambiguate_key(
                    target_container, new_filename, is_file=True
                )

            if isinstance(file_info, dict):
                if doc_relpath and not file_info.get("source_path"):
                    file_info["source_path"] = doc_relpath
                if abs_fp and not file_info.get("filepath"):
                    file_info["filepath"] = abs_fp
                target_container[new_filename] = file_info
                file_info["key"] = new_filename
                file_info["target_filename"] = new_filename
                file_info["rename_source"] = "Manual"
                file_info["folder"] = target_folder
                file_info["is_locked"] = True
                file_info["confirmed"] = True
                _update_node_relative_source(
                    file_info, db_base, abs_fp, target_folder
                )
            else:
                file_info = {
                    "__type__": "file",
                    "key": new_filename,
                    "target_filename": new_filename,
                    "rename_source": "Manual",
                    "folder": target_folder,
                    "is_locked": True,
                    "confirmed": True,
                }
                if doc_relpath:
                    file_info["source_path"] = doc_relpath
                if abs_fp:
                    file_info["filepath"] = abs_fp
                _update_node_relative_source(
                    file_info, db_base, abs_fp, target_folder
                )
                data["info"] = file_info
                target_container[new_filename] = file_info
            if old_name and old_name != new_filename:
                self.locked_files.pop(old_name, None)
            data["key"] = new_filename
            data["folder"] = target_folder
            data["is_locked"] = True
            self.locked_files[new_filename] = target_folder
            if doc_relpath:
                self.locked_files[doc_relpath] = target_folder
                if self.app_session:
                    self.app_session.db.set_user_verified_target_path(
                        db_base,
                        doc_relpath,
                        target_folder,
                        target_name=new_filename,
                    )
                _record_manual_edit(
                    self,
                    db_base,
                    doc_relpath,
                    abs_fp,
                    target_filename=new_filename,
                    rename_source="Manual",
                    reverted_target_name=False,
                    folder=target_folder,
                    is_locked=True,
                    confirmed=True,
                )
            self.rebuild_tree(run_validation=True)
            self.announce(f"Renamed target file to '{new_filename}' [Locked]")

        self.push_screen(modal, on_renamed)

action_toggle_lock()

Toggle node lock state for selected files or focused file/folder [Ctrl+L].

Source code in app/ui/mixins/selection.py
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
def action_toggle_lock(self: TUIHostProtocol) -> None:
    """Toggle node lock state for selected files or focused file/folder [Ctrl+L]."""
    if self._is_text_control_focused(allow_tree_search=True):
        return

    SelectionActionsMixin._commit_visual_range_selection(self)
    node = self._get_active_node()
    has_selection = bool(getattr(self, "selected_paths", None))

    target_files: list[dict[str, Any]] = []
    if has_selection:
        target_files = self._get_target_file_infos()
    elif (
        node and isinstance(node.data, dict) and not node.data.get("is_empty_state")
    ):
        if node.data.get("is_file"):
            info_obj = node.data.get("info")
            if isinstance(info_obj, dict):
                target_files = [info_obj]
        else:
            query = self._get_current_search_query()
            target_files = collect_scoped_file_nodes(
                self,
                node.data.get("info", {}),
                current_folder=str(node.data.get("folder") or ""),
                query=query,
            )

    if not target_files:
        self.announce("Select a file or folder node to toggle lock [Ctrl+L].")
        return

    def _is_info_locked(fi: dict[str, Any]) -> bool:
        _, found_k = _find_key_for_info(self.plan, fi)
        fkey = str(fi.get("key") or found_k or "")
        fp = str(fi.get("filepath") or "")
        _, d_rel, _ = _resolve_source_identity(
            self, file_key=fkey, filepath=fp or None, info=fi
        )
        return (
            bool(fi.get("is_locked"))
            or (bool(fkey) and fkey in self.locked_files)
            or (bool(fp) and fp in self.locked_files)
            or (bool(d_rel) and d_rel in self.locked_files)
            or (
                not has_selection
                and len(target_files) == 1
                and node is not None
                and isinstance(node.data, dict)
                and node.data.get("is_file")
                and bool(node.data.get("is_locked"))
            )
        )

    all_locked = all(_is_info_locked(fi) for fi in target_files)
    should_lock = not all_locked

    last_key = ""
    last_folder = ""
    for fi in target_files:
        found_folder, found_k = _find_key_for_info(self.plan, fi)
        file_key = str(
            found_k
            or fi.get("key")
            or (
                node.data.get("key")
                if (
                    not has_selection
                    and len(target_files) == 1
                    and node
                    and isinstance(node.data, dict)
                )
                else ""
            )
            or ""
        )
        folder = str(
            found_folder
            or fi.get("folder")
            or (
                node.data.get("folder")
                if (
                    not has_selection
                    and len(target_files) == 1
                    and node
                    and isinstance(node.data, dict)
                )
                else ""
            )
            or ""
        )
        filepath = str(
            fi.get("filepath")
            or (
                node.data.get("filepath")
                if (
                    not has_selection
                    and len(target_files) == 1
                    and node
                    and isinstance(node.data, dict)
                )
                else ""
            )
            or ""
        )
        last_key = file_key
        last_folder = folder
        db_base, doc_relpath, abs_fp = _resolve_source_identity(
            self, file_key=file_key, filepath=filepath or None, info=fi
        )
        if not should_lock:
            self.locked_files.pop(file_key, None)
            if filepath:
                self.locked_files.pop(filepath, None)
            if doc_relpath:
                self.locked_files.pop(doc_relpath, None)
            fi["is_locked"] = False
            if self.app_session and doc_relpath:
                self.app_session.db.set_user_verified_target_path(
                    db_base, doc_relpath, None
                )
            _record_manual_edit(
                self,
                db_base,
                doc_relpath,
                abs_fp,
                folder=None,
                target_filename=None,
                is_locked=False,
            )
        else:
            if file_key:
                self.locked_files[file_key] = folder
            if doc_relpath:
                self.locked_files[doc_relpath] = folder
            fi["is_locked"] = True
            locked_tf = (
                str(fi["target_filename"]) if fi.get("target_filename") else None
            )
            if self.app_session and doc_relpath:
                self.app_session.db.set_user_verified_target_path(
                    db_base, doc_relpath, folder, target_name=locked_tf
                )
            edit_kwargs: dict[str, Any] = {"folder": folder, "is_locked": True}
            if locked_tf:
                edit_kwargs["target_filename"] = locked_tf
                edit_kwargs["confirmed"] = True
            _record_manual_edit(self, db_base, doc_relpath, abs_fp, **edit_kwargs)

    if (
        node is not None
        and isinstance(node.data, dict)
        and node.data.get("is_file")
        and node.data.get("info") in target_files
    ):
        node.data["is_locked"] = should_lock

    if len(target_files) == 1:
        msg = (
            f"Locked file '{last_key}' to folder '{last_folder}'"
            if should_lock
            else f"Unlocked file '{last_key}'"
        )
    else:
        action_word = "Locked" if should_lock else "Unlocked"
        msg = f"{action_word} {len(target_files)} file(s) in sorting plan."

    self.announce(msg)
    self.rebuild_tree()

action_toggle_select_all()

Toggle Select All / Deselect All transient edit selection in plan [A].

Source code in app/ui/mixins/selection.py
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
def action_toggle_select_all(self: TUIHostProtocol) -> None:
    """Toggle Select All / Deselect All transient edit selection in plan [A]."""
    if self._is_text_control_focused():
        return
    if not hasattr(self, "selected_paths") or self.selected_paths is None:
        self.selected_paths = set()

    all_files = self._collect_file_nodes_from_dict(self.plan)
    if not all_files:
        self.announce("No file items available to select/deselect.")
        return

    query = self._get_current_search_query()
    if query:
        target_files = self._collect_visible_file_nodes_from_dict(
            self.plan, query=query
        )
    else:
        target_files = all_files

    if not target_files:
        self.announce(
            f"No visible file items matching '{query}' to select/deselect."
        )
        return

    target_pids: list[tuple[dict[str, Any], str]] = []
    for f in target_files:
        _, found_k = _find_key_for_info(self.plan, f)
        pid = resolve_file_selection_id(
            self,
            f,
            str(f.get("key") or found_k or ""),
            str(f.get("folder") or ""),
        )
        target_pids.append((f, pid))

    all_selected = all(pid in self.selected_paths for _, pid in target_pids)
    new_state = not all_selected

    for f, pid in target_pids:
        f["is_selected"] = new_state
        if new_state:
            self.selected_paths.add(pid)
        else:
            self.selected_paths.discard(pid)

    self.rebuild_tree(run_validation=False)

    if query:
        hidden_count = len(all_files) - len(target_files)
        status_str = "Selected" if new_state else "Deselected"
        if hidden_count > 0:
            self.announce(
                f"{status_str} {len(target_files)} visible file item(s) ({hidden_count} hidden files unchanged)."
            )
        else:
            self.announce(f"{status_str} {len(target_files)} visible file item(s).")
    else:
        status_str = "Selected all" if new_state else "Deselected all"
        self.announce(f"{status_str} {len(all_files)} file item(s).")

action_toggle_selection()

Toggle transient edit selection [●]/[ ] for active node, folder, or visual range [Space].

Source code in app/ui/mixins/selection.py
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
def action_toggle_selection(self: TUIHostProtocol) -> None:
    """Toggle transient edit selection ``[●]``/``[ ]`` for active node, folder, or visual range [Space]."""
    if self._is_text_control_focused():
        return
    if not hasattr(self, "selected_paths") or self.selected_paths is None:
        self.selected_paths = set()

    nodes_to_toggle = []
    if self.visual_select_active and self.visual_selected_nodes:
        nodes_to_toggle = list(self.visual_selected_nodes)
        self.visual_select_active = False
        self.visual_selected_nodes = []
    else:
        active_node = self._get_active_node()
        if active_node:
            nodes_to_toggle = [active_node]

    if not nodes_to_toggle:
        self.announce("Select a tree node to toggle edit selection [Space].")
        return

    query = self._get_current_search_query()
    file_infos_to_toggle: list[dict[str, Any]] = []
    seen_ids: set[int] = set()
    for n in nodes_to_toggle:
        data = getattr(n, "data", None)
        if not data or not isinstance(data, dict) or data.get("is_empty_state"):
            continue
        if data.get("is_file"):
            fi = data["info"]
            if isinstance(fi, dict) and id(fi) not in seen_ids:
                seen_ids.add(id(fi))
                file_infos_to_toggle.append(fi)
        else:
            info_dict = data.get("info", {})
            for fi in collect_scoped_file_nodes(
                self,
                info_dict,
                current_folder=str(data.get("folder") or ""),
                query=query,
            ):
                if id(fi) not in seen_ids:
                    seen_ids.add(id(fi))
                    file_infos_to_toggle.append(fi)

    if not file_infos_to_toggle:
        self.announce("No file nodes found to toggle.")
        return

    toggle_pids: list[tuple[dict[str, Any], str]] = []
    for fi in file_infos_to_toggle:
        _, found_k = _find_key_for_info(self.plan, fi)
        pid = resolve_file_selection_id(
            self,
            fi,
            str(fi.get("key") or found_k or ""),
            str(fi.get("folder") or ""),
        )
        toggle_pids.append((fi, pid))

    all_selected = all(pid in self.selected_paths for _, pid in toggle_pids)
    new_selected = not all_selected

    for fi, pid in toggle_pids:
        fi["is_selected"] = new_selected
        if new_selected:
            self.selected_paths.add(pid)
        else:
            self.selected_paths.discard(pid)

    self.rebuild_tree(run_validation=False)
    status_str = "selected [●]" if new_selected else "unselected [ ]"
    self.announce(
        f"Toggled {len(file_infos_to_toggle)} document item(s) to {status_str}."
    )

action_visual_range_select()

Toggle visual range selection mode [V].

Source code in app/ui/mixins/selection.py
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
def action_visual_range_select(self: TUIHostProtocol) -> None:
    """Toggle visual range selection mode [V]."""
    if self._is_text_control_focused():
        return
    self.visual_select_active = not self.visual_select_active
    if self.visual_select_active:
        self.visual_selected_nodes = []
        node = self._get_active_node()
        if node:
            self.visual_selected_nodes.append(node)
        self.refresh_tree_selection_markers()
        self.announce(
            "Visual range selection mode enabled. Move cursor [j/k/Up/Down] to extend range."
        )
    else:
        self.visual_selected_nodes = []
        self.refresh_tree_selection_markers()
        self.announce("Visual range selection mode disabled.")

extend_shift_range_selection(anchor_node, target_node)

Extend transient edit selection across anchor_node and target_node [Shift+Up/Down].

Source code in app/ui/mixins/selection.py
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def extend_shift_range_selection(
    self: TUIHostProtocol,
    anchor_node: TreeNode[Any] | None,
    target_node: TreeNode[Any] | None,
) -> None:
    """Extend transient edit selection across ``anchor_node`` and ``target_node`` [Shift+Up/Down]."""
    if not hasattr(self, "selected_paths") or self.selected_paths is None:
        self.selected_paths = set()
    query = self._get_current_search_query()
    added_any = False
    for node in (anchor_node, target_node):
        if node is None:
            continue
        data = getattr(node, "data", None)
        if not isinstance(data, dict) or data.get("is_empty_state"):
            continue
        if data.get("is_file"):
            info = data.get("info")
            file_infos = [info] if isinstance(info, dict) else []
        else:
            file_infos = collect_scoped_file_nodes(
                self,
                data.get("info", {}),
                current_folder=str(data.get("folder") or ""),
                query=query,
            )
        for fi in file_infos:
            _, found_k = _find_key_for_info(self.plan, fi)
            pid = resolve_file_selection_id(
                self,
                fi,
                str(fi.get("key") or found_k or ""),
                str(fi.get("folder") or ""),
            )
            if pid:
                self.selected_paths.add(pid)
                fi["is_selected"] = True
                added_any = True
    if added_any:
        self.refresh_tree_selection_markers()
        self.announce(
            f"Extended selection to {len(self.selected_paths)} file item(s)."
        )

register_visual_selected_node(node)

Register node into visual range selection list when visual selection is active.

Source code in app/ui/mixins/selection.py
379
380
381
382
383
384
385
386
def register_visual_selected_node(
    self: TUIHostProtocol, node: TreeNode[Any]
) -> None:
    """Register node into visual range selection list when visual selection is active."""
    if not self.visual_select_active or not node:
        return
    if node not in self.visual_selected_nodes:
        self.visual_selected_nodes.append(node)

app.ui.mixins.tree_view

app.ui.mixins.tree_view

Plan tree rendering, search filtering and the inspector panel for the TUI.

PathLookupIndex

Bases: NamedTuple

Pre-indexed lookup sets for exact O(1) file path and basename matching.

Source code in app/ui/mixins/tree_view.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
class PathLookupIndex(NamedTuple):
    """Pre-indexed lookup sets for exact O(1) file path and basename matching."""

    paths: set[str]
    basenames: set[str]

    def __contains__(self, item: object) -> bool:
        """Check if a path, basename, or separator-normalized variant exists in the index."""
        if not isinstance(item, str) or not item:
            return False
        return (
            item in self.paths
            or item in self.basenames
            or item.replace("\\", "/") in self.paths
            or item.replace("/", "\\") in self.paths
        )

    @classmethod
    def _coerce(cls, index: tuple[set[str], set[str]]) -> "PathLookupIndex":
        """Return ``index`` as a ``PathLookupIndex``, wrapping plain 2-tuples."""
        if isinstance(index, cls):
            return index
        return cls(paths=index[0], basenames=index[1])

    def _matches_path(self, raw_path: str | None) -> bool:
        """Check whether normalized or absolute variants of ``raw_path`` exist in ``self.paths``."""
        if not raw_path or not self.paths:
            return False
        norm_p = os.path.normpath(raw_path)
        if norm_p in self.paths or norm_p.replace("\\", "/") in self.paths:
            return True
        abs_p = os.path.normpath(os.path.abspath(raw_path))
        return abs_p in self.paths or abs_p.replace("\\", "/") in self.paths

    def _matches_node(self, filepath: str | None, key: str | None) -> bool:
        """Check whether ``filepath`` matches ``self.paths`` or ``norm_key`` is in the index."""
        if self._matches_path(filepath):
            return True
        norm_key = os.path.normpath(key) if key else ""
        return norm_key in self

    def _matches_collision(
        self,
        file_info: Mapping[str, Any],
        target_path: str | None,
        filepath: str | None,
        key: str | None,
    ) -> bool:
        """Check collision flags, ``target_path``, ``filepath``, and ``key`` against the index."""
        return bool(
            file_info.get("collision")
            or file_info.get("has_collision")
            or file_info.get("is_collision")
            or self._matches_path(target_path)
            or self._matches_node(filepath, key)
        )

__contains__(item)

Check if a path, basename, or separator-normalized variant exists in the index.

Source code in app/ui/mixins/tree_view.py
192
193
194
195
196
197
198
199
200
201
def __contains__(self, item: object) -> bool:
    """Check if a path, basename, or separator-normalized variant exists in the index."""
    if not isinstance(item, str) or not item:
        return False
    return (
        item in self.paths
        or item in self.basenames
        or item.replace("\\", "/") in self.paths
        or item.replace("/", "\\") in self.paths
    )

TreeViewMixin

Render the plan tree, filter it by search query and fill the inspector.

Source code in app/ui/mixins/tree_view.py
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
class TreeViewMixin:
    """Render the plan tree, filter it by search query and fill the inspector."""

    _tree_expansion_memory: dict[str, bool] = {}
    _last_cursor_key: str | None = None

    def _build_path_lookup_index(
        self: TUIHostProtocol, paths: Any | None = None
    ) -> PathLookupIndex:
        """Build sets of normalized paths and filename basenames from input path collections.

        Pre-indexes path variants (raw, normalized, POSIX, Windows, absolute, and base_dir-joined)
        and filename basenames so subsequent node styling and building can perform exact O(1)
        set membership lookups without running synchronous generator scans over collections.
        """
        indexed_paths: set[str] = set()
        indexed_basenames: set[str] = set()

        if not paths:
            return PathLookupIndex(paths=indexed_paths, basenames=indexed_basenames)

        if isinstance(paths, (str, bytes, os.PathLike)):
            items = [paths]
        elif not hasattr(paths, "__iter__"):
            return PathLookupIndex(paths=indexed_paths, basenames=indexed_basenames)
        else:
            items = paths

        base_dir = getattr(self, "base_dir", None)

        for item in items:
            if item is None:
                continue
            p_str = str(item).strip()
            if not p_str:
                continue

            # Normalized path variants
            norm_p = os.path.normpath(p_str)
            posix_p = p_str.replace("\\", "/")
            norm_posix_p = os.path.normpath(posix_p)
            win_p = p_str.replace("/", "\\")
            norm_win_p = os.path.normpath(win_p)

            indexed_paths.add(p_str)
            indexed_paths.add(norm_p)
            indexed_paths.add(posix_p)
            indexed_paths.add(norm_posix_p)
            indexed_paths.add(win_p)
            indexed_paths.add(norm_win_p)

            try:
                abs_p = os.path.normpath(os.path.abspath(p_str))
                indexed_paths.add(abs_p)
                indexed_paths.add(abs_p.replace("\\", "/"))
                indexed_paths.add(abs_p.replace("/", "\\"))
            except Exception:
                pass

            if base_dir:
                try:
                    if not _is_absolute_path(p_str):
                        joined = os.path.normpath(os.path.join(base_dir, p_str))
                        indexed_paths.add(joined)
                        indexed_paths.add(joined.replace("\\", "/"))
                        indexed_paths.add(joined.replace("/", "\\"))
                        indexed_paths.add(os.path.normpath(os.path.abspath(joined)))
                except Exception:
                    pass

            # Basename extraction
            clean = p_str.rstrip("/\\")
            if clean:
                clean_posix = clean.replace("\\", "/")
                basename = clean_posix.rsplit("/", 1)[-1]
                if basename:
                    indexed_basenames.add(basename)
                    indexed_basenames.add(os.path.normpath(basename))

        return PathLookupIndex(paths=indexed_paths, basenames=indexed_basenames)

    def _resolve_node_target_path(
        self: TUIHostProtocol,
        file_info: Mapping[str, Any],
        folder: str,
        file_key: str,
    ) -> str | None:
        """Resolve destination path for a file node while preserving Windows drive separators."""
        override_dir = file_info.get("destination_override")
        eff_folder = str(override_dir) if override_dir else folder
        target_filename = str(file_info.get("target_filename") or file_key)
        if eff_folder and _is_absolute_path(eff_folder):
            if re.match(r"^[a-zA-Z]:[/\\]", eff_folder):
                sep = "\\" if "\\" in eff_folder else "/"
                return f"{eff_folder.rstrip('/\\')}{sep}{target_filename}"
            return os.path.normpath(os.path.join(eff_folder, target_filename))
        base_dir = getattr(self, "base_dir", None)
        if base_dir:
            return os.path.normpath(os.path.join(base_dir, eff_folder, target_filename))
        if eff_folder:
            return os.path.normpath(os.path.join(eff_folder, target_filename))
        return None

    def _resolve_file_source_path(
        self: TUIHostProtocol,
        file_info: Mapping[str, Any],
        file_key: str,
        current_folder: str = "",
    ) -> str:
        """Resolve real source path for a plan file node without fabricating destination folders."""
        raw_fp = file_info.get("filepath")
        if raw_fp is not None and str(raw_fp).strip():
            return str(raw_fp)

        raw_root = file_info.get("source_root")
        s_root = str(raw_root).strip() if raw_root is not None else ""

        raw_rel = file_info.get("relative_source")
        rel_src = str(raw_rel).strip() if raw_rel is not None else ""
        if "::" in rel_src:
            parsed_root, rel_src = rel_src.split("::", 1)
            if not s_root:
                s_root = parsed_root

        raw_sp = file_info.get("source_path")
        sp_str = str(raw_sp).strip() if raw_sp is not None else ""
        if "::" in sp_str:
            parsed_root, sp_str = sp_str.split("::", 1)
            if not s_root:
                s_root = parsed_root

        clean_key = str(file_key) if file_key else ""
        if "::" in clean_key:
            parsed_root, clean_key = clean_key.split("::", 1)
            if not s_root:
                s_root = parsed_root

        base_dir = str(getattr(self, "base_dir", "") or "")
        eff_base = s_root or base_dir
        folder_posix = (
            current_folder.replace("\\", "/")
            if current_folder and current_folder != "(Root)"
            else ""
        )

        if rel_src:
            rel_posix = rel_src.replace("\\", "/")
            if _is_absolute_path(rel_src):
                return posixpath.normpath(rel_posix)

            has_parent_seg = rel_posix == ".." or rel_posix.startswith("../")
            if eff_base:
                eff_posix = eff_base.replace("\\", "/")
                root_cand = posixpath.normpath(posixpath.join(eff_posix, rel_posix))
                if folder_posix:
                    folder_cand = posixpath.normpath(
                        posixpath.join(eff_posix, folder_posix, rel_posix)
                    )
                    if os.path.lexists(root_cand) and os.path.normcase(
                        os.path.abspath(root_cand)
                    ) != os.path.normcase(os.path.abspath(folder_cand)):
                        return root_cand
                    if os.path.lexists(folder_cand):
                        return folder_cand
                    if os.path.lexists(root_cand):
                        return root_cand
                    if sp_str:
                        sp_posix = sp_str.replace("\\", "/")
                        sp_cand = posixpath.normpath(
                            sp_posix
                            if _is_absolute_path(sp_str)
                            else posixpath.join(eff_posix, sp_posix)
                        )
                        if os.path.lexists(sp_cand) or not has_parent_seg:
                            return sp_cand
                    return folder_cand if has_parent_seg else root_cand

                if os.path.lexists(root_cand):
                    return root_cand
                if has_parent_seg:
                    if sp_str:
                        sp_posix = sp_str.replace("\\", "/")
                        return posixpath.normpath(
                            sp_posix
                            if _is_absolute_path(sp_str)
                            else posixpath.join(eff_posix, sp_posix)
                        )
                    if clean_key:
                        key_cand = posixpath.normpath(
                            posixpath.join(eff_posix, clean_key.replace("\\", "/"))
                        )
                        if os.path.lexists(key_cand):
                            return key_cand
                return root_cand

            if has_parent_seg:
                if folder_posix:
                    rel_cand = posixpath.normpath(
                        posixpath.join(folder_posix, rel_posix)
                    )
                    if rel_cand not in ("", ".") and not (
                        rel_cand == ".." or rel_cand.startswith("../")
                    ):
                        return rel_cand
            else:
                return posixpath.normpath(rel_posix)

        if sp_str:
            sp_posix = sp_str.replace("\\", "/")
            if _is_absolute_path(sp_str):
                return posixpath.normpath(sp_posix)
            if eff_base:
                return posixpath.normpath(
                    posixpath.join(eff_base.replace("\\", "/"), sp_posix)
                )
            return posixpath.normpath(sp_posix)

        if not clean_key:
            return ""
        key_posix = clean_key.replace("\\", "/")
        if _is_absolute_path(clean_key):
            return posixpath.normpath(key_posix)
        if eff_base:
            return (Path(eff_base.replace("\\", "/")) / key_posix).as_posix()
        return posixpath.normpath(key_posix)

    def _enrich_file_info_in_place(
        self: TUIHostProtocol,
        file_info: dict[str, Any],
        file_key: str,
        current_folder: str = "",
    ) -> dict[str, Any]:
        """Populate missing ``key``, ``folder``, and ``filepath`` metadata on ``file_info`` in place."""
        if not file_info.get("key") and file_key:
            file_info["key"] = file_key
        eff_folder = str(file_info.get("folder") or current_folder)
        if "folder" not in file_info or (
            not file_info.get("folder") and current_folder
        ):
            file_info["folder"] = eff_folder
        if not file_info.get("filepath"):
            eff_key = str(file_info.get("key") or file_key)
            file_info["filepath"] = TreeViewMixin._resolve_file_source_path(
                self, file_info, eff_key, eff_folder
            )
        return file_info

    def _get_plan_invalid_locks(self: TUIHostProtocol) -> dict[str, Any]:
        """Extract the ``invalid_locks`` mapping from ``SortingPlan`` or ``dict`` plans."""
        plan = getattr(self, "plan", None)
        invalid_locks = getattr(plan, "invalid_locks", None) or {}
        if not invalid_locks and isinstance(plan, dict):
            invalid_locks = plan.get("invalid_locks", {}) or {}
        return invalid_locks if isinstance(invalid_locks, dict) else {}

    @staticmethod
    def _invalid_lock_candidates(
        filepath: str | None, key: str | None
    ) -> tuple[str, ...]:
        """Build up to 4 normalized lookup keys for ``invalid_locks`` checks."""
        candidates: list[str] = []
        if filepath:
            candidates.append(filepath)
        if key:
            candidates.append(key)
        if filepath:
            candidates.append(filepath.replace("\\", "/"))
            candidates.append(os.path.normpath(filepath))
        return tuple(candidates)

    def _has_invalid_lock(
        self: TUIHostProtocol,
        filepath: str | None,
        key: str | None,
        invalid_locks: Mapping[str, Any] | None = None,
    ) -> bool:
        """Check whether any of the 4 path variants exists in ``invalid_locks``."""
        locks = (
            TreeViewMixin._get_plan_invalid_locks(self)
            if invalid_locks is None
            else invalid_locks
        )
        if not locks:
            return False
        return any(
            candidate in locks
            for candidate in TreeViewMixin._invalid_lock_candidates(filepath, key)
        )

    def _get_invalid_lock_error(
        self: TUIHostProtocol,
        filepath: str | None,
        key: str | None,
        invalid_locks: Mapping[str, Any] | None = None,
    ) -> str | None:
        """Return the first truthy ``invalid_locks`` error across 4 path variants."""
        locks = (
            TreeViewMixin._get_plan_invalid_locks(self)
            if invalid_locks is None
            else invalid_locks
        )
        if not locks:
            return None
        for candidate in TreeViewMixin._invalid_lock_candidates(filepath, key):
            err = locks.get(candidate)
            if err:
                return str(err)
        return None

    def _capture_tree_state(
        self: TUIHostProtocol, tree: Tree[Any], search_query: str = ""
    ) -> None:
        """Record node expansion status and cursor key prior to tree rebuild."""
        if (
            not hasattr(self, "_tree_expansion_memory")
            or self._tree_expansion_memory is None
        ):
            self._tree_expansion_memory = {}

        prev_query = getattr(self, "_last_rendered_search_query", "")
        last_snap: dict[str, bool] = (
            getattr(self, "_last_rendered_expansion_snapshot", None) or {}
        )

        def _walk(node: TreeNode):
            data = getattr(node, "data", {}) or {}
            if isinstance(data, dict):
                key = data.get("filepath") or data.get("folder") or data.get("key")
                if (
                    key
                    and not data.get("is_file")
                    and not search_query
                    and not prev_query
                ):
                    if (
                        key not in self._tree_expansion_memory
                        or node.is_expanded != last_snap.get(key)
                    ):
                        self._tree_expansion_memory[key] = node.is_expanded
            for child in node.children:
                _walk(child)

        _walk(tree.root)

        node_for_cursor = tree.cursor_node or getattr(self, "active_tree_node", None)
        if node_for_cursor and getattr(node_for_cursor, "data", None):
            cdata = node_for_cursor.data
            if isinstance(cdata, dict):
                key = cdata.get("filepath") or cdata.get("folder") or cdata.get("key")
                if key:
                    self._last_cursor_key = key

    def _restore_tree_state(
        self: TUIHostProtocol, tree: Tree[Any], search_query: str = ""
    ) -> None:
        """Apply saved expansion states and restore cursor position after render."""
        target_cursor_node = None
        last_key = getattr(self, "_last_cursor_key", None)
        expansion_memory = getattr(self, "_tree_expansion_memory", {}) or {}

        def _walk(node: TreeNode):
            nonlocal target_cursor_node
            data = getattr(node, "data", {}) or {}
            if isinstance(data, dict):
                key = data.get("filepath") or data.get("folder") or data.get("key")

                if key and key == last_key:
                    target_cursor_node = node

                if not search_query:
                    folder_key = data.get("folder") or key
                    raw_name = data.get("key")
                    if folder_key in expansion_memory:
                        exp_state = expansion_memory[folder_key]
                    elif raw_name in expansion_memory:
                        exp_state = expansion_memory[str(raw_name)]
                    else:
                        exp_state = None
                    if exp_state is not None:
                        if exp_state:
                            node.expand()
                        else:
                            node.collapse()
            for child in node.children:
                _walk(child)

        _walk(tree.root)
        if target_cursor_node:
            if search_query:
                curr = target_cursor_node.parent
                while curr:
                    curr.expand()
                    curr = curr.parent
                tree.select_node(target_cursor_node)
                self.active_tree_node = target_cursor_node
            else:
                collapsed_ancestor: TreeNode[Any] | None = None
                curr = target_cursor_node.parent
                while curr and curr is not tree.root:
                    if not curr.is_expanded:
                        collapsed_ancestor = curr
                    curr = curr.parent
                chosen = collapsed_ancestor or target_cursor_node
                chosen_data = getattr(chosen, "data", None)
                if isinstance(chosen_data, dict) and not chosen_data.get("is_file"):
                    tree.move_cursor(chosen)
                else:
                    tree.select_node(chosen)
                self.active_tree_node = chosen
        elif search_query:
            self.active_tree_node = None

    def _apply_tree_node_styles(self: TUIHostProtocol) -> None:
        """Apply red/yellow styling to existing tree nodes and refresh collision labels."""
        try:
            tree = self.query_one("#plan-tree", Tree)

            crit_index = self._build_path_lookup_index(
                getattr(self, "critical_error_paths", set())
            )
            warn_index = self._build_path_lookup_index(
                getattr(self, "warning_paths", set())
            )
            collision_index = self._build_path_lookup_index(
                getattr(self, "collision_paths", set())
            )

            def _stylize_node(node: TreeNode) -> None:
                data = getattr(node, "data", None)
                if not data or not isinstance(data, dict):
                    for child in node.children:
                        _stylize_node(child)
                    return

                filepath = data.get("filepath", "")
                key = data.get("key", "")

                is_crit = crit_index._matches_node(filepath, key)
                is_warn = not is_crit and warn_index._matches_node(filepath, key)

                plain_txt = (
                    node.label.plain
                    if isinstance(node.label, Text)
                    else str(node.label)
                )
                plain_txt = re.sub(r"\[(ERR|WARN)\]\s*", "", plain_txt)

                if data.get("is_file"):
                    raw_info = data.get("info")
                    file_info = raw_info if isinstance(raw_info, Mapping) else {}
                    raw_tp = data.get("target_path")
                    target_path = (
                        raw_tp
                        if isinstance(raw_tp, str) and raw_tp
                        else TreeViewMixin._resolve_node_target_path(
                            self,
                            file_info,
                            str(data.get("folder") or ""),
                            str(key),
                        )
                    )
                    is_node_collision = collision_index._matches_collision(
                        file_info, target_path, filepath, key
                    )

                    pol = str(
                        getattr(self.settings, "CONFLICT_POLICY", "rename")
                    ).lower()
                    data["is_collision"] = is_node_collision
                    data["conflict_policy"] = pol
                    if target_path:
                        data["target_path"] = target_path

                    clean_txt = re.sub(r"\[COLLISION:\s*[^\]]+\]\s*", "", plain_txt)
                    if is_node_collision:
                        target_filename = file_info.get("target_filename") or key
                        if target_filename and target_filename != key:
                            suffix = f"{key} -> {target_filename}"
                        else:
                            suffix = f"{key}"
                        r_badge = data.get("routing_badge", "")
                        suffix_with_badge = f"{suffix} {r_badge}" if r_badge else suffix
                        if r_badge and clean_txt.endswith(suffix_with_badge):
                            prefix = clean_txt[: -len(suffix_with_badge)]
                            plain_txt = f"{prefix}[COLLISION: {pol.upper()}] {suffix_with_badge}"
                        elif clean_txt.endswith(suffix):
                            prefix = clean_txt[: -len(suffix)]
                            plain_txt = f"{prefix}[COLLISION: {pol.upper()}] {suffix}"
                        else:
                            plain_txt = f"{clean_txt} [COLLISION: {pol.upper()}]"
                    else:
                        plain_txt = clean_txt

                if is_crit:
                    if "📄 " in plain_txt:
                        plain_txt = plain_txt.replace("📄 ", "📄 [ERR] ", 1)
                    elif "📁 " in plain_txt:
                        plain_txt = plain_txt.replace("📁 ", "📁 [ERR] ", 1)
                    else:
                        plain_txt = f"[ERR] {plain_txt}"
                elif is_warn:
                    if "📄 " in plain_txt:
                        plain_txt = plain_txt.replace("📄 ", "📄 [WARN] ", 1)
                    elif "📁 " in plain_txt:
                        plain_txt = plain_txt.replace("📁 ", "📁 [WARN] ", 1)
                    else:
                        plain_txt = f"[WARN] {plain_txt}"

                new_txt = Text(plain_txt)
                if is_crit:
                    new_txt.stylize("bold red")
                elif is_warn:
                    new_txt.stylize("bold yellow")
                node.label = new_txt

                for child in node.children:
                    _stylize_node(child)

            _stylize_node(tree.root)
            active_node = getattr(self, "active_tree_node", None)
            if tree.cursor_node and tree.cursor_node.data:
                self._update_inspector(tree.cursor_node, announce=False)
            elif active_node is not None and getattr(active_node, "data", None):
                self._update_inspector(active_node, announce=False)
        except Exception as e:
            logger.debug(f"Error applying tree node styles: {e}")

    def _has_file_nodes(self: TUIHostProtocol, plan_dict: dict[str, Any]) -> bool:
        """Check if plan structure contains any document file nodes."""
        if not plan_dict or not isinstance(plan_dict, dict):
            return False
        for k, v in plan_dict.items():
            if isinstance(v, dict):
                if v.get("__type__") == "file":
                    return True
                if self._has_file_nodes(v):
                    return True
            elif (
                isinstance(v, list)
                and len(v) > 0
                or isinstance(v, str)
                and k != "action"
            ):
                return True
        return False

    def _has_folder_nodes(self: TUIHostProtocol, plan_dict: dict[str, Any]) -> bool:
        """Check if plan structure contains any folder category dictionaries (including empty ones)."""
        if not plan_dict or not isinstance(plan_dict, dict):
            return False
        for v in plan_dict.values():
            if isinstance(v, dict) and v.get("__type__") not in ("file", "directory"):
                return True
        return False

    def _get_current_search_query(self: TUIHostProtocol) -> str:
        """Return lowercased search query string if search input exists and contains text."""
        try:
            search_input = self.query_one("#tree-search-input", Input)
            return search_input.value.strip().lower()
        except Exception:
            return ""

    def _build_file_search_context(
        self: TUIHostProtocol,
        file_key: str,
        file_info: Mapping[str, Any],
        folder: str,
        *,
        crit_lookup: PathLookupIndex,
        warn_lookup: PathLookupIndex,
        col_lookup: PathLookupIndex,
        invalid_locks: Mapping[str, Any],
        selected_set: set[str],
        excluded_set: set[str],
    ) -> dict[str, Any]:
        """Build lowercased status, routing, extension, and badge tokens for search filtering."""
        filepath = TreeViewMixin._resolve_file_source_path(
            self, file_info, file_key, folder
        )
        target_filename = str(file_info.get("target_filename") or file_key)
        raw_sp = file_info.get("source_path")
        src_rel_lookup = (
            str(raw_sp).split("::", 1)[-1].replace("\\", "/") if raw_sp else ""
        )
        is_locked = (
            file_key in self.locked_files
            or filepath in self.locked_files
            or (bool(src_rel_lookup) and src_rel_lookup in self.locked_files)
            or bool(file_info.get("is_locked"))
        )
        is_invalid_lock = TreeViewMixin._has_invalid_lock(
            self, filepath, file_key, invalid_locks
        )
        rating = (
            self._ratings_cache.get(filepath)
            or (self._ratings_cache.get(src_rel_lookup) if src_rel_lookup else None)
            or file_info.get("rating")
        )
        path_id = resolve_file_selection_id(self, file_info, file_key, folder)
        is_excluded = (
            bool(file_info.get("is_excluded", False))
            or file_info.get("is_checked") is False
            or (path_id in excluded_set and "is_excluded" not in file_info)
        )
        is_selected = path_id in selected_set or bool(
            file_info.get("is_selected", False)
        )
        is_crit_node = crit_lookup._matches_node(filepath, file_key)
        is_warn_node = not is_crit_node and warn_lookup._matches_node(
            filepath, file_key
        )
        target_path = TreeViewMixin._resolve_node_target_path(
            self, file_info, folder, file_key
        )
        is_collision = col_lookup._matches_collision(
            file_info, target_path, filepath, file_key
        )
        pol = str(getattr(self.settings, "CONFLICT_POLICY", "rename")).lower()
        routing_badge, route_token = compute_routing_badge(file_info)
        raw_routed_by = str(file_info.get("routed_by") or "").strip().lower()

        status_tokens: set[str] = set()
        badge_parts: list[str] = [routing_badge.lower()]
        if is_selected:
            status_tokens.add("selected")
            badge_parts.append("[●] selected")
        if is_excluded:
            status_tokens.add("excluded")
            badge_parts.append("[excluded]")
        else:
            status_tokens.add("included")
            badge_parts.append("[✓] included")
        if is_crit_node:
            status_tokens.update({"err", "error", "critical"})
            badge_parts.append("[err] error critical")
        elif is_warn_node:
            status_tokens.update({"warn", "warning"})
            badge_parts.append("[warn] warning")
        if is_invalid_lock:
            status_tokens.update({"lock_warning", "locked", "warn", "warning"})
            badge_parts.append("[lock warning] locked")
        elif is_locked:
            status_tokens.add("locked")
            badge_parts.append("[locked]")
        if is_collision:
            status_tokens.update({"collision", f"collision_{pol}"})
            badge_parts.append(f"[collision: {pol}]")
        if rating == "positive":
            status_tokens.update({"positive", "+", "rated"})
            badge_parts.append("[+] positive")
        elif rating == "negative":
            status_tokens.update({"negative", "-", "rated", "excluded"})
            badge_parts.append("[-] negative [excluded]")

        source_root = file_info.get("source_root")
        if source_root:
            root_name = os.path.basename(str(source_root)) or str(source_root)
            badge_parts.append(f"[root: {root_name.lower()}]")
        policy_action = file_info.get("policy_action")
        if policy_action:
            act_low = str(policy_action).lower()
            status_tokens.add(f"action_{act_low}")
            badge_parts.append(f"[action: {act_low}]")
        sens_rating = file_info.get("sensitivity_rating")
        if sens_rating:
            sens_low = str(sens_rating).lower()
            status_tokens.add(f"sens_{sens_low}")
            badge_parts.append(f"[sens: {sens_low}]")
        arch_prio = file_info.get("archival_priority")
        if arch_prio is not None:
            arch_str = (
                f"p{arch_prio}"
                if isinstance(arch_prio, int)
                or (
                    isinstance(arch_prio, str)
                    and not str(arch_prio).upper().startswith("P")
                )
                else str(arch_prio).lower()
            )
            status_tokens.add(f"arch_{arch_str}")
            badge_parts.append(f"[arch: {arch_str}]")

        route_tokens: set[str] = {route_token}
        if raw_routed_by:
            route_tokens.add(raw_routed_by)

        exts: set[str] = set()
        for candidate_name in (file_key, target_filename, filepath):
            if candidate_name:
                suffix = Path(str(candidate_name)).suffix.lower().lstrip(".")
                if suffix:
                    exts.add(suffix)

        searchable_blob = " ".join(
            [
                file_key.lower(),
                filepath.lower(),
                target_filename.lower(),
                folder.lower(),
                raw_routed_by,
                *badge_parts,
            ]
        )
        return {
            "status_tokens": status_tokens,
            "route_tokens": route_tokens,
            "exts": exts,
            "searchable_blob": searchable_blob,
        }

    def _build_matching_node_ids(
        self: TUIHostProtocol,
        plan_dict: dict[str, Any],
        query: str,
        current_folder: str = "",
    ) -> set[int]:
        """Perform a single O(N) bottom-up pass returning a set of dictionary object IDs matching the query."""
        matching_ids: set[int] = set()
        clean_query = query.strip().lower() if query else ""
        if not clean_query or not isinstance(plan_dict, dict):
            return matching_ids

        crit_lookup = self._build_path_lookup_index(
            getattr(self, "critical_error_paths", set())
        )
        warn_lookup = self._build_path_lookup_index(
            getattr(self, "warning_paths", set())
        )
        col_lookup = self._build_path_lookup_index(
            getattr(self, "collision_paths", set())
        )
        invalid_locks = TreeViewMixin._get_plan_invalid_locks(self)
        selected_set: set[str] = set(getattr(self, "selected_paths", None) or set())
        excluded_set: set[str] = set(getattr(self, "excluded_paths", None) or set())
        is_structured = _is_structured_tree_query(clean_query)

        def _walk(d: dict[str, Any], folder: str) -> bool:
            has_match = False
            for k, v in d.items():
                if isinstance(v, dict):
                    if v.get("__type__") == "file":
                        file_ctx = TreeViewMixin._build_file_search_context(
                            self,
                            str(k),
                            v,
                            folder,
                            crit_lookup=crit_lookup,
                            warn_lookup=warn_lookup,
                            col_lookup=col_lookup,
                            invalid_locks=invalid_locks,
                            selected_set=selected_set,
                            excluded_set=excluded_set,
                        )
                        if _file_matches_tree_query(clean_query, file_ctx):
                            matching_ids.add(id(v))
                            has_match = True
                    else:
                        sub_folder = (Path(folder) / k).as_posix() if folder else k
                        folder_direct_match = not is_structured and (
                            clean_query in k.lower()
                            or clean_query in sub_folder.lower()
                        )
                        child_match = _walk(v, sub_folder)
                        if folder_direct_match or child_match:
                            matching_ids.add(id(v))
                            has_match = True
            return has_match

        _walk(plan_dict, current_folder)
        return matching_ids

    def render_tree(self: TUIHostProtocol, search_query: str | None = None) -> None:
        """Render Textual Tree widget from in-memory plan structure without running validation worker."""
        try:
            tree_matches = self.query("#plan-tree")
            if not tree_matches:
                return
            tree = tree_matches.first(Tree)
            if search_query is None:
                search_query = self._get_current_search_query()

            query = search_query.strip().lower() if search_query else ""
            setattr(self, "_last_rendered_search_query", query)

            self._capture_tree_state(tree, query)

            tree.reset("Proposed Organization Plan")

            if not self._has_file_nodes(self.plan) and not self._has_folder_nodes(
                self.plan
            ):
                scan_diag = self._get_active_scan_diagnostics()
                from app.core.scanner import format_scan_diagnostics_summary

                diag_summary = format_scan_diagnostics_summary(scan_diag)
                if diag_summary:
                    eff_depth = scan_diag.get("effective_max_depth")
                    ws_label = getattr(self, "base_dir", "") or "target directory"
                    scope_word = "top-level files" if eff_depth == 0 else "files"
                    tree.root.add_leaf(
                        f"💡 0 {scope_word} matched in {ws_label}",
                        data={
                            "is_empty_state": True,
                            "action": "info",
                            "diag_summary": diag_summary,
                        },
                    )
                    tree.root.add_leaf(
                        f"   Skipped by scan filters: {diag_summary}",
                        data={
                            "is_empty_state": True,
                            "action": "info",
                            "diag_summary": diag_summary,
                        },
                    )
                    if int(scan_diag.get("max_depth") or 0) > 0:
                        tree.root.add_leaf(
                            "▶ Press [D] to Scan Subfolders (Depth 5)",
                            data={
                                "is_empty_state": True,
                                "action": "scan_subfolders",
                                "shortcut": "D",
                            },
                        )
                    tree.root.add_leaf(
                        "▶ Press [Ctrl+O] to Open Scan Filter Settings",
                        data={
                            "is_empty_state": True,
                            "action": "open_settings",
                            "shortcut": "Ctrl+O",
                        },
                    )
                    tree.root.add_leaf(
                        "▶ Press [Ctrl+B] to Select Different Directory",
                        data={
                            "is_empty_state": True,
                            "action": "select_dir",
                            "shortcut": "Ctrl+B",
                        },
                    )
                else:
                    tree.root.add_leaf(
                        "💡 Empty Workspace: No documents found in target directory",
                        data={"is_empty_state": True, "action": "info"},
                    )
                    tree.root.add_leaf(
                        "▶ Press [G] to Load Sample Dataset",
                        data={
                            "is_empty_state": True,
                            "action": "generate_sample_corpus",
                            "shortcut": "G",
                        },
                    )
                    tree.root.add_leaf(
                        "▶ Press [Ctrl+B] to Select Different Directory",
                        data={
                            "is_empty_state": True,
                            "action": "select_dir",
                            "shortcut": "Ctrl+B",
                        },
                    )
            else:
                matching_ids = (
                    self._build_matching_node_ids(self.plan, query) if query else None
                )
                crit_index = self._build_path_lookup_index(
                    getattr(self, "critical_error_paths", set())
                )
                warn_index = self._build_path_lookup_index(
                    getattr(self, "warning_paths", set())
                )
                collision_index = self._build_path_lookup_index(
                    getattr(self, "collision_paths", set())
                )
                nodes_added = self._build_tree_nodes(
                    self.plan,
                    tree.root,
                    current_folder="",
                    query=query,
                    matching_ids=matching_ids,
                    crit_index=crit_index,
                    warn_index=warn_index,
                    collision_index=collision_index,
                )
                if query and nodes_added == 0:
                    tree.root.add_leaf(
                        f"🔍 No matching tree nodes found for '{search_query}'",
                        data={"is_empty_state": True, "action": "info"},
                    )
            if query:
                tree.root.expand_all()
            else:
                tree.root.expand()
            self._restore_tree_state(tree, query)
            if not query:
                snap: dict[str, bool] = {}

                def _record_snap(n: TreeNode[Any]) -> None:
                    ndata = getattr(n, "data", None)
                    if isinstance(ndata, dict) and not ndata.get("is_file"):
                        nkey = (
                            ndata.get("filepath")
                            or ndata.get("folder")
                            or ndata.get("key")
                        )
                        if nkey:
                            snap[str(nkey)] = n.is_expanded
                    for ch in n.children:
                        _record_snap(ch)

                _record_snap(tree.root)
                setattr(self, "_last_rendered_expansion_snapshot", snap)
            self._update_tree_summary_strip()
            active_node = getattr(self, "active_tree_node", None)
            if tree.cursor_node and tree.cursor_node.data:
                self._update_inspector(tree.cursor_node, announce=False)
            elif active_node is not None and active_node.data:
                self._update_inspector(active_node, announce=False)
            else:
                self._update_inspector(None, announce=False)
        except Exception as e:
            logger.error(f"Error rendering tree: {e}")

    def rebuild_tree(
        self: TUIHostProtocol,
        search_query: str | None = None,
        run_validation: bool = True,
    ) -> None:
        """Rebuild Textual Tree widget from in-memory plan structure and optionally validate plan integrity."""
        self.render_tree(search_query=search_query)
        update_cta = getattr(self, "_update_onboarding_cta_visibility", None)
        if callable(update_cta):
            try:
                update_cta()
            except Exception:
                pass
        if run_validation:
            self.run_validation_worker()

    def _collect_file_nodes_from_dict(
        self: TUIHostProtocol, d: dict[str, Any], current_folder: str = ""
    ) -> list[dict[str, Any]]:
        """Collect all file info dicts nested within a plan directory subtree."""
        files: list[dict[str, Any]] = []
        if not isinstance(d, dict):
            return files
        for k, val in d.items():
            if isinstance(val, dict):
                if val.get("__type__") == "file":
                    TreeViewMixin._enrich_file_info_in_place(
                        self, val, str(k), current_folder
                    )
                    files.append(val)
                else:
                    sub_folder = (
                        (Path(current_folder) / k).as_posix() if current_folder else k
                    )
                    files.extend(
                        TreeViewMixin._collect_file_nodes_from_dict(
                            self, val, current_folder=sub_folder
                        )
                    )
        return files

    def _collect_visible_file_nodes_from_dict(
        self: TUIHostProtocol,
        node_dict: dict[str, Any],
        current_folder: str = "",
        query: str = "",
        parent_folder_matches: bool = False,
        matching_ids: set[int] | None = None,
    ) -> list[dict[str, Any]]:
        """Collect file info dicts for nodes visible under the active search query filter."""
        files: list[dict[str, Any]] = []
        if not isinstance(node_dict, dict):
            return files

        if not query:
            return TreeViewMixin._collect_file_nodes_from_dict(
                self, node_dict, current_folder=current_folder
            )

        if matching_ids is None and query:
            matching_ids = self._build_matching_node_ids(
                node_dict, query, current_folder=current_folder
            )

        for k, v in sorted(node_dict.items()):
            if isinstance(v, dict) and v.get("__type__") == "file":
                if parent_folder_matches or (
                    matching_ids is not None and id(v) in matching_ids
                ):
                    TreeViewMixin._enrich_file_info_in_place(
                        self, v, str(k), current_folder
                    )
                    files.append(v)
            elif isinstance(v, dict):
                sub_folder = (
                    (Path(current_folder) / k).as_posix() if current_folder else k
                )
                folder_matches = not _is_structured_tree_query(query) and (
                    query in k.lower() or query in sub_folder.lower()
                )
                if (
                    parent_folder_matches
                    or folder_matches
                    or (matching_ids is not None and id(v) in matching_ids)
                ):
                    files.extend(
                        self._collect_visible_file_nodes_from_dict(
                            v,
                            current_folder=sub_folder,
                            query=query,
                            parent_folder_matches=parent_folder_matches
                            or folder_matches,
                            matching_ids=matching_ids,
                        )
                    )
        return files

    def _node_matches_query(
        self: TUIHostProtocol,
        key: str,
        val: dict[str, Any],
        current_folder: str,
        query: str,
    ) -> bool:
        """Check if a node (file or directory) or any of its descendants match the search query."""
        if not query:
            return True
        matching_ids = self._build_matching_node_ids(
            {key: val}, query, current_folder=current_folder
        )
        return id(val) in matching_ids

    def _build_tree_nodes(
        self: TUIHostProtocol,
        node_dict: dict[str, Any],
        parent_item: TreeNode[Any],
        current_folder: str,
        query: str = "",
        parent_folder_matches: bool = False,
        matching_ids: set[int] | None = None,
        crit_index: tuple[set[str], set[str]] | None = None,
        warn_index: tuple[set[str], set[str]] | None = None,
        collision_index: tuple[set[str], set[str]] | None = None,
    ) -> int:
        """Recursively build tree nodes, filtering by search query if specified. Returns count of nodes added."""
        added_count = 0
        if query and matching_ids is None:
            matching_ids = self._build_matching_node_ids(
                node_dict, query, current_folder=current_folder
            )

        crit_lookup = (
            self._build_path_lookup_index(getattr(self, "critical_error_paths", set()))
            if crit_index is None
            else PathLookupIndex._coerce(crit_index)
        )
        warn_lookup = (
            self._build_path_lookup_index(getattr(self, "warning_paths", set()))
            if warn_index is None
            else PathLookupIndex._coerce(warn_index)
        )
        col_lookup = (
            self._build_path_lookup_index(getattr(self, "collision_paths", set()))
            if collision_index is None
            else PathLookupIndex._coerce(collision_index)
        )
        invalid_locks = TreeViewMixin._get_plan_invalid_locks(self)
        if not hasattr(self, "selected_paths") or self.selected_paths is None:
            self.selected_paths = set()
        if not hasattr(self, "excluded_paths") or self.excluded_paths is None:
            self.excluded_paths = set()
        visual_file_ids = _collect_visual_selected_file_ids(self)
        expansion_memory = getattr(self, "_tree_expansion_memory", {}) or {}
        is_structured = _is_structured_tree_query(query)

        for k, v in sorted(
            node_dict.items(),
            key=lambda x: (
                1 if isinstance(x[1], dict) and x[1].get("__type__") == "file" else 0,
                x[0],
            ),
        ):
            if isinstance(v, dict) and v.get("__type__") == "file":
                file_key = k
                file_info = v
                raw_sp = file_info.get("source_path")
                filepath = TreeViewMixin._resolve_file_source_path(
                    self, file_info, file_key, current_folder
                )
                file_info["filepath"] = filepath
                file_info["key"] = file_key
                file_info["folder"] = current_folder

                if query and not parent_folder_matches:
                    file_matches = matching_ids is not None and id(v) in matching_ids
                    if not file_matches:
                        continue

                src_rel_lookup = (
                    str(raw_sp).split("::", 1)[-1].replace("\\", "/") if raw_sp else ""
                )
                is_locked = (
                    file_key in self.locked_files
                    or filepath in self.locked_files
                    or (bool(src_rel_lookup) and src_rel_lookup in self.locked_files)
                    or bool(file_info.get("is_locked"))
                )
                rating = (
                    self._ratings_cache.get(filepath)
                    or (
                        self._ratings_cache.get(src_rel_lookup)
                        if src_rel_lookup
                        else None
                    )
                    or file_info.get("rating")
                )

                is_invalid_lock = TreeViewMixin._has_invalid_lock(
                    self, filepath, file_key, invalid_locks
                )

                path_id = resolve_file_selection_id(
                    self, file_info, file_key, current_folder
                )
                explicit_excluded = file_info.get("is_excluded")
                if explicit_excluded is True:
                    is_excluded = True
                elif explicit_excluded is False:
                    is_excluded = False
                else:
                    is_excluded = path_id in self.excluded_paths
                if str(rating or "").lower() == "negative":
                    is_excluded = True

                if is_excluded:
                    self.excluded_paths.add(path_id)
                else:
                    self.excluded_paths.discard(path_id)

                is_checked = (
                    False if is_excluded else bool(file_info.get("is_checked", True))
                )
                is_included = is_checked and not is_excluded
                is_selected = (
                    path_id in self.selected_paths or id(file_info) in visual_file_ids
                )
                file_info["is_checked"] = is_checked
                file_info["is_excluded"] = is_excluded
                file_info["is_selected"] = is_selected

                is_crit_node = crit_lookup._matches_node(filepath, file_key)
                is_warn_node = not is_crit_node and warn_lookup._matches_node(
                    filepath, file_key
                )

                sel_marker = "[●]" if is_selected else "[ ]"
                inc_marker = "[✓]" if is_included else "[EXCLUDED]"
                prefix_str = f"{sel_marker} {inc_marker}"
                label_parts = [prefix_str]
                if is_crit_node:
                    label_parts.append("[ERR]")
                elif is_warn_node:
                    label_parts.append("[WARN]")
                if is_invalid_lock:
                    label_parts.append("[LOCK WARNING]")
                elif is_locked:
                    label_parts.append("[LOCKED]")

                source_root = file_info.get("source_root")
                if source_root:
                    root_name = os.path.basename(source_root) or source_root
                    label_parts.append(f"[ROOT: {root_name}]")

                if rating == "positive":
                    label_parts.append("[+]")
                elif rating == "negative":
                    label_parts.append("[-]")

                routing_badge, _ = compute_routing_badge(file_info)

                policy_action = file_info.get("policy_action")
                if policy_action:
                    label_parts.append(f"[ACTION: {str(policy_action).upper()}]")

                sens_rating = file_info.get("sensitivity_rating")
                if sens_rating:
                    label_parts.append(f"[SENS: {str(sens_rating).upper()}]")

                arch_prio = file_info.get("archival_priority")
                if arch_prio is not None:
                    arch_str = (
                        f"P{arch_prio}"
                        if isinstance(arch_prio, int)
                        or (
                            isinstance(arch_prio, str)
                            and not str(arch_prio).upper().startswith("P")
                        )
                        else str(arch_prio).upper()
                    )
                    label_parts.append(f"[ARCH: {arch_str}]")

                target_filename = file_info.get("target_filename") or file_key
                target_path = TreeViewMixin._resolve_node_target_path(
                    self, file_info, current_folder, file_key
                )
                is_collision = col_lookup._matches_collision(
                    file_info, target_path, filepath, file_key
                )

                pol = str(getattr(self.settings, "CONFLICT_POLICY", "rename")).lower()
                if is_collision:
                    label_parts.append(f"[COLLISION: {pol.upper()}]")

                label_parts.append(file_key)
                if target_filename and target_filename != file_key:
                    label_parts.append(f"-> {target_filename}")
                label_parts.append(routing_badge)

                label_str = prefix_str + " 📄 " + " ".join(label_parts[1:])
                text_obj = Text(label_str)
                if is_crit_node:
                    text_obj.stylize("bold red")
                elif is_warn_node:
                    text_obj.stylize("bold yellow")

                node_data = {
                    "is_file": True,
                    "key": file_key,
                    "filepath": filepath,
                    "folder": current_folder,
                    "info": file_info,
                    "is_locked": is_locked,
                    "rating": rating,
                    "is_checked": is_checked,
                    "is_excluded": is_excluded,
                    "is_selected": is_selected,
                    "is_collision": is_collision,
                    "conflict_policy": pol,
                    "target_path": target_path,
                    "routing_badge": routing_badge,
                }
                parent_item.add_leaf(text_obj, data=node_data)
                added_count += 1
            elif isinstance(v, dict):
                sub_folder = (
                    (Path(current_folder) / k).as_posix() if current_folder else k
                )
                folder_matches = (
                    (
                        not is_structured
                        and (query in k.lower() or query in sub_folder.lower())
                    )
                    if query
                    else True
                )

                if query and not (
                    parent_folder_matches
                    or folder_matches
                    or (matching_ids is not None and id(v) in matching_ids)
                ):
                    continue

                node_data = {
                    "is_file": False,
                    "key": k,
                    "folder": sub_folder,
                    "info": v,
                }
                child_files = TreeViewMixin._collect_file_nodes_from_dict(
                    self, v, current_folder=sub_folder
                )
                if child_files:
                    sel_count = 0
                    inc_count = 0
                    for cf in child_files:
                        cf_id = resolve_file_selection_id(
                            self,
                            cf,
                            str(cf.get("key") or ""),
                            str(cf.get("folder") or sub_folder),
                        )
                        cf_excl = (
                            bool(cf.get("is_excluded", False))
                            or cf.get("is_checked") is False
                            or (
                                cf_id in self.excluded_paths and "is_excluded" not in cf
                            )
                            or str(cf.get("rating") or "").lower() == "negative"
                        )
                        if not cf_excl:
                            inc_count += 1
                        if cf_id in self.selected_paths or id(cf) in visual_file_ids:
                            sel_count += 1
                    if sel_count == len(child_files):
                        folder_sel = "[●]"
                    elif sel_count > 0:
                        folder_sel = "[◐]"
                    else:
                        folder_sel = "[ ]"
                    folder_inc = "[✓]" if inc_count > 0 else "[EXCLUDED]"
                    folder_cb = f"{folder_sel} {folder_inc} "
                else:
                    folder_cb = ""

                if query:
                    expand_folder = True
                elif sub_folder in expansion_memory:
                    expand_folder = bool(expansion_memory[sub_folder])
                elif k in expansion_memory:
                    expand_folder = bool(expansion_memory[k])
                else:
                    expand_folder = True

                child_tree_node = parent_item.add(
                    Text(f"{folder_cb}📁 {k}"),
                    data=node_data,
                    expand=expand_folder,
                )
                child_added = self._build_tree_nodes(
                    v,
                    child_tree_node,
                    current_folder=sub_folder,
                    query=query,
                    parent_folder_matches=parent_folder_matches or folder_matches,
                    matching_ids=matching_ids,
                    crit_index=crit_lookup,
                    warn_index=warn_lookup,
                    collision_index=col_lookup,
                )
                added_count += 1 + child_added

        return added_count

    def _update_inspector(
        self: TUIHostProtocol, node_or_data: Any = None, announce: bool = True
    ) -> str:
        """Update and return formatted metadata text for the inspector panel and path comparison pane."""
        update_cta = getattr(self, "_update_onboarding_cta_visibility", None)
        if callable(update_cta):
            try:
                update_cta()
            except Exception:
                pass

        if node_or_data is None:
            node_or_data = self.active_tree_node

        data = None
        if hasattr(node_or_data, "data"):
            data = getattr(node_or_data, "data", None)
        elif isinstance(node_or_data, dict):
            data = node_or_data

        path_comp_widget = None
        try:
            path_comp_widget = self.query_one("#path-comparison", Static)
        except Exception:
            pass

        if not data or not isinstance(data, dict):
            msg = (
                "Root folder of sorting plan."
                if getattr(self, "plan", None)
                else self._start_hint()
            )
            try:
                meta_widget = self.query_one("#meta-details", Static)
                meta_widget.update(escape_textual_markup(msg))
            except Exception:
                pass
            if path_comp_widget:
                plan_dict = getattr(self, "plan", None)
                all_files = (
                    TreeViewMixin._collect_file_nodes_from_dict(
                        self, plan_dict, current_folder=""
                    )
                    if isinstance(plan_dict, dict) and plan_dict
                    else []
                )
                if all_files:
                    path_comp_widget.update(
                        format_folder_path_comparison(all_files, self.base_dir)
                    )
                else:
                    path_comp_widget.update(
                        "Select a file or folder in the tree to compare source and target paths."
                    )
            return msg

        if data.get("is_empty_state"):
            action = data.get("action")
            diag_summary = data.get("diag_summary")
            if action == "scan_subfolders":
                msg = "Filtered scan diagnostic action. Press [D] or [Enter] to rescan nested subfolders up to depth 5."
            elif action == "open_settings":
                msg = "Filtered scan diagnostic action. Press [Ctrl+O] or [Enter] to open scan filter and depth settings."
            elif action == "generate_sample_corpus":
                msg = "Empty workspace node. Press [G] to create a sample dataset to try sorting on."
            elif action == "select_dir":
                msg = "Empty workspace node. Press [Ctrl+B] to select a different directory."
            elif diag_summary:
                msg = f"0 matched files. Skipped by scan filters: {diag_summary}."
            else:
                msg = "Empty workspace node. No documents found in target directory."
            if announce:
                self.announce(msg)
            try:
                meta_widget = self.query_one("#meta-details", Static)
                meta_widget.update(escape_textual_markup(msg))
            except Exception:
                pass
            if path_comp_widget:
                path_comp_widget.update("No documents available for path comparison.")
            return msg

        lines = []
        if data.get("is_file"):
            key = data.get("key", "")
            folder = data.get("folder") or "(Root)"
            locked = "Yes [LOCKED]" if data.get("is_locked") else "No"
            rating = data.get("rating") or "None"
            info = data.get("info") if isinstance(data.get("info"), dict) else {}

            target_fn = info.get("target_filename") or key
            target_folder = folder if folder != "(Root)" else ""
            src_filepath = (
                str(data["filepath"])
                if data.get("filepath")
                else TreeViewMixin._resolve_file_source_path(
                    self, info, str(key), target_folder
                )
            )
            raw_tp = data.get("target_path")
            resolved_tp = (
                str(raw_tp)
                if isinstance(raw_tp, str) and raw_tp
                else TreeViewMixin._resolve_node_target_path(
                    self, info, target_folder, str(key)
                )
            )
            if resolved_tp:
                target_filepath = resolved_tp
            elif self.base_dir and target_folder:
                target_filepath = os.path.join(self.base_dir, target_folder, target_fn)
            elif self.base_dir:
                target_filepath = os.path.join(self.base_dir, target_fn)
            else:
                target_filepath = (
                    os.path.join(target_folder, target_fn)
                    if target_folder
                    else target_fn
                )

            if path_comp_widget:
                table = format_side_by_side_path_comparison(
                    source_path=src_filepath,
                    target_path=target_filepath,
                    base_dir=self.base_dir,
                )
                path_comp_widget.update(table)

            lock_err = TreeViewMixin._get_invalid_lock_error(
                self, src_filepath, data.get("key")
            )
            lines = format_file_inspector_lines(
                key=key,
                path_display=src_filepath or data.get("filepath"),
                folder=folder,
                locked=locked,
                rating=rating,
                info=info,
                lock_error=lock_err,
                is_collision=bool(data.get("is_collision")),
                conflict_policy=(
                    data.get("conflict_policy")
                    or getattr(self.settings, "CONFLICT_POLICY", "rename")
                ),
            )

            if announce:
                routing_src = info.get("routed_by")
                pol_prio = info.get("policy_priority")
                match_val = info.get("match") or info.get("keyword")
                routing_detail = ""
                if routing_src:
                    routing_detail = f" Routed by {routing_src}"
                    if pol_prio is not None:
                        routing_detail += f" (priority {pol_prio})"
                    if match_val and str(match_val).strip().lower() != "none":
                        detail_lbl = (
                            "cluster keywords"
                            if str(routing_src).strip().lower() == "clustering"
                            else "matched rule"
                        )
                        routing_detail += f", {detail_lbl}: {match_val}"
                    routing_detail += "."
                self.announce(
                    f"Selected file '{key}' in folder '{folder}'. Locked: {locked}. Rating: {rating}.{routing_detail}"
                )
        else:
            key = data.get("key", "")
            folder = data.get("folder", "")
            folder_info = data.get("info", {})
            child_files = (
                TreeViewMixin._collect_file_nodes_from_dict(
                    self, folder_info, current_folder=folder
                )
                if isinstance(folder_info, dict)
                else []
            )

            if path_comp_widget:
                if child_files:
                    table = format_folder_path_comparison(
                        files_info=child_files,
                        base_dir=self.base_dir,
                    )
                    path_comp_widget.update(table)
                else:
                    path_comp_widget.update(
                        escape_textual_markup(
                            f"Folder category '{key}' contains no document items."
                        )
                    )

            lines = format_folder_inspector_lines(key=key, folder=folder)
            if announce:
                self.announce(f"Selected folder category '{key}' at path '{folder}'.")

        text = "\n".join(lines)
        try:
            meta_widget = self.query_one("#meta-details", Static)
            meta_widget.update(text)
        except Exception:
            pass

        return text

    def _get_active_scan_diagnostics(self: TUIHostProtocol) -> dict[str, Any]:
        """Retrieve structured scan filter diagnostics from pipeline, session, or plan."""
        pipeline = getattr(self, "pipeline", None)
        if pipeline is not None:
            p_diag = getattr(pipeline, "scan_diagnostics", None)
            if isinstance(p_diag, dict) and p_diag:
                return p_diag
        session = getattr(self, "app_session", None)
        if session is not None:
            s_diag = getattr(session, "last_scan_diagnostics", None)
            if isinstance(s_diag, dict) and s_diag:
                return s_diag
        plan_obj = getattr(self, "plan", None)
        if plan_obj is not None and not isinstance(plan_obj, dict):
            pl_diag = getattr(plan_obj, "scan_diagnostics", None)
            if isinstance(pl_diag, dict) and pl_diag:
                return pl_diag
        return {}

    def _update_tree_summary_strip(self: TUIHostProtocol) -> None:
        """Update compact selection and plan inclusion summary strip above ``#plan-tree``."""
        summary_matches = self.query("#tree-summary-label")
        if not summary_matches:
            return
        lbl = summary_matches.first(Static)
        plan_dict = getattr(self, "plan", None)
        all_files = (
            TreeViewMixin._collect_file_nodes_from_dict(self, plan_dict)
            if isinstance(plan_dict, dict) and plan_dict
            else []
        )
        selected_set: set[str] = set(getattr(self, "selected_paths", None) or set())
        excluded_set: set[str] = set(getattr(self, "excluded_paths", None) or set())
        visual_ids = _collect_visual_selected_file_ids(self)

        total_count = len(all_files)
        included_count = 0
        selected_count = 0
        for fi in all_files:
            pid = resolve_file_selection_id(
                self,
                fi,
                str(fi.get("key") or ""),
                str(fi.get("folder") or ""),
            )
            is_excl = (
                bool(fi.get("is_excluded", False))
                or fi.get("is_checked") is False
                or (pid in excluded_set and "is_excluded" not in fi)
                or str(fi.get("rating") or "").lower() == "negative"
            )
            if not is_excl:
                included_count += 1
            if pid in selected_set or id(fi) in visual_ids:
                selected_count += 1

        lbl.update(
            f"Selection: {selected_count} selected · Plan: {included_count} of {total_count} included"
        )

    def refresh_tree_selection_markers(self: TUIHostProtocol) -> None:
        """Refresh ``[●]``/``[ ]`` and ``[✓]``/``[EXCLUDED]`` row prefixes in place."""
        tree_matches = self.query("#plan-tree")
        if not tree_matches:
            return
        tree = tree_matches.first(Tree)
        selected_set: set[str] = set(getattr(self, "selected_paths", None) or set())
        excluded_set: set[str] = set(getattr(self, "excluded_paths", None) or set())
        visual_ids = _collect_visual_selected_file_ids(self)

        def _refresh_node(node: TreeNode[Any]) -> None:
            data = getattr(node, "data", None)
            if isinstance(data, dict) and not data.get("is_empty_state"):
                plain_txt = (
                    node.label.plain
                    if isinstance(node.label, Text)
                    else str(node.label)
                )
                styles = (
                    list(node.label.spans) if isinstance(node.label, Text) else None
                )
                base_style = node.label.style if isinstance(node.label, Text) else ""
                if data.get("is_file"):
                    info = data.get("info")
                    info_dict = info if isinstance(info, dict) else {}
                    pid = resolve_file_selection_id(
                        self,
                        info_dict,
                        str(data.get("key") or ""),
                        str(data.get("folder") or ""),
                    )
                    is_excl = (
                        bool(data.get("is_excluded", False))
                        or bool(info_dict.get("is_excluded", False))
                        or (pid in excluded_set and "is_excluded" not in info_dict)
                        or str(data.get("rating") or "").lower() == "negative"
                    )
                    is_chk = (
                        False if is_excl else bool(info_dict.get("is_checked", True))
                    )
                    is_inc = is_chk and not is_excl
                    is_sel = pid in selected_set or id(info_dict) in visual_ids
                    data["is_selected"] = is_sel
                    data["is_excluded"] = is_excl
                    data["is_checked"] = is_chk
                    info_dict["is_selected"] = is_sel
                    new_prefix = (
                        f"{'[●]' if is_sel else '[ ]'} "
                        f"{'[✓]' if is_inc else '[EXCLUDED]'} "
                    )
                    updated_txt = _ROW_PREFIX_RE.sub(new_prefix, plain_txt, count=1)
                    new_label = Text(updated_txt, style=base_style)
                    if styles and len(updated_txt) == len(plain_txt):
                        for sp in styles:
                            new_label.stylize(sp.style, sp.start, sp.end)
                    node.label = new_label
                else:
                    folder_path = str(data.get("folder") or "")
                    info_dict = (
                        data.get("info") if isinstance(data.get("info"), dict) else {}
                    )
                    child_files = TreeViewMixin._collect_file_nodes_from_dict(
                        self, info_dict, current_folder=folder_path
                    )
                    if child_files:
                        sel_c = 0
                        inc_c = 0
                        for cf in child_files:
                            cf_id = resolve_file_selection_id(
                                self,
                                cf,
                                str(cf.get("key") or ""),
                                str(cf.get("folder") or folder_path),
                            )
                            cf_excl = (
                                bool(cf.get("is_excluded", False))
                                or cf.get("is_checked") is False
                                or (cf_id in excluded_set and "is_excluded" not in cf)
                                or str(cf.get("rating") or "").lower() == "negative"
                            )
                            if not cf_excl:
                                inc_c += 1
                            if cf_id in selected_set or id(cf) in visual_ids:
                                sel_c += 1
                        f_sel = (
                            "[●]"
                            if sel_c == len(child_files)
                            else ("[◐]" if sel_c > 0 else "[ ]")
                        )
                        f_inc = "[✓]" if inc_c > 0 else "[EXCLUDED]"
                        updated_txt = _ROW_PREFIX_RE.sub(
                            f"{f_sel} {f_inc} ", plain_txt, count=1
                        )
                        node.label = Text(updated_txt, style=base_style)
            for ch in node.children:
                _refresh_node(ch)

        _refresh_node(tree.root)
        tree.refresh()
        self._update_tree_summary_strip()

    def _set_all_folders_expanded(self: TUIHostProtocol, expanded: bool) -> int:
        """Expand or collapse every destination folder node and persist in ``_tree_expansion_memory``."""
        if (
            not hasattr(self, "_tree_expansion_memory")
            or self._tree_expansion_memory is None
        ):
            self._tree_expansion_memory = {}

        def _record_plan_folders(d: dict[str, Any], prefix: str = "") -> None:
            for k, v in d.items():
                if isinstance(v, dict) and v.get("__type__") != "file":
                    sub = f"{prefix}/{k}" if prefix else k
                    self._tree_expansion_memory[sub] = expanded
                    self._tree_expansion_memory[str(k)] = expanded
                    _record_plan_folders(v, sub)

        if isinstance(self.plan, dict):
            _record_plan_folders(self.plan)

        tree_matches = self.query("#plan-tree")
        if not tree_matches:
            return 0
        tree = tree_matches.first(Tree)
        folder_count = 0
        snap: dict[str, bool] = {}

        def _apply_nodes(node: TreeNode[Any]) -> None:
            nonlocal folder_count
            ndata = getattr(node, "data", None)
            if (
                node is not tree.root
                and isinstance(ndata, dict)
                and not ndata.get("is_file")
                and not ndata.get("is_empty_state")
            ):
                folder_count += 1
                fkey = ndata.get("filepath") or ndata.get("folder") or ndata.get("key")
                if fkey:
                    self._tree_expansion_memory[str(fkey)] = expanded
                    snap[str(fkey)] = expanded
                if expanded:
                    node.expand()
                else:
                    node.collapse()
            for ch in node.children:
                _apply_nodes(ch)

        tree.root.expand()
        _apply_nodes(tree.root)
        setattr(self, "_last_rendered_expansion_snapshot", snap)

        if not expanded and tree.cursor_node and tree.cursor_node is not tree.root:
            top_collapsed: TreeNode[Any] | None = None
            curr = tree.cursor_node.parent
            while curr and curr is not tree.root:
                if not curr.is_expanded:
                    top_collapsed = curr
                curr = curr.parent
            if top_collapsed is not None:
                tree.move_cursor(top_collapsed)
                self.active_tree_node = top_collapsed
        tree.refresh()
        return folder_count

    def action_collapse_all(self: TUIHostProtocol) -> None:
        """Collapse all destination folders in ``#plan-tree``."""
        count = TreeViewMixin._set_all_folders_expanded(self, expanded=False)
        self.announce(f"Collapsed {count} folder(s) in sorting plan.")

    def action_expand_all(self: TUIHostProtocol) -> None:
        """Expand all destination folders in ``#plan-tree``."""
        count = TreeViewMixin._set_all_folders_expanded(self, expanded=True)
        self.announce(f"Expanded {count} folder(s) in sorting plan.")

action_collapse_all()

Collapse all destination folders in #plan-tree.

Source code in app/ui/mixins/tree_view.py
2012
2013
2014
2015
def action_collapse_all(self: TUIHostProtocol) -> None:
    """Collapse all destination folders in ``#plan-tree``."""
    count = TreeViewMixin._set_all_folders_expanded(self, expanded=False)
    self.announce(f"Collapsed {count} folder(s) in sorting plan.")

action_expand_all()

Expand all destination folders in #plan-tree.

Source code in app/ui/mixins/tree_view.py
2017
2018
2019
2020
def action_expand_all(self: TUIHostProtocol) -> None:
    """Expand all destination folders in ``#plan-tree``."""
    count = TreeViewMixin._set_all_folders_expanded(self, expanded=True)
    self.announce(f"Expanded {count} folder(s) in sorting plan.")

rebuild_tree(search_query=None, run_validation=True)

Rebuild Textual Tree widget from in-memory plan structure and optionally validate plan integrity.

Source code in app/ui/mixins/tree_view.py
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
def rebuild_tree(
    self: TUIHostProtocol,
    search_query: str | None = None,
    run_validation: bool = True,
) -> None:
    """Rebuild Textual Tree widget from in-memory plan structure and optionally validate plan integrity."""
    self.render_tree(search_query=search_query)
    update_cta = getattr(self, "_update_onboarding_cta_visibility", None)
    if callable(update_cta):
        try:
            update_cta()
        except Exception:
            pass
    if run_validation:
        self.run_validation_worker()

refresh_tree_selection_markers()

Refresh [●]/[ ] and [✓]/[EXCLUDED] row prefixes in place.

Source code in app/ui/mixins/tree_view.py
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
def refresh_tree_selection_markers(self: TUIHostProtocol) -> None:
    """Refresh ``[●]``/``[ ]`` and ``[✓]``/``[EXCLUDED]`` row prefixes in place."""
    tree_matches = self.query("#plan-tree")
    if not tree_matches:
        return
    tree = tree_matches.first(Tree)
    selected_set: set[str] = set(getattr(self, "selected_paths", None) or set())
    excluded_set: set[str] = set(getattr(self, "excluded_paths", None) or set())
    visual_ids = _collect_visual_selected_file_ids(self)

    def _refresh_node(node: TreeNode[Any]) -> None:
        data = getattr(node, "data", None)
        if isinstance(data, dict) and not data.get("is_empty_state"):
            plain_txt = (
                node.label.plain
                if isinstance(node.label, Text)
                else str(node.label)
            )
            styles = (
                list(node.label.spans) if isinstance(node.label, Text) else None
            )
            base_style = node.label.style if isinstance(node.label, Text) else ""
            if data.get("is_file"):
                info = data.get("info")
                info_dict = info if isinstance(info, dict) else {}
                pid = resolve_file_selection_id(
                    self,
                    info_dict,
                    str(data.get("key") or ""),
                    str(data.get("folder") or ""),
                )
                is_excl = (
                    bool(data.get("is_excluded", False))
                    or bool(info_dict.get("is_excluded", False))
                    or (pid in excluded_set and "is_excluded" not in info_dict)
                    or str(data.get("rating") or "").lower() == "negative"
                )
                is_chk = (
                    False if is_excl else bool(info_dict.get("is_checked", True))
                )
                is_inc = is_chk and not is_excl
                is_sel = pid in selected_set or id(info_dict) in visual_ids
                data["is_selected"] = is_sel
                data["is_excluded"] = is_excl
                data["is_checked"] = is_chk
                info_dict["is_selected"] = is_sel
                new_prefix = (
                    f"{'[●]' if is_sel else '[ ]'} "
                    f"{'[✓]' if is_inc else '[EXCLUDED]'} "
                )
                updated_txt = _ROW_PREFIX_RE.sub(new_prefix, plain_txt, count=1)
                new_label = Text(updated_txt, style=base_style)
                if styles and len(updated_txt) == len(plain_txt):
                    for sp in styles:
                        new_label.stylize(sp.style, sp.start, sp.end)
                node.label = new_label
            else:
                folder_path = str(data.get("folder") or "")
                info_dict = (
                    data.get("info") if isinstance(data.get("info"), dict) else {}
                )
                child_files = TreeViewMixin._collect_file_nodes_from_dict(
                    self, info_dict, current_folder=folder_path
                )
                if child_files:
                    sel_c = 0
                    inc_c = 0
                    for cf in child_files:
                        cf_id = resolve_file_selection_id(
                            self,
                            cf,
                            str(cf.get("key") or ""),
                            str(cf.get("folder") or folder_path),
                        )
                        cf_excl = (
                            bool(cf.get("is_excluded", False))
                            or cf.get("is_checked") is False
                            or (cf_id in excluded_set and "is_excluded" not in cf)
                            or str(cf.get("rating") or "").lower() == "negative"
                        )
                        if not cf_excl:
                            inc_c += 1
                        if cf_id in selected_set or id(cf) in visual_ids:
                            sel_c += 1
                    f_sel = (
                        "[●]"
                        if sel_c == len(child_files)
                        else ("[◐]" if sel_c > 0 else "[ ]")
                    )
                    f_inc = "[✓]" if inc_c > 0 else "[EXCLUDED]"
                    updated_txt = _ROW_PREFIX_RE.sub(
                        f"{f_sel} {f_inc} ", plain_txt, count=1
                    )
                    node.label = Text(updated_txt, style=base_style)
        for ch in node.children:
            _refresh_node(ch)

    _refresh_node(tree.root)
    tree.refresh()
    self._update_tree_summary_strip()

render_tree(search_query=None)

Render Textual Tree widget from in-memory plan structure without running validation worker.

Source code in app/ui/mixins/tree_view.py
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
def render_tree(self: TUIHostProtocol, search_query: str | None = None) -> None:
    """Render Textual Tree widget from in-memory plan structure without running validation worker."""
    try:
        tree_matches = self.query("#plan-tree")
        if not tree_matches:
            return
        tree = tree_matches.first(Tree)
        if search_query is None:
            search_query = self._get_current_search_query()

        query = search_query.strip().lower() if search_query else ""
        setattr(self, "_last_rendered_search_query", query)

        self._capture_tree_state(tree, query)

        tree.reset("Proposed Organization Plan")

        if not self._has_file_nodes(self.plan) and not self._has_folder_nodes(
            self.plan
        ):
            scan_diag = self._get_active_scan_diagnostics()
            from app.core.scanner import format_scan_diagnostics_summary

            diag_summary = format_scan_diagnostics_summary(scan_diag)
            if diag_summary:
                eff_depth = scan_diag.get("effective_max_depth")
                ws_label = getattr(self, "base_dir", "") or "target directory"
                scope_word = "top-level files" if eff_depth == 0 else "files"
                tree.root.add_leaf(
                    f"💡 0 {scope_word} matched in {ws_label}",
                    data={
                        "is_empty_state": True,
                        "action": "info",
                        "diag_summary": diag_summary,
                    },
                )
                tree.root.add_leaf(
                    f"   Skipped by scan filters: {diag_summary}",
                    data={
                        "is_empty_state": True,
                        "action": "info",
                        "diag_summary": diag_summary,
                    },
                )
                if int(scan_diag.get("max_depth") or 0) > 0:
                    tree.root.add_leaf(
                        "▶ Press [D] to Scan Subfolders (Depth 5)",
                        data={
                            "is_empty_state": True,
                            "action": "scan_subfolders",
                            "shortcut": "D",
                        },
                    )
                tree.root.add_leaf(
                    "▶ Press [Ctrl+O] to Open Scan Filter Settings",
                    data={
                        "is_empty_state": True,
                        "action": "open_settings",
                        "shortcut": "Ctrl+O",
                    },
                )
                tree.root.add_leaf(
                    "▶ Press [Ctrl+B] to Select Different Directory",
                    data={
                        "is_empty_state": True,
                        "action": "select_dir",
                        "shortcut": "Ctrl+B",
                    },
                )
            else:
                tree.root.add_leaf(
                    "💡 Empty Workspace: No documents found in target directory",
                    data={"is_empty_state": True, "action": "info"},
                )
                tree.root.add_leaf(
                    "▶ Press [G] to Load Sample Dataset",
                    data={
                        "is_empty_state": True,
                        "action": "generate_sample_corpus",
                        "shortcut": "G",
                    },
                )
                tree.root.add_leaf(
                    "▶ Press [Ctrl+B] to Select Different Directory",
                    data={
                        "is_empty_state": True,
                        "action": "select_dir",
                        "shortcut": "Ctrl+B",
                    },
                )
        else:
            matching_ids = (
                self._build_matching_node_ids(self.plan, query) if query else None
            )
            crit_index = self._build_path_lookup_index(
                getattr(self, "critical_error_paths", set())
            )
            warn_index = self._build_path_lookup_index(
                getattr(self, "warning_paths", set())
            )
            collision_index = self._build_path_lookup_index(
                getattr(self, "collision_paths", set())
            )
            nodes_added = self._build_tree_nodes(
                self.plan,
                tree.root,
                current_folder="",
                query=query,
                matching_ids=matching_ids,
                crit_index=crit_index,
                warn_index=warn_index,
                collision_index=collision_index,
            )
            if query and nodes_added == 0:
                tree.root.add_leaf(
                    f"🔍 No matching tree nodes found for '{search_query}'",
                    data={"is_empty_state": True, "action": "info"},
                )
        if query:
            tree.root.expand_all()
        else:
            tree.root.expand()
        self._restore_tree_state(tree, query)
        if not query:
            snap: dict[str, bool] = {}

            def _record_snap(n: TreeNode[Any]) -> None:
                ndata = getattr(n, "data", None)
                if isinstance(ndata, dict) and not ndata.get("is_file"):
                    nkey = (
                        ndata.get("filepath")
                        or ndata.get("folder")
                        or ndata.get("key")
                    )
                    if nkey:
                        snap[str(nkey)] = n.is_expanded
                for ch in n.children:
                    _record_snap(ch)

            _record_snap(tree.root)
            setattr(self, "_last_rendered_expansion_snapshot", snap)
        self._update_tree_summary_strip()
        active_node = getattr(self, "active_tree_node", None)
        if tree.cursor_node and tree.cursor_node.data:
            self._update_inspector(tree.cursor_node, announce=False)
        elif active_node is not None and active_node.data:
            self._update_inspector(active_node, announce=False)
        else:
            self._update_inspector(None, announce=False)
    except Exception as e:
        logger.error(f"Error rendering tree: {e}")

compute_routing_badge(file_info)

Return (routing_badge, route_token) for a planned file dictionary.

Source code in app/ui/mixins/tree_view.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def compute_routing_badge(file_info: Mapping[str, Any]) -> tuple[str, str]:
    """Return ``(routing_badge, route_token)`` for a planned file dictionary."""
    routed_by = str(file_info.get("routed_by") or "").strip().lower()
    has_policy_prio = file_info.get("policy_priority") is not None
    if routed_by == "jev_classifier" or file_info.get("is_jev"):
        return "[JEV]", "jev"
    if has_policy_prio or routed_by in {
        "policy",
        "compliance",
        "override",
        "action",
        "unarchive",
        "duplicate",
        "secret",
        "credential",
        "age",
        "modified_date",
        "created_date",
        "exif_date",
        "size",
    }:
        return "[POLICY]", "policy"
    if routed_by == "keyword":
        return "[KEYWORD]", "keyword"
    if routed_by == "learned":
        return "[LEARNED]", "learned"
    if routed_by == "pattern":
        return "[PATTERN]", "pattern"
    if routed_by == "extension_category":
        return "[EXT]", "ext"
    if routed_by == "historical":
        return "[HIST]", "hist"
    if routed_by == "similarity":
        return "[SIM]", "sim"
    if routed_by == "existing_folder":
        return "[FOLDER]", "folder"
    if routed_by == "fallback":
        return "[FALLBACK]", "fallback"
    return "[CLUSTER]", "cluster"

resolve_file_selection_id(host, file_info, file_key='', folder='')

Resolve a canonical path identifier for selected_paths and excluded_paths.

Source code in app/ui/mixins/tree_view.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def resolve_file_selection_id(
    host: TUIHostProtocol,
    file_info: Mapping[str, Any],
    file_key: str = "",
    folder: str = "",
) -> str:
    """Resolve a canonical path identifier for ``selected_paths`` and ``excluded_paths``."""
    eff_key = str(file_key or file_info.get("key") or "")
    eff_folder = str(folder or file_info.get("folder") or "")
    raw_fp = str(file_info.get("filepath") or "")
    if not raw_fp:
        raw_fp = TreeViewMixin._resolve_file_source_path(
            host, file_info, eff_key, eff_folder
        )
    if raw_fp:
        return os.path.normpath(raw_fp).replace("\\", "/")
    raw_sp = str(file_info.get("source_path") or "")
    if raw_sp:
        return os.path.normpath(raw_sp).replace("\\", "/")
    return f"{eff_folder}/{eff_key}".strip("/")

app.ui.modals.command_palette

app.ui.modals.command_palette

Command palette overlay modal screen.

CommandPaletteModal

Bases: ResponsiveModalScreen[PaletteCommand | None]

Modal screen presenting a searchable command palette overlay.

Source code in app/ui/modals/command_palette.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
class CommandPaletteModal(ResponsiveModalScreen[PaletteCommand | None]):
    """Modal screen presenting a searchable command palette overlay."""

    BINDINGS = [
        Binding("escape", "cancel", "Close palette", show=True),
        Binding("up", "cursor_up", "Move selection up", show=False),
        Binding("down", "cursor_down", "Move selection down", show=False),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .palette-box {
        width: 80%;
        max-width: 76;
        min-width: 40;
        max-height: 85%;
    }
    .palette-input {
        margin-bottom: 1;
    }
    .palette-list {
        height: 12;
        max-height: 16;
        border: solid $secondary;
        background: $surface;
    }
    .palette-status {
        margin-top: 1;
        color: $text-muted;
        text-style: italic;
    }
    CommandPaletteModal {
        background: rgba(0, 0, 0, 0.65);
        &.compact .palette-box, &.narrow .palette-box {
            padding: 0 1;
            width: 96%;
            max-height: 96%;
        }
        &.compact .palette-input {
            margin-bottom: 0;
        }
        &.compact .palette-status {
            margin-top: 0;
        }
    }
    """

    def __init__(
        self,
        catalog: list[PaletteCommand] | None = None,
        name: str | None = None,
        id: str | None = None,
        classes: str | None = None,
    ) -> None:
        super().__init__(name=name, id=id, classes=classes)
        self.commands: list[PaletteCommand] = catalog or list(DEFAULT_COMMAND_CATALOG)
        self._filtered_commands: list[PaletteCommand] = list(self.commands)
        self._last_applied_filter_state: tuple[str, int] | None = None

    @staticmethod
    def _build_option_for_command(cmd: PaletteCommand) -> Option:
        """Build a literal-markup Option entry for a PaletteCommand."""
        label = f"[{cmd.category}] {cmd.title}"
        if cmd.shortcut:
            label += f" ({cmd.shortcut})"
        return Option(literal_content(label), id=cmd.id)

    def compose(self) -> ComposeResult:
        """Compose modal layout widgets."""
        with Vertical(classes="palette-box modal-box"):
            yield Heading(
                "Command Palette Overlay [Ctrl+K]",
                level=1,
                classes="palette-title modal-title",
            )
            inp = Input(
                placeholder="Type a command or search actions...",
                id="palette-input",
                classes="palette-input",
            )
            self.watch(inp, "value", self._on_watched_input_value, init=False)
            yield inp
            option_list = OptionList(
                *(
                    self._build_option_for_command(cmd)
                    for cmd in self._filtered_commands
                ),
                id="palette-list",
                classes="palette-list",
            )
            if self._filtered_commands:
                option_list.highlighted = 0
            yield option_list
            yield Label(
                f"{len(self._filtered_commands)} commands available",
                id="palette-status",
                classes="palette-status",
            )

    def on_mount(self) -> None:
        """Initialize palette list, focus search input, and emit screen reader announcement."""
        super().on_mount()
        inp = self.query_one("#palette-input", Input)
        self._apply_filter_query(inp.value, announce=False, force=True)
        inp.focus()
        self.announce(
            "Opened command palette overlay dialog. Type to search actions.",
            priority="polite",
        )

    def _populate_option_list(self) -> None:
        """Populate OptionList with filtered command items."""
        option_list = self.query_one("#palette-list", OptionList)
        option_list.clear_options()
        for cmd in self._filtered_commands:
            option_list.add_option(self._build_option_for_command(cmd))

        status_lbl = self.query_one("#palette-status", Label)
        if self._filtered_commands:
            option_list.highlighted = 0
            status_lbl.update(f"{len(self._filtered_commands)} command(s) available")
        else:
            status_lbl.update("No matching commands found")

    def _apply_filter_query(
        self,
        raw_query: str,
        *,
        announce: bool = True,
        force: bool = False,
    ) -> None:
        """Filter command list for raw_query if state changed or forced."""
        query = raw_query.strip().lower()
        state = (query, len(self.commands))
        if force or self._last_applied_filter_state != state:
            if not query:
                self._filtered_commands = list(self.commands)
            else:
                self._filtered_commands = [
                    cmd
                    for cmd in self.commands
                    if query in cmd.title.lower()
                    or query in cmd.category.lower()
                    or query in cmd.description.lower()
                    or query in cmd.shortcut.lower()
                ]
            self._populate_option_list()
            self._last_applied_filter_state = state
        if announce:
            self.announce(
                f"{len(self._filtered_commands)} matching command(s) found.",
                priority="polite",
            )

    def _on_watched_input_value(self, value: str) -> None:
        """Update filtered options synchronously when #palette-input value mutates."""
        if self.query("#palette-list") and self.query("#palette-status"):
            self._apply_filter_query(value, announce=False)

    @on(Input.Changed, "#palette-input")
    def _on_input_changed(self, event: Input.Changed) -> None:
        """Filter command list in real time as query text changes."""
        self._apply_filter_query(event.value, announce=True)

    def action_cursor_up(self) -> None:
        """Move list selection up."""
        option_list = self.query_one("#palette-list", OptionList)
        if option_list.option_count > 0:
            if option_list.highlighted is None:
                option_list.highlighted = option_list.option_count - 1
            else:
                option_list.highlighted = max(0, option_list.highlighted - 1)

    def action_cursor_down(self) -> None:
        """Move list selection down."""
        option_list = self.query_one("#palette-list", OptionList)
        if option_list.option_count > 0:
            if option_list.highlighted is None:
                option_list.highlighted = 0
            else:
                option_list.highlighted = min(
                    option_list.option_count - 1, option_list.highlighted + 1
                )

    @on(Input.Submitted, "#palette-input")
    def _on_input_submitted(self, event: Input.Submitted) -> None:
        """Execute currently highlighted command when Enter is pressed in input field."""
        option_list = self.query_one("#palette-list", OptionList)
        highlighted = option_list.highlighted
        if highlighted is not None and 0 <= highlighted < len(self._filtered_commands):
            self._execute_command(self._filtered_commands[highlighted])

    @on(OptionList.OptionSelected, "#palette-list")
    def _on_option_selected(self, event: OptionList.OptionSelected) -> None:
        """Execute selected command when an OptionList item is clicked or selected."""
        opt_id = event.option.id
        for cmd in self._filtered_commands:
            if cmd.id == opt_id:
                self._execute_command(cmd)
                break

    def _execute_command(self, cmd: PaletteCommand) -> None:
        """Announce action execution and dismiss modal with selected command payload."""
        self.announce(f"Executing action: {cmd.title}", priority="polite")
        self.dismiss(cmd)

    def action_cancel(self) -> None:
        """Close command palette without executing any action."""
        self.announce("Closed command palette overlay dialog.", priority="polite")
        self.dismiss(None)

action_cancel()

Close command palette without executing any action.

Source code in app/ui/modals/command_palette.py
448
449
450
451
def action_cancel(self) -> None:
    """Close command palette without executing any action."""
    self.announce("Closed command palette overlay dialog.", priority="polite")
    self.dismiss(None)

action_cursor_down()

Move list selection down.

Source code in app/ui/modals/command_palette.py
415
416
417
418
419
420
421
422
423
424
def action_cursor_down(self) -> None:
    """Move list selection down."""
    option_list = self.query_one("#palette-list", OptionList)
    if option_list.option_count > 0:
        if option_list.highlighted is None:
            option_list.highlighted = 0
        else:
            option_list.highlighted = min(
                option_list.option_count - 1, option_list.highlighted + 1
            )

action_cursor_up()

Move list selection up.

Source code in app/ui/modals/command_palette.py
406
407
408
409
410
411
412
413
def action_cursor_up(self) -> None:
    """Move list selection up."""
    option_list = self.query_one("#palette-list", OptionList)
    if option_list.option_count > 0:
        if option_list.highlighted is None:
            option_list.highlighted = option_list.option_count - 1
        else:
            option_list.highlighted = max(0, option_list.highlighted - 1)

compose()

Compose modal layout widgets.

Source code in app/ui/modals/command_palette.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
def compose(self) -> ComposeResult:
    """Compose modal layout widgets."""
    with Vertical(classes="palette-box modal-box"):
        yield Heading(
            "Command Palette Overlay [Ctrl+K]",
            level=1,
            classes="palette-title modal-title",
        )
        inp = Input(
            placeholder="Type a command or search actions...",
            id="palette-input",
            classes="palette-input",
        )
        self.watch(inp, "value", self._on_watched_input_value, init=False)
        yield inp
        option_list = OptionList(
            *(
                self._build_option_for_command(cmd)
                for cmd in self._filtered_commands
            ),
            id="palette-list",
            classes="palette-list",
        )
        if self._filtered_commands:
            option_list.highlighted = 0
        yield option_list
        yield Label(
            f"{len(self._filtered_commands)} commands available",
            id="palette-status",
            classes="palette-status",
        )

on_mount()

Initialize palette list, focus search input, and emit screen reader announcement.

Source code in app/ui/modals/command_palette.py
341
342
343
344
345
346
347
348
349
350
def on_mount(self) -> None:
    """Initialize palette list, focus search input, and emit screen reader announcement."""
    super().on_mount()
    inp = self.query_one("#palette-input", Input)
    self._apply_filter_query(inp.value, announce=False, force=True)
    inp.focus()
    self.announce(
        "Opened command palette overlay dialog. Type to search actions.",
        priority="polite",
    )

PaletteCommand dataclass

Descriptor for a searchable command palette action.

Source code in app/ui/modals/command_palette.py
17
18
19
20
21
22
23
24
25
26
@dataclass
class PaletteCommand:
    """Descriptor for a searchable command palette action."""

    id: str
    title: str
    category: str
    shortcut: str = ""
    description: str = ""
    action_name: str = ""

app.ui.modals.drop_zone

app.ui.modals.drop_zone

Drop zone dialog for sorting dropped files, with its plan confirmation.

DropPlanConfirmModal

Bases: ResponsiveModalScreen[bool]

Show the DropZone plan, surface collision warnings, and apply user overrides before moving.

Source code in app/ui/modals/drop_zone.py
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
class DropPlanConfirmModal(ResponsiveModalScreen[bool]):
    """Show the DropZone plan, surface collision warnings, and apply user overrides before moving."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-box {
        max-width: 100;
        max-height: 95%;
    }
    #drop-plan-warnings {
        height: auto;
        max-height: 5;
        overflow-y: auto;
        border: solid $warning;
        color: $warning;
        padding: 0 1;
        margin-bottom: 0;
    }
    #drop-plan-warnings.hidden {
        display: none;
    }
    #drop-plan-tree {
        height: auto;
        max-height: 10;
        overflow-y: auto;
        border: solid $secondary;
        padding: 0 1;
    }
    #drop-plan-items-table {
        height: 5;
        min-height: 4;
        max-height: 6;
        border: solid $accent;
        margin-top: 0;
        margin-bottom: 0;
    }
    .plan-policy-row {
        width: 100%;
        height: auto;
        layout: grid;
        grid-size: 4;
        grid-columns: 1fr 1fr 1fr 1fr;
        grid-gutter: 0 1;
        margin-top: 0;
        margin-bottom: 0;
    }
    .plan-policy-row Button {
        width: 100%;
        min-width: 0;
        margin: 0;
    }
    .plan-override-row {
        width: 100%;
        height: auto;
        margin-top: 0;
        margin-bottom: 0;
        align: left middle;
    }
    #input-plan-folder-override {
        width: 1fr;
        margin: 0;
    }
    #btn-apply-folder-override {
        width: auto;
        min-width: 12;
        margin: 0 0 0 1;
    }
    DropPlanConfirmModal {
        &.compact .plan-policy-row Button,
        &.compact .plan-override-row Button,
        &.compact .button-row Button {
            height: 1;
            min-height: 1;
            border: none;
        }
        &.narrow .plan-policy-row {
            grid-size: 2;
            grid-columns: 1fr 1fr;
        }
    }
    """

    def __init__(
        self,
        summary: str,
        plan_lines: list[str],
        *,
        warnings: list[str] | None = None,
        batch_plan: Any = None,
        coordinator: Any = None,
    ):
        super().__init__()
        self.summary = summary
        self.plan_lines = list(plan_lines)
        self.warnings: list[str] = list(
            warnings
            if warnings is not None
            else (getattr(batch_plan, "warnings", None) or [])
        )
        self.batch_plan = batch_plan
        self.coordinator = coordinator

    def _format_warnings_text(self) -> str:
        if not self.warnings:
            return ""
        return "\n".join(f"! {w}" for w in self.warnings)

    def compose(self) -> ComposeResult:
        """Compose the plan preview, collision warnings, override controls, and action buttons."""
        with ModalBox(classes="modal-box"):
            yield Heading("Review DropZone Plan", level=1, classes="modal-title")
            with Vertical(classes="modal-body"):
                yield Label(self.summary, id="lbl-drop-plan-summary")
                warn_classes = "" if self.warnings else "hidden"
                yield Static(
                    self._format_warnings_text(),
                    id="drop-plan-warnings",
                    classes=warn_classes,
                    markup=False,
                )
                yield Static(
                    "\n".join(self.plan_lines), id="drop-plan-tree", markup=False
                )
                if self.batch_plan is not None:
                    items_table = DataTable(id="drop-plan-items-table")
                    items_table.cursor_type = "row"
                    items_table.tooltip = "Planned drop items; select a row to override its folder or exclusion"
                    yield items_table

                    with Horizontal(classes="plan-policy-row"):
                        btn_ren = Button(
                            "Policy: Rename",
                            id="btn-policy-rename",
                            variant="default",
                        )
                        btn_ren.tooltip = "Auto-rename colliding files while keeping clean filenames for higher queue priority"
                        yield btn_ren

                        btn_ovr = Button(
                            "Policy: Overwrite",
                            id="btn-policy-overwrite",
                            variant="warning",
                        )
                        btn_ovr.tooltip = "Overwrite colliding destination files (displaced originals are backed up for undo)"
                        yield btn_ovr

                        btn_skp = Button(
                            "Policy: Skip",
                            id="btn-policy-skip",
                            variant="default",
                        )
                        btn_skp.tooltip = (
                            "Skip moving files whose destination path already exists"
                        )
                        yield btn_skp

                        btn_exc = Button(
                            "Toggle Exclude",
                            id="btn-toggle-plan-exclude",
                            variant="error",
                        )
                        btn_exc.tooltip = "Exclude or re-include the selected file from this drop execution"
                        yield btn_exc

                    with Horizontal(classes="plan-override-row"):
                        folder_inp = Input(
                            placeholder="Override target folder for selected item (e.g. Finance or .)...",
                            id="input-plan-folder-override",
                        )
                        folder_inp.tooltip = "Enter a target category folder override for the selected item"
                        yield folder_inp

                        btn_folder = Button(
                            "Set Folder",
                            id="btn-apply-folder-override",
                            variant="primary",
                        )
                        btn_folder.tooltip = "Apply the entered target folder override to the selected item"
                        yield btn_folder

            with Horizontal(classes="button-row"):
                btn_cancel = Button("Cancel", id="btn-cancel-drop-plan")
                btn_cancel.tooltip = "Close without moving any files"
                yield btn_cancel
                btn_move = Button(
                    "Move Files", id="btn-confirm-drop-plan", variant="success"
                )
                btn_move.tooltip = "Move the files as shown. You can undo it with Ctrl+Z or History (Ctrl+Y)."
                yield btn_move

    def on_mount(self) -> None:
        """Populate item table and focus Cancel so Enter never moves files by accident."""
        super().on_mount()
        if self.batch_plan is not None:
            self._refresh_plan_view()
        self.query_one("#btn-cancel-drop-plan", Button).focus()

    def _selected_plan_item(self) -> Any:
        if self.batch_plan is None or not getattr(self.batch_plan, "items", None):
            return None
        try:
            table = self.query_one("#drop-plan-items-table", DataTable)
            row_idx = table.cursor_row
        except Exception:
            row_idx = 0
        items = list(self.batch_plan.items)
        if row_idx is not None and 0 <= row_idx < len(items):
            return items[row_idx]
        return items[0] if items else None

    def _refresh_plan_view(self) -> None:
        """Synchronize summary, warnings, plan lines, and interactive item table from batch_plan."""
        if self.batch_plan is not None:
            self.warnings = list(getattr(self.batch_plan, "warnings", None) or [])
            self.plan_lines = list(
                getattr(self.batch_plan, "plan_lines", None) or self.plan_lines
            )
            active_items = [
                it
                for it in self.batch_plan.items
                if not getattr(it, "is_excluded", False)
            ]
            folders = {(it.dest_base_dir, it.target_folder) for it in active_items}
            self.summary = (
                f"Move {len(active_items)} file(s) into {len(folders)} folder(s)? "
                f"[Conflict policy: {self.batch_plan.conflict_policy}] "
                "Nothing has been moved yet."
            )

        try:
            self.query_one("#lbl-drop-plan-summary", Label).update(self.summary)
        except Exception:
            pass

        try:
            warn_widget = self.query_one("#drop-plan-warnings", Static)
            warn_widget.update(self._format_warnings_text())
            if self.warnings:
                warn_widget.remove_class("hidden")
            else:
                warn_widget.add_class("hidden")
        except Exception:
            pass

        try:
            self.query_one("#drop-plan-tree", Static).update("\n".join(self.plan_lines))
        except Exception:
            pass

        if self.batch_plan is not None:
            try:
                table = self.query_one("#drop-plan-items-table", DataTable)
                prev_cursor = table.cursor_row or 0
                table.clear(columns=True)
                table.add_columns("State", "File", "Target Folder", "Policy")
                for it in self.batch_plan.items:
                    if it.is_excluded:
                        state = "Excluded"
                    elif it.has_collision:
                        state = "Collision"
                    else:
                        state = "Include"
                    table.add_row(
                        state,
                        os.path.basename(it.source_path),
                        it.target_folder,
                        it.conflict_policy,
                    )
                if self.batch_plan.items:
                    table.move_cursor(
                        row=min(prev_cursor, len(self.batch_plan.items) - 1)
                    )
            except Exception:
                pass

    def set_conflict_policy(self, policy: str, *, selected_only: bool = False) -> None:
        """Apply ``policy`` ('rename', 'overwrite', 'skip') globally or to the selected item."""
        if self.batch_plan is None or self.coordinator is None:
            return
        if selected_only:
            sel = self._selected_plan_item()
            if sel is None:
                return
            self.coordinator.apply_user_overrides(
                self.batch_plan,
                item_overrides={sel.item_id: {"conflict_policy": policy}},
            )
        else:
            self.coordinator.apply_user_overrides(
                self.batch_plan, conflict_policy=policy
            )
        self._refresh_plan_view()
        self.announce(f"Set drop conflict policy to '{policy}'.")

    def toggle_selected_exclusion(self) -> None:
        """Toggle ``is_excluded`` on the currently highlighted plan item."""
        if self.batch_plan is None or self.coordinator is None:
            return
        sel = self._selected_plan_item()
        if sel is None:
            return
        new_excl = not bool(sel.is_excluded)
        self.coordinator.apply_user_overrides(
            self.batch_plan,
            item_overrides={sel.item_id: {"is_excluded": new_excl}},
        )
        self._refresh_plan_view()
        verb = "Excluded" if new_excl else "Included"
        self.announce(f"{verb} '{os.path.basename(sel.source_path)}'.")

    def apply_folder_override(self, folder: str | None = None) -> None:
        """Override the target category folder of the currently highlighted plan item."""
        if self.batch_plan is None or self.coordinator is None:
            return
        sel = self._selected_plan_item()
        if sel is None:
            return
        raw_folder = folder
        if raw_folder is None:
            try:
                inp = self.query_one("#input-plan-folder-override", Input)
                raw_folder = inp.value.strip()
            except Exception:
                raw_folder = ""
        if raw_folder is None or raw_folder == "":
            return
        try:
            self.coordinator.apply_user_overrides(
                self.batch_plan,
                item_overrides={sel.item_id: {"target_folder": raw_folder}},
            )
            try:
                self.query_one("#input-plan-folder-override", Input).value = ""
            except Exception:
                pass
            self._refresh_plan_view()
            self.announce(
                f"Overrode folder for '{os.path.basename(sel.source_path)}' to '{raw_folder}'."
            )
        except (ValueError, PermissionError) as exc:
            self.announce(f"Invalid folder override: {exc}")

    @on(Button.Pressed, "#btn-policy-rename")
    def _on_policy_rename(self) -> None:
        self.set_conflict_policy("rename")

    @on(Button.Pressed, "#btn-policy-overwrite")
    def _on_policy_overwrite(self) -> None:
        self.set_conflict_policy("overwrite")

    @on(Button.Pressed, "#btn-policy-skip")
    def _on_policy_skip(self) -> None:
        self.set_conflict_policy("skip")

    @on(Button.Pressed, "#btn-toggle-plan-exclude")
    def _on_toggle_exclude(self) -> None:
        self.toggle_selected_exclusion()

    @on(Button.Pressed, "#btn-apply-folder-override")
    def _on_apply_folder_override(self) -> None:
        self.apply_folder_override()

    @on(Input.Submitted, "#input-plan-folder-override")
    def _on_submit_folder_override(self, event: Input.Submitted) -> None:
        if event.value.strip():
            self.apply_folder_override(event.value.strip())

    @on(Button.Pressed, "#btn-confirm-drop-plan")
    def action_confirm(self) -> None:
        """Confirm the moves."""
        if self.batch_plan is not None:
            active_items = [
                it
                for it in self.batch_plan.items
                if not getattr(it, "is_excluded", False)
            ]
            if not active_items:
                self.announce(
                    "All items are excluded; cancel or include at least one item."
                )
                return
        self.dismiss(True)

    @on(Button.Pressed, "#btn-cancel-drop-plan")
    def action_cancel(self) -> None:
        """Cancel without moving anything."""
        self.dismiss(False)

action_cancel()

Cancel without moving anything.

Source code in app/ui/modals/drop_zone.py
413
414
415
416
@on(Button.Pressed, "#btn-cancel-drop-plan")
def action_cancel(self) -> None:
    """Cancel without moving anything."""
    self.dismiss(False)

action_confirm()

Confirm the moves.

Source code in app/ui/modals/drop_zone.py
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
@on(Button.Pressed, "#btn-confirm-drop-plan")
def action_confirm(self) -> None:
    """Confirm the moves."""
    if self.batch_plan is not None:
        active_items = [
            it
            for it in self.batch_plan.items
            if not getattr(it, "is_excluded", False)
        ]
        if not active_items:
            self.announce(
                "All items are excluded; cancel or include at least one item."
            )
            return
    self.dismiss(True)

apply_folder_override(folder=None)

Override the target category folder of the currently highlighted plan item.

Source code in app/ui/modals/drop_zone.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
def apply_folder_override(self, folder: str | None = None) -> None:
    """Override the target category folder of the currently highlighted plan item."""
    if self.batch_plan is None or self.coordinator is None:
        return
    sel = self._selected_plan_item()
    if sel is None:
        return
    raw_folder = folder
    if raw_folder is None:
        try:
            inp = self.query_one("#input-plan-folder-override", Input)
            raw_folder = inp.value.strip()
        except Exception:
            raw_folder = ""
    if raw_folder is None or raw_folder == "":
        return
    try:
        self.coordinator.apply_user_overrides(
            self.batch_plan,
            item_overrides={sel.item_id: {"target_folder": raw_folder}},
        )
        try:
            self.query_one("#input-plan-folder-override", Input).value = ""
        except Exception:
            pass
        self._refresh_plan_view()
        self.announce(
            f"Overrode folder for '{os.path.basename(sel.source_path)}' to '{raw_folder}'."
        )
    except (ValueError, PermissionError) as exc:
        self.announce(f"Invalid folder override: {exc}")

compose()

Compose the plan preview, collision warnings, override controls, and action buttons.

Source code in app/ui/modals/drop_zone.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def compose(self) -> ComposeResult:
    """Compose the plan preview, collision warnings, override controls, and action buttons."""
    with ModalBox(classes="modal-box"):
        yield Heading("Review DropZone Plan", level=1, classes="modal-title")
        with Vertical(classes="modal-body"):
            yield Label(self.summary, id="lbl-drop-plan-summary")
            warn_classes = "" if self.warnings else "hidden"
            yield Static(
                self._format_warnings_text(),
                id="drop-plan-warnings",
                classes=warn_classes,
                markup=False,
            )
            yield Static(
                "\n".join(self.plan_lines), id="drop-plan-tree", markup=False
            )
            if self.batch_plan is not None:
                items_table = DataTable(id="drop-plan-items-table")
                items_table.cursor_type = "row"
                items_table.tooltip = "Planned drop items; select a row to override its folder or exclusion"
                yield items_table

                with Horizontal(classes="plan-policy-row"):
                    btn_ren = Button(
                        "Policy: Rename",
                        id="btn-policy-rename",
                        variant="default",
                    )
                    btn_ren.tooltip = "Auto-rename colliding files while keeping clean filenames for higher queue priority"
                    yield btn_ren

                    btn_ovr = Button(
                        "Policy: Overwrite",
                        id="btn-policy-overwrite",
                        variant="warning",
                    )
                    btn_ovr.tooltip = "Overwrite colliding destination files (displaced originals are backed up for undo)"
                    yield btn_ovr

                    btn_skp = Button(
                        "Policy: Skip",
                        id="btn-policy-skip",
                        variant="default",
                    )
                    btn_skp.tooltip = (
                        "Skip moving files whose destination path already exists"
                    )
                    yield btn_skp

                    btn_exc = Button(
                        "Toggle Exclude",
                        id="btn-toggle-plan-exclude",
                        variant="error",
                    )
                    btn_exc.tooltip = "Exclude or re-include the selected file from this drop execution"
                    yield btn_exc

                with Horizontal(classes="plan-override-row"):
                    folder_inp = Input(
                        placeholder="Override target folder for selected item (e.g. Finance or .)...",
                        id="input-plan-folder-override",
                    )
                    folder_inp.tooltip = "Enter a target category folder override for the selected item"
                    yield folder_inp

                    btn_folder = Button(
                        "Set Folder",
                        id="btn-apply-folder-override",
                        variant="primary",
                    )
                    btn_folder.tooltip = "Apply the entered target folder override to the selected item"
                    yield btn_folder

        with Horizontal(classes="button-row"):
            btn_cancel = Button("Cancel", id="btn-cancel-drop-plan")
            btn_cancel.tooltip = "Close without moving any files"
            yield btn_cancel
            btn_move = Button(
                "Move Files", id="btn-confirm-drop-plan", variant="success"
            )
            btn_move.tooltip = "Move the files as shown. You can undo it with Ctrl+Z or History (Ctrl+Y)."
            yield btn_move

on_mount()

Populate item table and focus Cancel so Enter never moves files by accident.

Source code in app/ui/modals/drop_zone.py
220
221
222
223
224
225
def on_mount(self) -> None:
    """Populate item table and focus Cancel so Enter never moves files by accident."""
    super().on_mount()
    if self.batch_plan is not None:
        self._refresh_plan_view()
    self.query_one("#btn-cancel-drop-plan", Button).focus()

set_conflict_policy(policy, *, selected_only=False)

Apply policy ('rename', 'overwrite', 'skip') globally or to the selected item.

Source code in app/ui/modals/drop_zone.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
def set_conflict_policy(self, policy: str, *, selected_only: bool = False) -> None:
    """Apply ``policy`` ('rename', 'overwrite', 'skip') globally or to the selected item."""
    if self.batch_plan is None or self.coordinator is None:
        return
    if selected_only:
        sel = self._selected_plan_item()
        if sel is None:
            return
        self.coordinator.apply_user_overrides(
            self.batch_plan,
            item_overrides={sel.item_id: {"conflict_policy": policy}},
        )
    else:
        self.coordinator.apply_user_overrides(
            self.batch_plan, conflict_policy=policy
        )
    self._refresh_plan_view()
    self.announce(f"Set drop conflict policy to '{policy}'.")

toggle_selected_exclusion()

Toggle is_excluded on the currently highlighted plan item.

Source code in app/ui/modals/drop_zone.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def toggle_selected_exclusion(self) -> None:
    """Toggle ``is_excluded`` on the currently highlighted plan item."""
    if self.batch_plan is None or self.coordinator is None:
        return
    sel = self._selected_plan_item()
    if sel is None:
        return
    new_excl = not bool(sel.is_excluded)
    self.coordinator.apply_user_overrides(
        self.batch_plan,
        item_overrides={sel.item_id: {"is_excluded": new_excl}},
    )
    self._refresh_plan_view()
    verb = "Excluded" if new_excl else "Included"
    self.announce(f"{verb} '{os.path.basename(sel.source_path)}'.")

DropZoneModal

Bases: ResponsiveModalScreen[dict[str, Any] | None]

Floating overlay modal dialog for quick drag-and-drop or paste file triage.

Source code in app/ui/modals/drop_zone.py
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
class DropZoneModal(ResponsiveModalScreen[dict[str, Any] | None]):
    """Floating overlay modal dialog for quick drag-and-drop or paste file triage."""

    HELP_URL = f"{TROUBLESHOOTING_URL}#dropzone-errors"

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-box {
        border: double $accent;
        width: 92%;
        max-width: 100;
        min-width: 40;
        max-height: 95%;
    }
    .modal-title {
        margin-bottom: 0;
    }
    .dropzone-target {
        border: dashed $primary;
        background: $surface;
        padding: 0 1;
        margin-top: 0;
        margin-bottom: 0;
        align: center middle;
        height: auto;
    }
    .dropzone-instructions {
        text-style: bold;
        color: $primary;
        text-align: center;
        margin-bottom: 0;
    }
    .dropzone-subinstructions {
        color: $text-muted;
        text-align: center;
    }
    #input-queue-filter {
        margin-top: 0;
        margin-bottom: 0;
    }
    .dest-row {
        width: 100%;
        height: auto;
        margin-top: 0;
        margin-bottom: 0;
        align: left middle;
    }
    #input-dest-dir {
        width: 1fr;
        margin-top: 0;
        margin-bottom: 0;
    }
    #btn-browse-dest {
        width: auto;
        min-width: 12;
        margin: 0 0 0 1;
    }
    .dropzone-split-container {
        height: auto;
        min-height: 7;
        layout: horizontal;
        margin-top: 0;
        margin-bottom: 0;
    }
    #dropzone-staging-table {
        width: 60%;
        height: 7;
        min-height: 6;
        margin-top: 0;
        margin-bottom: 0;
        border: solid $accent;
    }
    #dropzone-metadata-preview {
        width: 40%;
        height: 7;
        min-height: 6;
        border: solid $primary;
        background: $surface;
        padding: 0 1;
        margin-left: 1;
        overflow-x: hidden;
        overflow-y: auto;
    }
    .preview-header {
        text-style: bold;
        color: $accent;
        margin-bottom: 0;
    }
    .preview-field {
        color: $text;
    }
    .status-text {
        color: $accent;
        margin-top: 0;
        margin-bottom: 0;
        text-style: italic;
    }
    .button-row {
        margin-top: 0;
    }
    .queue-row {
        width: 100%;
        margin-top: 0;
        layout: grid;
        grid-size: 3;
        grid-columns: 1fr 1fr 1fr;
        grid-gutter: 0 1;
        height: auto;
    }
    .queue-row Button {
        width: 100%;
        min-width: 0;
        margin: 0;
    }
    Button:focus, Input:focus, DataTable:focus {
        border: heavy $accent;
        text-style: bold;
    }
    DropZoneModal {
        background: rgba(0, 0, 0, 0.7);
        &.compact .modal-box, &.narrow .modal-box {
            width: 98%;
            max-height: 96%;
        }
        &.compact .dropzone-target {
            border: none;
            padding: 0;
        }
        &.compact .dropzone-subinstructions {
            display: none;
        }
        &.compact Input, &.compact Input:focus {
            height: 1;
            border: none;
        }
        &.compact .dest-row Button {
            height: 1;
            min-height: 1;
            border: none;
            min-width: 10;
        }
        &.compact .dropzone-split-container {
            min-height: 6;
        }
        &.compact #dropzone-staging-table {
            height: 6;
            min-height: 6;
        }
        &.compact #dropzone-metadata-preview {
            height: 6;
            min-height: 6;
        }
        &.compact .button-row Button {
            height: 1;
            min-height: 1;
            border: none;
        }
        &.compact .queue-row Button {
            height: 1;
            min-height: 1;
            border: none;
            padding: 0;
        }
        &.narrow .dropzone-split-container {
            layout: vertical;
            min-height: 0;
        }
        &.narrow #dropzone-staging-table {
            width: 100%;
            height: 6;
            min-height: 6;
        }
        &.narrow #dropzone-metadata-preview {
            width: 100%;
            height: 4;
            min-height: 4;
            margin-left: 0;
            margin-top: 0;
        }
        &.narrow .queue-row {
            grid-size: 2;
            grid-columns: 1fr 1fr;
        }
        &.narrow .button-row Button {
            min-width: 0;
            padding: 0 1;
        }
    }
    """

    def __init__(
        self,
        settings: Any = None,
        base_dir: str | None = None,
        initial_paths: list[str] | None = None,
        initial_dest_dir: str | None = None,
    ):
        super().__init__()
        self.settings = settings
        self.base_dir = base_dir
        self.initial_dest_dir = initial_dest_dir
        self.initial_paths: list[str] = list(initial_paths) if initial_paths else []
        self.processed_result: dict[str, Any] | None = None
        self.staged_items: list[dict[str, Any]] = []
        self._coordinator: Any | None = None
        self._pending_batch_plan: Any | None = None
        self._pending_drop: list[dict[str, Any]] = []

    def compose(self) -> ComposeResult:
        """Compose floating dropzone modal overlay controls."""
        with ModalBox(classes="modal-box"):
            yield Heading(
                "Floating DropZone - Quick File Triage",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            with Vertical(classes="modal-body"):
                with Vertical(classes="dropzone-target"):
                    yield Label(
                        "📥 Drop or Paste File / Folder Paths Here",
                        classes="dropzone-instructions",
                    )
                    yield Label(
                        "Drag items onto terminal or paste absolute file paths to organize automatically",
                        classes="dropzone-subinstructions",
                    )
                inp = Input(
                    placeholder="Paste or drop file / directory paths here...",
                    id="input-drop-paths",
                )
                inp.tooltip = "Enter or drop target file or folder paths to trigger automated sorting"
                yield inp

                with Horizontal(classes="dest-row"):
                    dest_inp = Input(
                        value=self.initial_dest_dir or "",
                        placeholder="Destination folder (optional, leave blank to sort in place)...",
                        id="input-dest-dir",
                    )
                    dest_inp.tooltip = (
                        "Destination directory where sorted files will be placed "
                        "(leave empty to sort each item inside its own folder)"
                    )
                    yield dest_inp

                    btn_browse = Button(
                        "Browse", id="btn-browse-dest", variant="default"
                    )
                    btn_browse.tooltip = (
                        "Browse for a destination directory using native folder dialog"
                    )
                    yield btn_browse

                filter_inp = Input(
                    placeholder="Filter staged queue...",
                    id="input-queue-filter",
                )
                filter_inp.tooltip = "Filter staged queue items by typing keywords (filename, path, status, extension)"
                yield filter_inp

                with Container(classes="dropzone-split-container"):
                    table = DataTable(id="dropzone-staging-table")
                    table.cursor_type = "row"
                    table.tooltip = (
                        "Interactive staging queue displaying file status and details"
                    )
                    yield table

                    with Vertical(id="dropzone-metadata-preview"):
                        yield Label("📋 Metadata Preview", classes="preview-header")
                        yield Label(
                            "Path: N/A", id="preview-path", classes="preview-field"
                        )
                        yield Label(
                            "Size: N/A", id="preview-size", classes="preview-field"
                        )
                        yield Label(
                            "Modified: N/A", id="preview-mtime", classes="preview-field"
                        )
                        yield Label(
                            "Status: N/A", id="preview-status", classes="preview-field"
                        )

                with Horizontal(classes="queue-row"):
                    btn_filter = Button(
                        "Filter Unsupported",
                        id="btn-filter-unsupported",
                        variant="warning",
                    )
                    btn_filter.tooltip = (
                        "Remove unsupported file formats from the queue"
                    )
                    yield btn_filter

                    btn_remove = Button(
                        "Remove Item", id="btn-remove-item", variant="error"
                    )
                    btn_remove.tooltip = (
                        "Remove the selected row from the staging table"
                    )
                    yield btn_remove

                    btn_up = Button("Move Up", id="btn-move-up", variant="default")
                    btn_up.tooltip = "Move selected item up in queue priority"
                    yield btn_up

                    btn_down = Button(
                        "Move Down", id="btn-move-down", variant="default"
                    )
                    btn_down.tooltip = "Move selected item down in queue priority"
                    yield btn_down

                    btn_clear = Button(
                        "Clear Queue", id="btn-clear-queue", variant="default"
                    )
                    btn_clear.tooltip = "Clear all staged items from the modal"
                    yield btn_clear

                status_lbl = Label(
                    "Ready. Drop or enter paths above.",
                    id="dropzone-status",
                    classes="status-text",
                )
                status_lbl.tooltip = (
                    "Live visual progress indicators and classification status messages"
                )
                yield status_lbl

            with Horizontal(classes="button-row"):
                btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
                btn_cancel.tooltip = "Cancel dropzone triage operation and close dialog"
                yield btn_cancel

                btn_help = Button(
                    "Help", id="btn-help", variant="warning", classes="hidden"
                )
                btn_help.tooltip = (
                    "Open troubleshooting documentation for dropzone errors"
                )
                yield btn_help

                btn_process = Button("Sort Items", id="btn-process", variant="primary")
                btn_process.tooltip = (
                    "Start automated classification and relocation on dropped paths"
                )
                yield btn_process

    def _format_size(self, size_bytes: int) -> str:
        """Format size in bytes to human readable string."""
        if size_bytes <= 0:
            return "0 B"
        units = ["B", "KB", "MB", "GB", "TB"]
        size = float(size_bytes)
        idx = 0
        while size >= 1024.0 and idx < len(units) - 1:
            size /= 1024.0
            idx += 1
        if idx == 0:
            return f"{int(size)} B"
        return f"{size:.1f} {units[idx]}"

    def get_filter_query(self) -> str:
        """Get lowercase trimmed search query from input-queue-filter field."""
        try:
            inp = self.query_one("#input-queue-filter", Input)
            return inp.value.strip().lower()
        except Exception:
            return ""

    def get_filtered_items(self) -> list[dict[str, Any]]:
        """Return list of staged items filtered by search query."""
        query = self.get_filter_query()
        if not query:
            return list(self.staged_items)
        return [
            item
            for item in self.staged_items
            if query in item["filename"].lower()
            or query in item["path"].lower()
            or query in item["extension"].lower()
            or query in item["status"].lower()
        ]

    def _refresh_table(self) -> None:
        """Re-render staging table with items matching active search filter."""
        try:
            table = self.query_one("#dropzone-staging-table", DataTable)
        except Exception:
            return
        table.clear(columns=True)
        table.add_columns("Status", "Filename", "Extension", "Size", "Full Path")
        filtered = self.get_filtered_items()
        for item in filtered:
            table.add_row(
                item["status"],
                item["filename"],
                item["extension"],
                item["size_str"],
                item["path"],
            )
        self.update_active_metadata_preview()

    def update_metadata_preview(self, item: dict[str, Any] | None = None) -> None:
        """Update metadata preview card panel for given staged item."""
        if item is None:
            path_str = "N/A"
            size_str = "N/A"
            mtime_str = "N/A"
            status_str = "N/A"
        else:
            path_str = item.get("path", "N/A")
            size_str = item.get("size_str", "N/A")
            status_str = item.get("status", "N/A")
            if path_str and path_str != "N/A" and os.path.exists(path_str):
                try:
                    mtime = os.path.getmtime(path_str)
                    mtime_str = datetime.fromtimestamp(mtime).strftime(
                        "%Y-%m-%d %H:%M:%S"
                    )
                except Exception:
                    mtime_str = "Error reading timestamp"
            else:
                mtime_str = "N/A"

        try:
            self.query_one("#preview-path", Label).update(f"Path: {path_str}")
            self.query_one("#preview-size", Label).update(f"Size: {size_str}")
            self.query_one("#preview-mtime", Label).update(f"Modified: {mtime_str}")
            self.query_one("#preview-status", Label).update(f"Status: {status_str}")
        except Exception:
            pass

    def update_active_metadata_preview(self) -> None:
        """Fetch item corresponding to current table cursor row and update metadata preview."""
        try:
            table = self.query_one("#dropzone-staging-table", DataTable)
            row_idx = table.cursor_row
            filtered = self.get_filtered_items()
            if row_idx is not None and 0 <= row_idx < len(filtered):
                self.update_metadata_preview(filtered[row_idx])
            else:
                self.update_metadata_preview(None)
        except Exception:
            self.update_metadata_preview(None)

    @on(Input.Changed, "#input-queue-filter")
    def on_queue_filter_changed(self, event: Input.Changed) -> None:
        """Handle search filter text changes to dynamically update visible table rows."""
        self._refresh_table()

    @on(DataTable.RowHighlighted)
    @on(DataTable.RowSelected)
    @on(DataTable.CellHighlighted)
    def _on_table_row_highlighted(
        self,
        event: DataTable.RowHighlighted
        | DataTable.RowSelected
        | DataTable.CellHighlighted,
    ) -> None:
        """Update metadata preview panel on table row or cell focus/selection."""
        self.update_active_metadata_preview()

    @staticmethod
    def _decode_path_token(token: str) -> str:
        """Strip outer quotes, decode file:// URIs, and expand user home."""
        cleaned = token.strip()
        if len(cleaned) >= 2 and cleaned[0] == cleaned[-1] and cleaned[0] in ("'", '"'):
            cleaned = cleaned[1:-1].strip()
        if cleaned.lower().startswith("file://"):
            rest = cleaned[7:]
            if rest.lower().startswith("localhost/"):
                raw_url_path = rest[9:]
            elif rest.startswith("/"):
                raw_url_path = rest
            else:
                raw_url_path = f"//{rest}"
            decoded = re.sub(
                r"(?:%[0-9a-fA-F]{2})+",
                lambda m: bytes.fromhex(m.group(0).replace("%", "")).decode(
                    "utf-8", errors="replace"
                ),
                raw_url_path,
            )
            if re.match(r"^/[a-zA-Z]:[/\\]", decoded):
                decoded = decoded[1:]
            if os.sep == "\\":
                decoded = decoded.replace("/", "\\")
            return os.path.expanduser(decoded)
        return os.path.expanduser(cleaned)

    @staticmethod
    def _looks_like_standalone_path(token: str) -> bool:
        """Return True when a shell token begins with an explicit path or URI prefix."""
        t = token.strip()
        return bool(
            t.startswith(("/", "~", "./", "../", ".\\", "..\\"))
            or t.lower().startswith("file://")
            or _WIN_DRIVE_RE.match(t)
        )

    def _parse_raw_drop_input(self, raw_text: str) -> list[str]:
        """Parse pasted or dropped text into individual filesystem path strings."""
        parsed_paths: list[str] = []
        for raw_line in raw_text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
            line = raw_line.strip()
            if not line:
                continue

            has_quotes = "'" in line or '"' in line
            has_escaped_space = "\\ " in line
            file_uri_count = line.lower().count("file://")

            whole_candidate = self._decode_path_token(line)
            if not has_quotes and file_uri_count <= 1:
                if os.path.exists(os.path.abspath(whole_candidate)):
                    parsed_paths.append(whole_candidate)
                    continue

            use_posix = not bool(re.search(r"""(?:^|\s|["'])[a-zA-Z]:\\""", line))
            try:
                tokens = shlex.split(line, posix=use_posix)
            except ValueError:
                tokens = [line]

            if not tokens:
                continue

            if len(tokens) == 1:
                decoded_single = self._decode_path_token(tokens[0])
                if decoded_single:
                    parsed_paths.append(decoded_single)
                continue

            decoded_tokens = [self._decode_path_token(tok) for tok in tokens]
            decoded_tokens = [tok for tok in decoded_tokens if tok]
            if not decoded_tokens:
                continue

            if (
                not has_quotes
                and not has_escaped_space
                and file_uri_count == 0
                and not all(self._looks_like_standalone_path(tok) for tok in tokens[1:])
                and not any(
                    os.path.exists(os.path.abspath(tok)) for tok in decoded_tokens
                )
            ):
                parsed_paths.append(whole_candidate)
            else:
                parsed_paths.extend(decoded_tokens)

        return parsed_paths

    def _is_supported_file(self, abs_p: str) -> bool:
        """Check whether the sorting pipeline can classify or route ``abs_p``.

        Accepts all non-ignored file extensions so uncategorized files route cleanly
        into ``Miscellaneous`` unless explicitly ignored or halted by policy.
        """
        from app.core.metadata import evaluate_static_file_routing
        from app.core.scanner import ScanFilter

        scan_filter = ScanFilter.from_settings(settings=self.settings)
        if scan_filter.has_ignored_extension(abs_p) or scan_filter.is_transient_lock(
            abs_p
        ):
            return False

        _, _, halt_evaluation = evaluate_static_file_routing(
            abs_p,
            self.settings,
            check_extension_categories=True,
            defer_content_inspection=False,
        )
        if halt_evaluation:
            return False
        return True

    def stage_paths(self, raw_text: str) -> None:
        """Parse raw input string, validate dropped paths before expansion, and stage items."""
        raw_items = self._parse_raw_drop_input(raw_text)
        if not raw_items:
            return

        from app.core.mover import is_subpath_or_equal
        from app.core.pipeline import (
            drop_scope,
            expand_drop_scope_files,
            validate_drop_paths,
        )

        protected = (
            getattr(self.settings, "PROTECTED_PATHS", []) if self.settings else []
        )
        new_count = 0

        for item in raw_items:
            abs_p = os.path.abspath(item)
            _, issues = validate_drop_paths([abs_p], settings=self.settings)
            issue = issues[0] if issues else None
            is_prot = (issue is not None and issue.reason == "protected") or any(
                prot and is_subpath_or_equal(abs_p, prot) for prot in (protected or ())
            )

            if is_prot or issue is not None:
                self._stage_rejected_item(abs_p, issue=issue, is_protected=is_prot)
                new_count += 1
                continue

            scope_dir, scope_files = drop_scope(abs_p)
            if scope_files is None:
                _, files = expand_drop_scope_files(abs_p, settings=self.settings)
                for f_path in files:
                    self._add_single_file_to_staging(
                        os.path.join(scope_dir, f_path), protected, root_dir=scope_dir
                    )
                    new_count += 1
            else:
                self._add_single_file_to_staging(abs_p, protected)
                new_count += 1

        self._refresh_table()
        try:
            inp = self.query_one("#input-drop-paths", Input)
            inp.value = ""
        except Exception:
            pass

        ready_cnt = sum(1 for item in self.staged_items if item["status"] == "Ready")
        msg = f"Staged {new_count} item(s). Queue total: {len(self.staged_items)} ({ready_cnt} ready)."
        self.update_status_msg(msg)

    def _stage_rejected_item(
        self,
        abs_p: str,
        *,
        issue: Any = None,
        is_protected: bool = False,
    ) -> None:
        """Stage a blocked, missing, or ignored dropped path without expanding internal files."""
        cleaned_abs = abs_p.rstrip("/\\") or abs_p
        filename = os.path.basename(cleaned_abs) or abs_p
        ext = os.path.splitext(cleaned_abs)[1].lower()
        group_root = os.path.dirname(cleaned_abs) or cleaned_abs
        detail = getattr(issue, "detail", None)
        reason = getattr(issue, "reason", None)

        block_reason: str | None = None
        if is_protected or reason == "protected":
            status = "BLOCKED"
            block_reason = "protected"
        elif detail in ("app_bundle", "quarantine"):
            status = "BLOCKED"
            block_reason = str(detail)
        elif reason == "missing" or not os.path.exists(abs_p):
            status = "Not Found"
        else:
            status = "Unsupported"

        size_bytes = 0
        if os.path.exists(abs_p) and os.path.isfile(abs_p):
            try:
                size_bytes = os.path.getsize(abs_p)
            except OSError:
                size_bytes = 0
        size_str = self._format_size(size_bytes)

        existing = next(
            (item for item in self.staged_items if item["path"] == abs_p), None
        )
        if existing is None:
            entry: dict[str, Any] = {
                "path": abs_p,
                "filename": filename,
                "extension": ext,
                "size": size_bytes,
                "size_str": size_str,
                "status": status,
                "group_root": group_root,
            }
            if block_reason:
                entry["block_reason"] = block_reason
            self.staged_items.append(entry)

    def _add_single_file_to_staging(
        self,
        abs_p: str,
        protected: list[str] | None = None,
        root_dir: str | None = None,
    ) -> None:
        """Validate and append a single file path to staged_items."""
        from app.core.mover import is_subpath_or_equal
        from app.core.pipeline import validate_drop_paths

        _, issues = validate_drop_paths([abs_p], settings=self.settings)
        issue = issues[0] if issues else None
        issue_reason = issue.reason if issue else None
        issue_detail = issue.detail if issue else None
        is_prot = issue_reason == "protected" or any(
            prot and is_subpath_or_equal(abs_p, prot) for prot in (protected or ())
        )

        filename = os.path.basename(abs_p) or abs_p
        ext = os.path.splitext(abs_p)[1].lower()
        group_root = root_dir or os.path.dirname(abs_p)

        block_reason: str | None = None
        if is_prot:
            status = "BLOCKED"
            block_reason = "protected"
            size_bytes = os.path.getsize(abs_p) if os.path.isfile(abs_p) else 0
        elif issue_detail in ("app_bundle", "quarantine"):
            status = "BLOCKED"
            block_reason = str(issue_detail)
            size_bytes = 0
        elif issue_reason == "missing" or not os.path.exists(abs_p):
            status = "Not Found"
            size_bytes = 0
        elif issue_reason == "ignored" or not self._is_supported_file(abs_p):
            status = "Unsupported"
            size_bytes = os.path.getsize(abs_p) if os.path.isfile(abs_p) else 0
        else:
            status = "Ready"
            size_bytes = os.path.getsize(abs_p)

        size_str = self._format_size(size_bytes)

        existing = next(
            (item for item in self.staged_items if item["path"] == abs_p), None
        )
        if existing is None:
            entry: dict[str, Any] = {
                "path": abs_p,
                "filename": filename,
                "extension": ext,
                "size": size_bytes,
                "size_str": size_str,
                "status": status,
                "group_root": group_root,
            }
            if block_reason:
                entry["block_reason"] = block_reason
            self.staged_items.append(entry)
        elif root_dir and is_subpath_or_equal(abs_p, root_dir):
            existing["group_root"] = root_dir

    def filter_unsupported_items(self) -> None:
        """Remove items with 'Unsupported' status from the queue."""
        before = len(self.staged_items)
        self.staged_items = [
            item for item in self.staged_items if item["status"] != "Unsupported"
        ]
        removed = before - len(self.staged_items)
        self._refresh_table()
        msg = f"Filtered {removed} unsupported item(s) from queue. {len(self.staged_items)} item(s) remaining."
        self.update_status_msg(msg)

    def remove_selected_item(self) -> None:
        """Remove currently selected row from the staging table."""
        try:
            table = self.query_one("#dropzone-staging-table", DataTable)
            row_idx = table.cursor_row
        except Exception:
            row_idx = None

        filtered = self.get_filtered_items()
        if row_idx is not None and 0 <= row_idx < len(filtered):
            removed_item = filtered[row_idx]
            if removed_item in self.staged_items:
                self.staged_items.remove(removed_item)
            self._refresh_table()
            msg = f"Removed '{removed_item['filename']}' from queue. {len(self.staged_items)} item(s) remaining."
            self.update_status_msg(msg)
            new_filtered = self.get_filtered_items()
            if new_filtered:
                new_idx = min(row_idx, len(new_filtered) - 1)
                try:
                    table.move_cursor(row=new_idx)
                except Exception:
                    pass
            self.update_active_metadata_preview()
        else:
            self.update_status_msg("No item selected to remove.")

    def move_selected_item_up(self) -> None:
        """Move selected queue item up in priority."""
        try:
            table = self.query_one("#dropzone-staging-table", DataTable)
            row_idx = table.cursor_row
        except Exception:
            row_idx = None

        filtered = self.get_filtered_items()
        if row_idx is not None and 0 < row_idx < len(filtered):
            item_curr = filtered[row_idx]
            item_prev = filtered[row_idx - 1]
            idx_curr = self.staged_items.index(item_curr)
            idx_prev = self.staged_items.index(item_prev)
            self.staged_items[idx_curr], self.staged_items[idx_prev] = (
                self.staged_items[idx_prev],
                self.staged_items[idx_curr],
            )
            self._refresh_table()
            try:
                table.move_cursor(row=row_idx - 1)
            except Exception:
                pass
            self.update_active_metadata_preview()
            self.update_status_msg(
                f"Moved '{item_curr['filename']}' up in queue priority."
            )

    def move_selected_item_down(self) -> None:
        """Move selected queue item down in priority."""
        try:
            table = self.query_one("#dropzone-staging-table", DataTable)
            row_idx = table.cursor_row
        except Exception:
            row_idx = None

        filtered = self.get_filtered_items()
        if row_idx is not None and 0 <= row_idx < len(filtered) - 1:
            item_curr = filtered[row_idx]
            item_next = filtered[row_idx + 1]
            idx_curr = self.staged_items.index(item_curr)
            idx_next = self.staged_items.index(item_next)
            self.staged_items[idx_curr], self.staged_items[idx_next] = (
                self.staged_items[idx_next],
                self.staged_items[idx_curr],
            )
            self._refresh_table()
            try:
                table.move_cursor(row=row_idx + 1)
            except Exception:
                pass
            self.update_active_metadata_preview()
            self.update_status_msg(
                f"Moved '{item_curr['filename']}' down in queue priority."
            )

    def clear_queue(self) -> None:
        """Clear all staged items from modal queue."""
        self.staged_items.clear()
        self._refresh_table()
        self.update_status_msg("Cleared all staged items from the queue.")

    def on_mount(self) -> None:
        """Focus input on mount, stage initial paths if any, and announce modal opening."""
        self._app_ref = self.app
        super().on_mount()
        self._refresh_table()
        try:
            self.query_one("#input-drop-paths", Input).focus()
        except Exception:
            pass
        self.announce("Opened floating dropzone overlay for quick file triage.")
        if self.initial_paths:
            self.stage_paths("\n".join(str(p) for p in self.initial_paths))

    def on_paste(self, event: events.Paste) -> None:
        """Handle clipboard paste event for dropped path payloads."""
        focused = getattr(self, "focused", None)
        if focused is not None and getattr(focused, "id", None) in (
            "input-dest-dir",
            "input-queue-filter",
        ):
            return
        if event.text:
            event.stop()
            try:
                inp = self.query_one("#input-drop-paths", Input)
                inp.value = event.text.strip()
            except Exception:
                pass
            self.stage_paths(event.text)

    @on(Button.Pressed, "#btn-browse-dest")
    def on_btn_browse_dest_pressed(self, event: Button.Pressed) -> None:
        """Open native directory picker to populate the destination folder input."""
        curr_val = ""
        try:
            curr_val = self.query_one("#input-dest-dir", Input).value.strip()
        except Exception:
            pass
        initial_dir = curr_val or self.base_dir
        self._browse_dest_worker(initial_dir)

    @work(thread=True)
    def _browse_dest_worker(self, initial_dir: str | None) -> None:
        """Launch native folder selection dialog in a background thread."""
        from app.core.native_dialog import NativeDialogError, select_native_directory

        app_ref = getattr(self, "_app_ref", None)
        try:
            chosen = select_native_directory(initial_dir)
            if chosen:
                if app_ref:
                    app_ref.call_from_thread(self._on_dest_dir_selected, chosen)
                else:
                    self._on_dest_dir_selected(chosen)
        except NativeDialogError as exc:
            if app_ref:
                app_ref.call_from_thread(self._on_dest_dir_failed, str(exc))
            else:
                self._on_dest_dir_failed(str(exc))
        except Exception as exc:
            if app_ref:
                app_ref.call_from_thread(self._on_dest_dir_failed, str(exc))
            else:
                self._on_dest_dir_failed(str(exc))

    def _on_dest_dir_selected(self, path: str) -> None:
        """Set destination input from native folder browser selection."""
        abs_p = os.path.abspath(os.path.expanduser(path))
        try:
            inp = self.query_one("#input-dest-dir", Input)
            inp.value = abs_p
        except Exception:
            pass
        self.update_status_msg(f"Destination folder set to: {abs_p}")

    def _on_dest_dir_failed(self, reason: str) -> None:
        """Notify user and focus manual destination input when native dialog fails."""
        from app.ui.notifications import notify

        msg = "Native folder browser unavailable; enter destination path manually."
        notify(f"{msg} ({reason})", type="warning")
        self.update_status_msg(msg)
        try:
            self.query_one("#input-dest-dir", Input).focus()
        except Exception:
            pass

    @on(Input.Submitted, "#input-drop-paths")
    def on_input_submitted(self, event: Input.Submitted) -> None:
        """Handle enter key in drop paths input field to stage items or process queue."""
        if event.value.strip():
            self.stage_paths(event.value)

    @on(Button.Pressed, "#btn-filter-unsupported")
    def on_btn_filter_unsupported_pressed(self, event: Button.Pressed) -> None:
        """Filter unsupported file formats button handler."""
        self.filter_unsupported_items()

    @on(Button.Pressed, "#btn-remove-item")
    def on_btn_remove_pressed(self, event: Button.Pressed) -> None:
        """Remove selected item button handler."""
        self.remove_selected_item()

    @on(Button.Pressed, "#btn-move-up")
    def on_btn_move_up_pressed(self, event: Button.Pressed) -> None:
        """Move item up button handler."""
        self.move_selected_item_up()

    @on(Button.Pressed, "#btn-move-down")
    def on_btn_move_down_pressed(self, event: Button.Pressed) -> None:
        """Move item down button handler."""
        self.move_selected_item_down()

    @on(Button.Pressed, "#btn-clear-queue")
    def on_btn_clear_pressed(self, event: Button.Pressed) -> None:
        """Clear queue button handler."""
        self.clear_queue()

    @on(Button.Pressed, "#btn-process")
    def on_btn_process_pressed(self, event: Button.Pressed) -> None:
        """Handle Sort Items button press."""
        self.trigger_drop_triage()

    @on(Button.Pressed, "#btn-cancel")
    def action_cancel(self) -> None:
        """Dismiss dropzone modal."""
        self._close_pending_drop()
        self.announce("Cancelled dropzone modal dialog.")
        self.dismiss(None)

    def trigger_drop_triage(self) -> None:
        """Parse input paths if any, validate active queue, and trigger worker."""
        try:
            inp = self.query_one("#input-drop-paths", Input)
            raw_text = inp.value.strip()
        except Exception:
            raw_text = ""

        if raw_text:
            self.stage_paths(raw_text)

        help_url = f"{TROUBLESHOOTING_URL}#dropzone-errors"

        raw_dest: str | None = None
        try:
            dest_inp = self.query_one("#input-dest-dir", Input)
            raw_dest = dest_inp.value.strip()
        except Exception:
            raw_dest = (self.initial_dest_dir or "").strip()

        resolved_dest: str | None = None
        if raw_dest:
            from app.core.pipeline import validate_drop_destination
            from app.ui.notifications import notify

            decoded_dest = self._decode_path_token(raw_dest)
            resolved_dest, dest_err = validate_drop_destination(
                decoded_dest, settings=self.settings
            )
            if dest_err in ("protected", "not_directory"):
                err_text = (
                    f"Protected destination blocked: {resolved_dest}"
                    if dest_err == "protected"
                    else f"Destination path is not a folder: {resolved_dest}"
                )
                self._show_help_button(help_url)
                notify(f"DropZone error: {err_text}", type="error", help_url=help_url)
                self.update_status_msg(err_text, help_url=help_url)
                return

        filtered = self.get_filtered_items()
        ready_paths = [item["path"] for item in filtered if item["status"] == "Ready"]

        if not ready_paths:
            blocked_items = [
                item for item in filtered if item["status"] == "BLOCKED"
            ] or [item for item in self.staged_items if item["status"] == "BLOCKED"]
            status_err_detail: str | None = None
            if blocked_items:
                first_blk = blocked_items[0]
                blk_reason = first_blk.get("block_reason")
                if blk_reason == "app_bundle":
                    err_text = f"Application bundle blocked: {first_blk['filename']}"
                    status_err_detail = (
                        f"Application bundle blocked: {first_blk['path']}"
                    )
                elif blk_reason == "quarantine":
                    err_text = f"Quarantine folder blocked: {first_blk['filename']}"
                    status_err_detail = (
                        f"Quarantine folder blocked: {first_blk['path']}"
                    )
                else:
                    err_text = f"Protected path blocked: {first_blk['filename']}"
                    status_err_detail = f"Protected path blocked: {first_blk['path']}"
            elif self.staged_items:
                err_text = "No ready files to sort in queue."
            else:
                err_text = "No file or folder paths provided."

            self._show_help_button(help_url)
            from app.ui.notifications import notify

            notify(f"DropZone error: {err_text}", type="error", help_url=help_url)
            self.update_status_msg(
                status_err_detail if status_err_detail else f"Error: {err_text}",
                help_url=help_url,
            )
            return

        self.update_status_msg(f"Processing {len(ready_paths)} dropped item(s)...")
        self.run_drop_worker(ready_paths, dest_dir=resolved_dest)

    def update_status_msg(self, msg: str, help_url: str | None = None) -> None:
        """Update live status message region and screen reader announcement."""
        display_msg = f"{msg} [Help: {help_url}]" if help_url else msg
        try:
            lbl = self.query_one("#dropzone-status", Label)
            lbl.update(display_msg)
        except Exception:
            pass
        self.announce(msg, help_url=help_url)

    def _close_pending_drop(self) -> None:
        """Close the sessions of a planned but unexecuted drop."""
        batch_plan = getattr(self, "_pending_batch_plan", None)
        coord = getattr(self, "_coordinator", None)
        if batch_plan is not None and coord is not None:
            try:
                coord.close_batch(batch_plan)
            except Exception:
                pass
        self._pending_batch_plan = None
        for item in getattr(self, "_pending_drop", []):
            try:
                item["session"].close()
            except Exception:
                pass
        self._pending_drop = []

    @work(exclusive=True, thread=True)
    def run_drop_worker(
        self, target_paths: list[str], dest_dir: str | None = None
    ) -> None:
        """Plan the dropped items via DropBatchCoordinator in a worker thread, then ask before moving."""
        app_ref = getattr(self, "_app_ref", None)
        self._close_pending_drop()
        try:
            from app.core.pipeline import DropBatchCoordinator

            staged_roots = {
                item["path"]: item.get("group_root")
                for item in list(self.staged_items)
                if isinstance(item, dict) and "path" in item
            }
            coordinator = DropBatchCoordinator(self.settings)

            def _on_plan_progress(info: Any) -> None:
                if app_ref is None:
                    return
                stage = (
                    info.get("stage") if isinstance(info, dict) else None
                ) or "Classifying dropped items..."
                app_ref.call_from_thread(self.update_status_msg, str(stage))

            batch_plan = coordinator.plan_batch(
                target_paths,
                dest_dir=dest_dir,
                staged_roots=staged_roots,
                progress_callback=_on_plan_progress if app_ref else None,
            )
            self._coordinator = coordinator
            self._pending_batch_plan = batch_plan
            self._pending_drop = [
                {
                    "path": grp.source_root,
                    "session": grp.session,
                    "plan": grp.plan,
                    "file_count": len(grp.rel_files),
                    "re_rooted": grp.re_rooted,
                }
                for grp in batch_plan.groups
            ]
            if app_ref:
                app_ref.call_from_thread(self._confirm_pending_drop)
            else:
                self._confirm_pending_drop()
        except Exception as e:
            logger.exception(f"Error during dropzone classification: {e}")
            self._close_pending_drop()
            if app_ref:
                app_ref.call_from_thread(
                    self.update_status_msg, f"Dropzone triage error: {e}"
                )

    def _confirm_pending_drop(self) -> None:
        """Show what the drop would do, including collision warnings and overrides, and wait for go-ahead."""
        from app.core.domain_contracts import _make_json_serializable
        from app.core.plan_format import (
            count_plan_actions,
            format_plan_tree,
            normalize_duplicate_mode,
        )
        from app.core.verifier import VerificationEngine
        from app.ui.modals.edit import DuplicateReviewModal

        batch_plan = getattr(self, "_pending_batch_plan", None)
        coordinator = getattr(self, "_coordinator", None)

        dup_mode = normalize_duplicate_mode(
            getattr(self.settings, "DUPLICATE_ACTION", "off")
        )
        detect_original_by = str(
            getattr(self.settings, "DETECT_ORIGINAL_BY", "first_seen") or "first_seen"
        )

        if dup_mode == "review" and not getattr(
            self, "_drop_duplicates_reviewed", False
        ):
            self._pending_drop_flush_trash = False
            dup_groups: list[dict[str, Any]] = []
            plan_targets: list[tuple[str, dict[str, Any]]] = []
            if batch_plan is not None:
                if batch_plan.resolved_dest and batch_plan.unified_plan is not None:
                    plan_targets.append(
                        (batch_plan.resolved_dest, batch_plan.unified_plan)
                    )
                else:
                    for grp in batch_plan.groups:
                        plan_targets.append((grp.source_root, grp.plan))
            else:
                for item in self._pending_drop:
                    if isinstance(item.get("plan"), dict):
                        plan_targets.append((item["session"].base_dir, item["plan"]))

            seen_gids: set[str] = set()
            for p_base, p_dict in plan_targets:
                for dg in VerificationEngine.get_duplicate_groups(
                    p_base,
                    p_dict,
                    detect_original_by=detect_original_by,
                ):
                    gid = str(dg.get("group_id") or "")
                    if gid and gid not in seen_gids:
                        seen_gids.add(gid)
                        dup_groups.append(dg)

            if dup_groups:

                def _on_dup_review(selections: dict[str, str] | None) -> None:
                    if selections is None:
                        self._drop_duplicates_reviewed = False
                        self._pending_drop_flush_trash = False
                        self._close_pending_drop()
                        self.update_status_msg(
                            "Cancelled duplicate review. No files were moved."
                        )
                        return

                    self._drop_duplicates_reviewed = True
                    self._pending_drop_flush_trash = any(
                        val == "trash" for val in selections.values()
                    )
                    for p_base, p_dict in plan_targets:
                        local_groups = VerificationEngine.get_duplicate_groups(
                            p_base,
                            p_dict,
                            detect_original_by=detect_original_by,
                        )
                        if local_groups:
                            VerificationEngine.apply_deduplication_selections(
                                p_base,
                                p_dict,
                                selections,
                                groups=local_groups,
                                detect_original_by=detect_original_by,
                            )
                    if batch_plan is not None and batch_plan.unified_plan is not None:
                        for grp in batch_plan.groups:
                            grp_groups = VerificationEngine.get_duplicate_groups(
                                batch_plan.resolved_dest or grp.source_root,
                                grp.plan,
                                detect_original_by=detect_original_by,
                            )
                            if grp_groups:
                                VerificationEngine.apply_deduplication_selections(
                                    batch_plan.resolved_dest or grp.source_root,
                                    grp.plan,
                                    selections,
                                    groups=grp_groups,
                                    detect_original_by=detect_original_by,
                                )
                    if batch_plan is not None and coordinator is not None:
                        coordinator.refresh_verification(batch_plan)
                    self._confirm_pending_drop()

                self.app.push_screen(
                    DuplicateReviewModal(duplicate_groups=dup_groups),
                    _on_dup_review,
                )
                return
        elif not getattr(self, "_drop_duplicates_reviewed", False):
            self._pending_drop_flush_trash = dup_mode == "trash"

        lines: list[str] = []
        total_files = total_folders = total_staged = total_trashed = 0
        for item in self._pending_drop:
            plan = _make_json_serializable(item["plan"])
            tree, n_files, n_folders = format_plan_tree(plan)
            p_counts = count_plan_actions(plan)
            item_staged = p_counts["staged"]
            item_trashed = p_counts["trashed"]
            if not (n_files or item_staged or item_trashed):
                continue
            total_files += n_files
            total_folders += n_folders
            total_staged += item_staged
            total_trashed += item_trashed
            lines.append(f"In {item['session'].base_dir}:")
            lines.extend(f"  {line}" for line in tree)

        if batch_plan is not None and batch_plan.plan_lines and not lines:
            lines = list(batch_plan.plan_lines)
            for it in batch_plan.items:
                if getattr(it, "is_excluded", False):
                    continue
                dup_act = str(it.node_ref.get("duplicate_action") or "").strip().lower()
                pol_act = str(it.node_ref.get("policy_action") or "").strip().lower()
                if dup_act == "trash" or pol_act == "trash":
                    total_trashed += 1
                elif dup_act == "stage":
                    total_staged += 1
                else:
                    total_files += 1
            total_folders = len(
                {
                    (it.dest_base_dir, it.target_folder)
                    for it in batch_plan.items
                    if not getattr(it, "is_excluded", False)
                    and str(it.node_ref.get("duplicate_action") or "").strip().lower()
                    not in ("stage", "trash")
                    and str(it.node_ref.get("policy_action") or "").strip().lower()
                    != "trash"
                }
            )

        if not (total_files or total_staged or total_trashed):
            self._drop_duplicates_reviewed = False
            self._pending_drop_flush_trash = False
            self._close_pending_drop()
            self.update_status_msg("Nothing to sort: no files could be classified.")
            return

        warnings = list(getattr(batch_plan, "warnings", None) or [])
        warn_suffix = f" ({len(warnings)} warning(s) detected)" if warnings else ""
        dup_parts: list[str] = []
        if total_staged > 0:
            dup_parts.append(f"{total_staged} staged")
        if total_trashed > 0:
            dup_parts.append(
                f"{total_trashed} trashed"
                if getattr(self, "_pending_drop_flush_trash", False)
                else f"{total_trashed} staged for trash"
            )
        dup_note = f" ({', '.join(dup_parts)})" if dup_parts else ""
        summary = (
            f"Move {total_files} file(s) into {total_folders} folder(s){dup_note}?{warn_suffix} "
            "Nothing has been moved yet."
        )
        self.update_status_msg(f"Review the plan: {summary}")

        def _on_answer(confirmed: bool | None) -> None:
            self._drop_duplicates_reviewed = False
            if confirmed:
                self.update_status_msg(
                    "Relocating items according to generated sorting plan..."
                )
                self.run_drop_execute_worker()
            else:
                self._pending_drop_flush_trash = False
                self._close_pending_drop()
                self.update_status_msg("Cancelled. No files were moved.")

        self.app.push_screen(
            DropPlanConfirmModal(
                summary,
                lines,
                warnings=warnings,
                batch_plan=batch_plan,
                coordinator=coordinator,
            ),
            _on_answer,
        )

    @work(exclusive=True, thread=True)
    def run_drop_execute_worker(self) -> None:
        """Execute the confirmed drop batch under one undo session in a worker thread."""
        app_ref = getattr(self, "_app_ref", None)
        batch_plan = getattr(self, "_pending_batch_plan", None)
        coordinator = getattr(self, "_coordinator", None)
        flush_trash = bool(getattr(self, "_pending_drop_flush_trash", False))
        self._pending_drop_flush_trash = False
        self._drop_duplicates_reviewed = False

        if batch_plan is not None and coordinator is not None:
            self._pending_batch_plan = None
            self._pending_drop = []
            try:
                batch_result = coordinator.execute_batch(
                    batch_plan,
                    flush_trash=flush_trash,
                    flush_trashed_only=flush_trash,
                )
                active_items = [
                    it
                    for it in batch_plan.items
                    if not getattr(it, "is_excluded", False)
                ]
                handled_total = (
                    batch_result.moved_count
                    + batch_result.staged_count
                    + batch_result.trashed_count
                )
                succeeded_files = handled_total or (
                    len(active_items)
                    if batch_result.failed_count == 0
                    and batch_result.skipped_count == 0
                    else 0
                )
                failed_files = batch_result.failed_count
                processed_items = [
                    {
                        "path": tr.get("base_dir"),
                        "summary": tr.get("summary"),
                        "file_count": len(grp.rel_files),
                        "status": "success",
                    }
                    for grp, tr in zip(batch_plan.groups, batch_result.target_results)
                ]
                count_parts = [f"{batch_result.moved_count} moved"]
                if batch_result.staged_count > 0:
                    count_parts.append(f"{batch_result.staged_count} staged")
                if batch_result.trashed_count > 0:
                    count_parts.append(f"{batch_result.trashed_count} trashed")
                counts_detail = ", ".join(count_parts)
                from app.core.plan_format import format_trash_handoff_warning

                warn_note = format_trash_handoff_warning(batch_result.trash_handoff)
                err_note = f" {warn_note}" if warn_note else ""
                if failed_files == 0:
                    status = "success"
                    final_msg = (
                        f"Completed triage of {succeeded_files} dropped item(s) "
                        f"({counts_detail}).{err_note}"
                    )
                elif succeeded_files > 0:
                    status = "partial"
                    final_msg = (
                        f"Completed triage of {succeeded_files} item(s) "
                        f"({counts_detail}, {failed_files} failed).{err_note}"
                    )
                else:
                    status = "failed"
                    final_msg = f"Dropzone triage failed for {failed_files} item(s)."

                if app_ref:
                    app_ref.call_from_thread(self.update_status_msg, final_msg)
                    if warn_note:
                        from app.ui.notifications import notify

                        app_ref.call_from_thread(
                            lambda: notify(warn_note, type="warning")
                        )

                result_dict = {
                    "status": status,
                    "session_id": batch_result.session_id,
                    "destination_dir": batch_result.resolved_dest,
                    "processed_count": succeeded_files,
                    "moved_count": batch_result.moved_count,
                    "staged_count": batch_result.staged_count,
                    "trashed_count": batch_result.trashed_count,
                    "trash_handoff": batch_result.trash_handoff,
                    "failed_files": failed_files,
                    "items": processed_items,
                    "failed_items": [],
                    "succeeded_count": len(processed_items),
                    "failed_count": 1 if failed_files > 0 else 0,
                    "total_count": len(batch_plan.groups),
                }
                self.processed_result = result_dict
                try:
                    if app_ref:
                        app_ref.call_from_thread(self.dismiss, result_dict)
                    else:
                        self.dismiss(result_dict)
                except Exception:
                    pass
            except Exception as e:
                logger.exception(f"Error during dropzone relocation: {e}")
                coordinator.close_batch(batch_plan)
                if app_ref:
                    app_ref.call_from_thread(
                        self.update_status_msg, f"Dropzone triage error: {e}"
                    )
            return

        pending = list(getattr(self, "_pending_drop", []))
        self._pending_drop = []
        processed_items = []
        failed_items = []
        outcomes = []
        try:
            from app.core.pipeline import SortPipeline, restore_rerooted_source_dir

            for item in pending:
                try:
                    src_dir = item.get("path")
                    src_dir_was_dir = bool(src_dir and os.path.isdir(src_dir))
                    outcome = SortPipeline(item["session"]).execute(
                        item["plan"],
                        flush_trash=flush_trash,
                        flush_trashed_only=flush_trash,
                    )
                    restore_rerooted_source_dir(
                        src_dir,
                        was_dir=src_dir_was_dir,
                        re_rooted=bool(item.get("re_rooted")),
                    )
                    outcomes.append(outcome)
                    processed_items.append(
                        {
                            "path": item["path"],
                            "summary": outcome.summary,
                            "file_count": item.get("file_count", 1),
                            "status": "success",
                        }
                    )
                except Exception as e:
                    logger.exception(
                        f"Error during dropzone relocation for {item.get('path')}: {e}"
                    )
                    failed_items.append(
                        {
                            "path": item.get("path"),
                            "error": str(e),
                            "file_count": item.get("file_count", 1),
                            "status": "failed",
                        }
                    )
                finally:
                    try:
                        item["session"].close()
                    except Exception:
                        pass

            succeeded_files = sum(
                int(fc) if isinstance(fc := i.get("file_count"), (int, str)) else 0
                for i in processed_items
            )
            failed_files = sum(
                int(fc) if isinstance(fc := i.get("file_count"), (int, str)) else 0
                for i in failed_items
            )
            total_items = len(pending)

            fallback_trash_errors: dict[str, str] = {}
            for o in outcomes:
                th = (o.summary or {}).get("trash_handoff") if o.summary else None
                if isinstance(th, dict):
                    fallback_trash_errors.update(th.get("errors") or {})
            from app.core.plan_format import format_trash_handoff_warning

            fb_warn = format_trash_handoff_warning({"errors": fallback_trash_errors})
            fb_err_note = f" {fb_warn}" if fb_warn else ""

            if not failed_items:
                status = "success"
                final_msg = (
                    f"Completed triage of {succeeded_files} dropped item(s): "
                    + " ".join(o.describe() for o in outcomes)
                    + fb_err_note
                )
            elif processed_items:
                status = "partial"
                err_summary = "; ".join(
                    f"{item['path']}: {item['error']}" for item in failed_items
                )
                descriptions = " ".join(o.describe() for o in outcomes)
                final_msg = (
                    f"Completed triage of {succeeded_files} item(s) "
                    f"({len(processed_items)} succeeded, {len(failed_items)} failed): "
                    f"{descriptions} Errors: {err_summary}{fb_err_note}"
                )
            else:
                status = "failed"
                err_summary = "; ".join(
                    f"{item['path']}: {item['error']}" for item in failed_items
                )
                final_msg = f"Dropzone triage failed for all {len(failed_items)} item(s): {err_summary}"

            if app_ref:
                app_ref.call_from_thread(self.update_status_msg, final_msg)
                if fb_warn:
                    from app.ui.notifications import notify

                    app_ref.call_from_thread(lambda: notify(fb_warn, type="warning"))

            result_dict = {
                "status": status,
                "processed_count": succeeded_files,
                "failed_files": failed_files,
                "items": processed_items,
                "failed_items": failed_items,
                "succeeded_count": len(processed_items),
                "failed_count": len(failed_items),
                "total_count": total_items,
            }
            self.processed_result = result_dict
            try:
                if app_ref:
                    app_ref.call_from_thread(self.dismiss, result_dict)
                else:
                    self.dismiss(result_dict)
            except Exception:
                pass
        except Exception as e:
            logger.exception(f"Error during dropzone relocation: {e}")
            for item in pending:
                try:
                    item["session"].close()
                except Exception:
                    pass
            if app_ref:
                app_ref.call_from_thread(
                    self.update_status_msg, f"Dropzone triage error: {e}"
                )

action_cancel()

Dismiss dropzone modal.

Source code in app/ui/modals/drop_zone.py
1394
1395
1396
1397
1398
1399
@on(Button.Pressed, "#btn-cancel")
def action_cancel(self) -> None:
    """Dismiss dropzone modal."""
    self._close_pending_drop()
    self.announce("Cancelled dropzone modal dialog.")
    self.dismiss(None)

clear_queue()

Clear all staged items from modal queue.

Source code in app/ui/modals/drop_zone.py
1265
1266
1267
1268
1269
def clear_queue(self) -> None:
    """Clear all staged items from modal queue."""
    self.staged_items.clear()
    self._refresh_table()
    self.update_status_msg("Cleared all staged items from the queue.")

compose()

Compose floating dropzone modal overlay controls.

Source code in app/ui/modals/drop_zone.py
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
def compose(self) -> ComposeResult:
    """Compose floating dropzone modal overlay controls."""
    with ModalBox(classes="modal-box"):
        yield Heading(
            "Floating DropZone - Quick File Triage",
            level=1,
            classes="modal-title",
            id="modal-title",
        )
        with Vertical(classes="modal-body"):
            with Vertical(classes="dropzone-target"):
                yield Label(
                    "📥 Drop or Paste File / Folder Paths Here",
                    classes="dropzone-instructions",
                )
                yield Label(
                    "Drag items onto terminal or paste absolute file paths to organize automatically",
                    classes="dropzone-subinstructions",
                )
            inp = Input(
                placeholder="Paste or drop file / directory paths here...",
                id="input-drop-paths",
            )
            inp.tooltip = "Enter or drop target file or folder paths to trigger automated sorting"
            yield inp

            with Horizontal(classes="dest-row"):
                dest_inp = Input(
                    value=self.initial_dest_dir or "",
                    placeholder="Destination folder (optional, leave blank to sort in place)...",
                    id="input-dest-dir",
                )
                dest_inp.tooltip = (
                    "Destination directory where sorted files will be placed "
                    "(leave empty to sort each item inside its own folder)"
                )
                yield dest_inp

                btn_browse = Button(
                    "Browse", id="btn-browse-dest", variant="default"
                )
                btn_browse.tooltip = (
                    "Browse for a destination directory using native folder dialog"
                )
                yield btn_browse

            filter_inp = Input(
                placeholder="Filter staged queue...",
                id="input-queue-filter",
            )
            filter_inp.tooltip = "Filter staged queue items by typing keywords (filename, path, status, extension)"
            yield filter_inp

            with Container(classes="dropzone-split-container"):
                table = DataTable(id="dropzone-staging-table")
                table.cursor_type = "row"
                table.tooltip = (
                    "Interactive staging queue displaying file status and details"
                )
                yield table

                with Vertical(id="dropzone-metadata-preview"):
                    yield Label("📋 Metadata Preview", classes="preview-header")
                    yield Label(
                        "Path: N/A", id="preview-path", classes="preview-field"
                    )
                    yield Label(
                        "Size: N/A", id="preview-size", classes="preview-field"
                    )
                    yield Label(
                        "Modified: N/A", id="preview-mtime", classes="preview-field"
                    )
                    yield Label(
                        "Status: N/A", id="preview-status", classes="preview-field"
                    )

            with Horizontal(classes="queue-row"):
                btn_filter = Button(
                    "Filter Unsupported",
                    id="btn-filter-unsupported",
                    variant="warning",
                )
                btn_filter.tooltip = (
                    "Remove unsupported file formats from the queue"
                )
                yield btn_filter

                btn_remove = Button(
                    "Remove Item", id="btn-remove-item", variant="error"
                )
                btn_remove.tooltip = (
                    "Remove the selected row from the staging table"
                )
                yield btn_remove

                btn_up = Button("Move Up", id="btn-move-up", variant="default")
                btn_up.tooltip = "Move selected item up in queue priority"
                yield btn_up

                btn_down = Button(
                    "Move Down", id="btn-move-down", variant="default"
                )
                btn_down.tooltip = "Move selected item down in queue priority"
                yield btn_down

                btn_clear = Button(
                    "Clear Queue", id="btn-clear-queue", variant="default"
                )
                btn_clear.tooltip = "Clear all staged items from the modal"
                yield btn_clear

            status_lbl = Label(
                "Ready. Drop or enter paths above.",
                id="dropzone-status",
                classes="status-text",
            )
            status_lbl.tooltip = (
                "Live visual progress indicators and classification status messages"
            )
            yield status_lbl

        with Horizontal(classes="button-row"):
            btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
            btn_cancel.tooltip = "Cancel dropzone triage operation and close dialog"
            yield btn_cancel

            btn_help = Button(
                "Help", id="btn-help", variant="warning", classes="hidden"
            )
            btn_help.tooltip = (
                "Open troubleshooting documentation for dropzone errors"
            )
            yield btn_help

            btn_process = Button("Sort Items", id="btn-process", variant="primary")
            btn_process.tooltip = (
                "Start automated classification and relocation on dropped paths"
            )
            yield btn_process

filter_unsupported_items()

Remove items with 'Unsupported' status from the queue.

Source code in app/ui/modals/drop_zone.py
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
def filter_unsupported_items(self) -> None:
    """Remove items with 'Unsupported' status from the queue."""
    before = len(self.staged_items)
    self.staged_items = [
        item for item in self.staged_items if item["status"] != "Unsupported"
    ]
    removed = before - len(self.staged_items)
    self._refresh_table()
    msg = f"Filtered {removed} unsupported item(s) from queue. {len(self.staged_items)} item(s) remaining."
    self.update_status_msg(msg)

get_filter_query()

Get lowercase trimmed search query from input-queue-filter field.

Source code in app/ui/modals/drop_zone.py
786
787
788
789
790
791
792
def get_filter_query(self) -> str:
    """Get lowercase trimmed search query from input-queue-filter field."""
    try:
        inp = self.query_one("#input-queue-filter", Input)
        return inp.value.strip().lower()
    except Exception:
        return ""

get_filtered_items()

Return list of staged items filtered by search query.

Source code in app/ui/modals/drop_zone.py
794
795
796
797
798
799
800
801
802
803
804
805
806
def get_filtered_items(self) -> list[dict[str, Any]]:
    """Return list of staged items filtered by search query."""
    query = self.get_filter_query()
    if not query:
        return list(self.staged_items)
    return [
        item
        for item in self.staged_items
        if query in item["filename"].lower()
        or query in item["path"].lower()
        or query in item["extension"].lower()
        or query in item["status"].lower()
    ]

move_selected_item_down()

Move selected queue item down in priority.

Source code in app/ui/modals/drop_zone.py
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
def move_selected_item_down(self) -> None:
    """Move selected queue item down in priority."""
    try:
        table = self.query_one("#dropzone-staging-table", DataTable)
        row_idx = table.cursor_row
    except Exception:
        row_idx = None

    filtered = self.get_filtered_items()
    if row_idx is not None and 0 <= row_idx < len(filtered) - 1:
        item_curr = filtered[row_idx]
        item_next = filtered[row_idx + 1]
        idx_curr = self.staged_items.index(item_curr)
        idx_next = self.staged_items.index(item_next)
        self.staged_items[idx_curr], self.staged_items[idx_next] = (
            self.staged_items[idx_next],
            self.staged_items[idx_curr],
        )
        self._refresh_table()
        try:
            table.move_cursor(row=row_idx + 1)
        except Exception:
            pass
        self.update_active_metadata_preview()
        self.update_status_msg(
            f"Moved '{item_curr['filename']}' down in queue priority."
        )

move_selected_item_up()

Move selected queue item up in priority.

Source code in app/ui/modals/drop_zone.py
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
def move_selected_item_up(self) -> None:
    """Move selected queue item up in priority."""
    try:
        table = self.query_one("#dropzone-staging-table", DataTable)
        row_idx = table.cursor_row
    except Exception:
        row_idx = None

    filtered = self.get_filtered_items()
    if row_idx is not None and 0 < row_idx < len(filtered):
        item_curr = filtered[row_idx]
        item_prev = filtered[row_idx - 1]
        idx_curr = self.staged_items.index(item_curr)
        idx_prev = self.staged_items.index(item_prev)
        self.staged_items[idx_curr], self.staged_items[idx_prev] = (
            self.staged_items[idx_prev],
            self.staged_items[idx_curr],
        )
        self._refresh_table()
        try:
            table.move_cursor(row=row_idx - 1)
        except Exception:
            pass
        self.update_active_metadata_preview()
        self.update_status_msg(
            f"Moved '{item_curr['filename']}' up in queue priority."
        )

on_btn_browse_dest_pressed(event)

Open native directory picker to populate the destination folder input.

Source code in app/ui/modals/drop_zone.py
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
@on(Button.Pressed, "#btn-browse-dest")
def on_btn_browse_dest_pressed(self, event: Button.Pressed) -> None:
    """Open native directory picker to populate the destination folder input."""
    curr_val = ""
    try:
        curr_val = self.query_one("#input-dest-dir", Input).value.strip()
    except Exception:
        pass
    initial_dir = curr_val or self.base_dir
    self._browse_dest_worker(initial_dir)

on_btn_clear_pressed(event)

Clear queue button handler.

Source code in app/ui/modals/drop_zone.py
1384
1385
1386
1387
@on(Button.Pressed, "#btn-clear-queue")
def on_btn_clear_pressed(self, event: Button.Pressed) -> None:
    """Clear queue button handler."""
    self.clear_queue()

on_btn_filter_unsupported_pressed(event)

Filter unsupported file formats button handler.

Source code in app/ui/modals/drop_zone.py
1364
1365
1366
1367
@on(Button.Pressed, "#btn-filter-unsupported")
def on_btn_filter_unsupported_pressed(self, event: Button.Pressed) -> None:
    """Filter unsupported file formats button handler."""
    self.filter_unsupported_items()

on_btn_move_down_pressed(event)

Move item down button handler.

Source code in app/ui/modals/drop_zone.py
1379
1380
1381
1382
@on(Button.Pressed, "#btn-move-down")
def on_btn_move_down_pressed(self, event: Button.Pressed) -> None:
    """Move item down button handler."""
    self.move_selected_item_down()

on_btn_move_up_pressed(event)

Move item up button handler.

Source code in app/ui/modals/drop_zone.py
1374
1375
1376
1377
@on(Button.Pressed, "#btn-move-up")
def on_btn_move_up_pressed(self, event: Button.Pressed) -> None:
    """Move item up button handler."""
    self.move_selected_item_up()

on_btn_process_pressed(event)

Handle Sort Items button press.

Source code in app/ui/modals/drop_zone.py
1389
1390
1391
1392
@on(Button.Pressed, "#btn-process")
def on_btn_process_pressed(self, event: Button.Pressed) -> None:
    """Handle Sort Items button press."""
    self.trigger_drop_triage()

on_btn_remove_pressed(event)

Remove selected item button handler.

Source code in app/ui/modals/drop_zone.py
1369
1370
1371
1372
@on(Button.Pressed, "#btn-remove-item")
def on_btn_remove_pressed(self, event: Button.Pressed) -> None:
    """Remove selected item button handler."""
    self.remove_selected_item()

on_input_submitted(event)

Handle enter key in drop paths input field to stage items or process queue.

Source code in app/ui/modals/drop_zone.py
1358
1359
1360
1361
1362
@on(Input.Submitted, "#input-drop-paths")
def on_input_submitted(self, event: Input.Submitted) -> None:
    """Handle enter key in drop paths input field to stage items or process queue."""
    if event.value.strip():
        self.stage_paths(event.value)

on_mount()

Focus input on mount, stage initial paths if any, and announce modal opening.

Source code in app/ui/modals/drop_zone.py
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
def on_mount(self) -> None:
    """Focus input on mount, stage initial paths if any, and announce modal opening."""
    self._app_ref = self.app
    super().on_mount()
    self._refresh_table()
    try:
        self.query_one("#input-drop-paths", Input).focus()
    except Exception:
        pass
    self.announce("Opened floating dropzone overlay for quick file triage.")
    if self.initial_paths:
        self.stage_paths("\n".join(str(p) for p in self.initial_paths))

on_paste(event)

Handle clipboard paste event for dropped path payloads.

Source code in app/ui/modals/drop_zone.py
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
def on_paste(self, event: events.Paste) -> None:
    """Handle clipboard paste event for dropped path payloads."""
    focused = getattr(self, "focused", None)
    if focused is not None and getattr(focused, "id", None) in (
        "input-dest-dir",
        "input-queue-filter",
    ):
        return
    if event.text:
        event.stop()
        try:
            inp = self.query_one("#input-drop-paths", Input)
            inp.value = event.text.strip()
        except Exception:
            pass
        self.stage_paths(event.text)

on_queue_filter_changed(event)

Handle search filter text changes to dynamically update visible table rows.

Source code in app/ui/modals/drop_zone.py
870
871
872
873
@on(Input.Changed, "#input-queue-filter")
def on_queue_filter_changed(self, event: Input.Changed) -> None:
    """Handle search filter text changes to dynamically update visible table rows."""
    self._refresh_table()

remove_selected_item()

Remove currently selected row from the staging table.

Source code in app/ui/modals/drop_zone.py
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
def remove_selected_item(self) -> None:
    """Remove currently selected row from the staging table."""
    try:
        table = self.query_one("#dropzone-staging-table", DataTable)
        row_idx = table.cursor_row
    except Exception:
        row_idx = None

    filtered = self.get_filtered_items()
    if row_idx is not None and 0 <= row_idx < len(filtered):
        removed_item = filtered[row_idx]
        if removed_item in self.staged_items:
            self.staged_items.remove(removed_item)
        self._refresh_table()
        msg = f"Removed '{removed_item['filename']}' from queue. {len(self.staged_items)} item(s) remaining."
        self.update_status_msg(msg)
        new_filtered = self.get_filtered_items()
        if new_filtered:
            new_idx = min(row_idx, len(new_filtered) - 1)
            try:
                table.move_cursor(row=new_idx)
            except Exception:
                pass
        self.update_active_metadata_preview()
    else:
        self.update_status_msg("No item selected to remove.")

run_drop_execute_worker()

Execute the confirmed drop batch under one undo session in a worker thread.

Source code in app/ui/modals/drop_zone.py
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
@work(exclusive=True, thread=True)
def run_drop_execute_worker(self) -> None:
    """Execute the confirmed drop batch under one undo session in a worker thread."""
    app_ref = getattr(self, "_app_ref", None)
    batch_plan = getattr(self, "_pending_batch_plan", None)
    coordinator = getattr(self, "_coordinator", None)
    flush_trash = bool(getattr(self, "_pending_drop_flush_trash", False))
    self._pending_drop_flush_trash = False
    self._drop_duplicates_reviewed = False

    if batch_plan is not None and coordinator is not None:
        self._pending_batch_plan = None
        self._pending_drop = []
        try:
            batch_result = coordinator.execute_batch(
                batch_plan,
                flush_trash=flush_trash,
                flush_trashed_only=flush_trash,
            )
            active_items = [
                it
                for it in batch_plan.items
                if not getattr(it, "is_excluded", False)
            ]
            handled_total = (
                batch_result.moved_count
                + batch_result.staged_count
                + batch_result.trashed_count
            )
            succeeded_files = handled_total or (
                len(active_items)
                if batch_result.failed_count == 0
                and batch_result.skipped_count == 0
                else 0
            )
            failed_files = batch_result.failed_count
            processed_items = [
                {
                    "path": tr.get("base_dir"),
                    "summary": tr.get("summary"),
                    "file_count": len(grp.rel_files),
                    "status": "success",
                }
                for grp, tr in zip(batch_plan.groups, batch_result.target_results)
            ]
            count_parts = [f"{batch_result.moved_count} moved"]
            if batch_result.staged_count > 0:
                count_parts.append(f"{batch_result.staged_count} staged")
            if batch_result.trashed_count > 0:
                count_parts.append(f"{batch_result.trashed_count} trashed")
            counts_detail = ", ".join(count_parts)
            from app.core.plan_format import format_trash_handoff_warning

            warn_note = format_trash_handoff_warning(batch_result.trash_handoff)
            err_note = f" {warn_note}" if warn_note else ""
            if failed_files == 0:
                status = "success"
                final_msg = (
                    f"Completed triage of {succeeded_files} dropped item(s) "
                    f"({counts_detail}).{err_note}"
                )
            elif succeeded_files > 0:
                status = "partial"
                final_msg = (
                    f"Completed triage of {succeeded_files} item(s) "
                    f"({counts_detail}, {failed_files} failed).{err_note}"
                )
            else:
                status = "failed"
                final_msg = f"Dropzone triage failed for {failed_files} item(s)."

            if app_ref:
                app_ref.call_from_thread(self.update_status_msg, final_msg)
                if warn_note:
                    from app.ui.notifications import notify

                    app_ref.call_from_thread(
                        lambda: notify(warn_note, type="warning")
                    )

            result_dict = {
                "status": status,
                "session_id": batch_result.session_id,
                "destination_dir": batch_result.resolved_dest,
                "processed_count": succeeded_files,
                "moved_count": batch_result.moved_count,
                "staged_count": batch_result.staged_count,
                "trashed_count": batch_result.trashed_count,
                "trash_handoff": batch_result.trash_handoff,
                "failed_files": failed_files,
                "items": processed_items,
                "failed_items": [],
                "succeeded_count": len(processed_items),
                "failed_count": 1 if failed_files > 0 else 0,
                "total_count": len(batch_plan.groups),
            }
            self.processed_result = result_dict
            try:
                if app_ref:
                    app_ref.call_from_thread(self.dismiss, result_dict)
                else:
                    self.dismiss(result_dict)
            except Exception:
                pass
        except Exception as e:
            logger.exception(f"Error during dropzone relocation: {e}")
            coordinator.close_batch(batch_plan)
            if app_ref:
                app_ref.call_from_thread(
                    self.update_status_msg, f"Dropzone triage error: {e}"
                )
        return

    pending = list(getattr(self, "_pending_drop", []))
    self._pending_drop = []
    processed_items = []
    failed_items = []
    outcomes = []
    try:
        from app.core.pipeline import SortPipeline, restore_rerooted_source_dir

        for item in pending:
            try:
                src_dir = item.get("path")
                src_dir_was_dir = bool(src_dir and os.path.isdir(src_dir))
                outcome = SortPipeline(item["session"]).execute(
                    item["plan"],
                    flush_trash=flush_trash,
                    flush_trashed_only=flush_trash,
                )
                restore_rerooted_source_dir(
                    src_dir,
                    was_dir=src_dir_was_dir,
                    re_rooted=bool(item.get("re_rooted")),
                )
                outcomes.append(outcome)
                processed_items.append(
                    {
                        "path": item["path"],
                        "summary": outcome.summary,
                        "file_count": item.get("file_count", 1),
                        "status": "success",
                    }
                )
            except Exception as e:
                logger.exception(
                    f"Error during dropzone relocation for {item.get('path')}: {e}"
                )
                failed_items.append(
                    {
                        "path": item.get("path"),
                        "error": str(e),
                        "file_count": item.get("file_count", 1),
                        "status": "failed",
                    }
                )
            finally:
                try:
                    item["session"].close()
                except Exception:
                    pass

        succeeded_files = sum(
            int(fc) if isinstance(fc := i.get("file_count"), (int, str)) else 0
            for i in processed_items
        )
        failed_files = sum(
            int(fc) if isinstance(fc := i.get("file_count"), (int, str)) else 0
            for i in failed_items
        )
        total_items = len(pending)

        fallback_trash_errors: dict[str, str] = {}
        for o in outcomes:
            th = (o.summary or {}).get("trash_handoff") if o.summary else None
            if isinstance(th, dict):
                fallback_trash_errors.update(th.get("errors") or {})
        from app.core.plan_format import format_trash_handoff_warning

        fb_warn = format_trash_handoff_warning({"errors": fallback_trash_errors})
        fb_err_note = f" {fb_warn}" if fb_warn else ""

        if not failed_items:
            status = "success"
            final_msg = (
                f"Completed triage of {succeeded_files} dropped item(s): "
                + " ".join(o.describe() for o in outcomes)
                + fb_err_note
            )
        elif processed_items:
            status = "partial"
            err_summary = "; ".join(
                f"{item['path']}: {item['error']}" for item in failed_items
            )
            descriptions = " ".join(o.describe() for o in outcomes)
            final_msg = (
                f"Completed triage of {succeeded_files} item(s) "
                f"({len(processed_items)} succeeded, {len(failed_items)} failed): "
                f"{descriptions} Errors: {err_summary}{fb_err_note}"
            )
        else:
            status = "failed"
            err_summary = "; ".join(
                f"{item['path']}: {item['error']}" for item in failed_items
            )
            final_msg = f"Dropzone triage failed for all {len(failed_items)} item(s): {err_summary}"

        if app_ref:
            app_ref.call_from_thread(self.update_status_msg, final_msg)
            if fb_warn:
                from app.ui.notifications import notify

                app_ref.call_from_thread(lambda: notify(fb_warn, type="warning"))

        result_dict = {
            "status": status,
            "processed_count": succeeded_files,
            "failed_files": failed_files,
            "items": processed_items,
            "failed_items": failed_items,
            "succeeded_count": len(processed_items),
            "failed_count": len(failed_items),
            "total_count": total_items,
        }
        self.processed_result = result_dict
        try:
            if app_ref:
                app_ref.call_from_thread(self.dismiss, result_dict)
            else:
                self.dismiss(result_dict)
        except Exception:
            pass
    except Exception as e:
        logger.exception(f"Error during dropzone relocation: {e}")
        for item in pending:
            try:
                item["session"].close()
            except Exception:
                pass
        if app_ref:
            app_ref.call_from_thread(
                self.update_status_msg, f"Dropzone triage error: {e}"
            )

run_drop_worker(target_paths, dest_dir=None)

Plan the dropped items via DropBatchCoordinator in a worker thread, then ask before moving.

Source code in app/ui/modals/drop_zone.py
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
@work(exclusive=True, thread=True)
def run_drop_worker(
    self, target_paths: list[str], dest_dir: str | None = None
) -> None:
    """Plan the dropped items via DropBatchCoordinator in a worker thread, then ask before moving."""
    app_ref = getattr(self, "_app_ref", None)
    self._close_pending_drop()
    try:
        from app.core.pipeline import DropBatchCoordinator

        staged_roots = {
            item["path"]: item.get("group_root")
            for item in list(self.staged_items)
            if isinstance(item, dict) and "path" in item
        }
        coordinator = DropBatchCoordinator(self.settings)

        def _on_plan_progress(info: Any) -> None:
            if app_ref is None:
                return
            stage = (
                info.get("stage") if isinstance(info, dict) else None
            ) or "Classifying dropped items..."
            app_ref.call_from_thread(self.update_status_msg, str(stage))

        batch_plan = coordinator.plan_batch(
            target_paths,
            dest_dir=dest_dir,
            staged_roots=staged_roots,
            progress_callback=_on_plan_progress if app_ref else None,
        )
        self._coordinator = coordinator
        self._pending_batch_plan = batch_plan
        self._pending_drop = [
            {
                "path": grp.source_root,
                "session": grp.session,
                "plan": grp.plan,
                "file_count": len(grp.rel_files),
                "re_rooted": grp.re_rooted,
            }
            for grp in batch_plan.groups
        ]
        if app_ref:
            app_ref.call_from_thread(self._confirm_pending_drop)
        else:
            self._confirm_pending_drop()
    except Exception as e:
        logger.exception(f"Error during dropzone classification: {e}")
        self._close_pending_drop()
        if app_ref:
            app_ref.call_from_thread(
                self.update_status_msg, f"Dropzone triage error: {e}"
            )

stage_paths(raw_text)

Parse raw input string, validate dropped paths before expansion, and stage items.

Source code in app/ui/modals/drop_zone.py
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
def stage_paths(self, raw_text: str) -> None:
    """Parse raw input string, validate dropped paths before expansion, and stage items."""
    raw_items = self._parse_raw_drop_input(raw_text)
    if not raw_items:
        return

    from app.core.mover import is_subpath_or_equal
    from app.core.pipeline import (
        drop_scope,
        expand_drop_scope_files,
        validate_drop_paths,
    )

    protected = (
        getattr(self.settings, "PROTECTED_PATHS", []) if self.settings else []
    )
    new_count = 0

    for item in raw_items:
        abs_p = os.path.abspath(item)
        _, issues = validate_drop_paths([abs_p], settings=self.settings)
        issue = issues[0] if issues else None
        is_prot = (issue is not None and issue.reason == "protected") or any(
            prot and is_subpath_or_equal(abs_p, prot) for prot in (protected or ())
        )

        if is_prot or issue is not None:
            self._stage_rejected_item(abs_p, issue=issue, is_protected=is_prot)
            new_count += 1
            continue

        scope_dir, scope_files = drop_scope(abs_p)
        if scope_files is None:
            _, files = expand_drop_scope_files(abs_p, settings=self.settings)
            for f_path in files:
                self._add_single_file_to_staging(
                    os.path.join(scope_dir, f_path), protected, root_dir=scope_dir
                )
                new_count += 1
        else:
            self._add_single_file_to_staging(abs_p, protected)
            new_count += 1

    self._refresh_table()
    try:
        inp = self.query_one("#input-drop-paths", Input)
        inp.value = ""
    except Exception:
        pass

    ready_cnt = sum(1 for item in self.staged_items if item["status"] == "Ready")
    msg = f"Staged {new_count} item(s). Queue total: {len(self.staged_items)} ({ready_cnt} ready)."
    self.update_status_msg(msg)

trigger_drop_triage()

Parse input paths if any, validate active queue, and trigger worker.

Source code in app/ui/modals/drop_zone.py
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
def trigger_drop_triage(self) -> None:
    """Parse input paths if any, validate active queue, and trigger worker."""
    try:
        inp = self.query_one("#input-drop-paths", Input)
        raw_text = inp.value.strip()
    except Exception:
        raw_text = ""

    if raw_text:
        self.stage_paths(raw_text)

    help_url = f"{TROUBLESHOOTING_URL}#dropzone-errors"

    raw_dest: str | None = None
    try:
        dest_inp = self.query_one("#input-dest-dir", Input)
        raw_dest = dest_inp.value.strip()
    except Exception:
        raw_dest = (self.initial_dest_dir or "").strip()

    resolved_dest: str | None = None
    if raw_dest:
        from app.core.pipeline import validate_drop_destination
        from app.ui.notifications import notify

        decoded_dest = self._decode_path_token(raw_dest)
        resolved_dest, dest_err = validate_drop_destination(
            decoded_dest, settings=self.settings
        )
        if dest_err in ("protected", "not_directory"):
            err_text = (
                f"Protected destination blocked: {resolved_dest}"
                if dest_err == "protected"
                else f"Destination path is not a folder: {resolved_dest}"
            )
            self._show_help_button(help_url)
            notify(f"DropZone error: {err_text}", type="error", help_url=help_url)
            self.update_status_msg(err_text, help_url=help_url)
            return

    filtered = self.get_filtered_items()
    ready_paths = [item["path"] for item in filtered if item["status"] == "Ready"]

    if not ready_paths:
        blocked_items = [
            item for item in filtered if item["status"] == "BLOCKED"
        ] or [item for item in self.staged_items if item["status"] == "BLOCKED"]
        status_err_detail: str | None = None
        if blocked_items:
            first_blk = blocked_items[0]
            blk_reason = first_blk.get("block_reason")
            if blk_reason == "app_bundle":
                err_text = f"Application bundle blocked: {first_blk['filename']}"
                status_err_detail = (
                    f"Application bundle blocked: {first_blk['path']}"
                )
            elif blk_reason == "quarantine":
                err_text = f"Quarantine folder blocked: {first_blk['filename']}"
                status_err_detail = (
                    f"Quarantine folder blocked: {first_blk['path']}"
                )
            else:
                err_text = f"Protected path blocked: {first_blk['filename']}"
                status_err_detail = f"Protected path blocked: {first_blk['path']}"
        elif self.staged_items:
            err_text = "No ready files to sort in queue."
        else:
            err_text = "No file or folder paths provided."

        self._show_help_button(help_url)
        from app.ui.notifications import notify

        notify(f"DropZone error: {err_text}", type="error", help_url=help_url)
        self.update_status_msg(
            status_err_detail if status_err_detail else f"Error: {err_text}",
            help_url=help_url,
        )
        return

    self.update_status_msg(f"Processing {len(ready_paths)} dropped item(s)...")
    self.run_drop_worker(ready_paths, dest_dir=resolved_dest)

update_active_metadata_preview()

Fetch item corresponding to current table cursor row and update metadata preview.

Source code in app/ui/modals/drop_zone.py
857
858
859
860
861
862
863
864
865
866
867
868
def update_active_metadata_preview(self) -> None:
    """Fetch item corresponding to current table cursor row and update metadata preview."""
    try:
        table = self.query_one("#dropzone-staging-table", DataTable)
        row_idx = table.cursor_row
        filtered = self.get_filtered_items()
        if row_idx is not None and 0 <= row_idx < len(filtered):
            self.update_metadata_preview(filtered[row_idx])
        else:
            self.update_metadata_preview(None)
    except Exception:
        self.update_metadata_preview(None)

update_metadata_preview(item=None)

Update metadata preview card panel for given staged item.

Source code in app/ui/modals/drop_zone.py
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
def update_metadata_preview(self, item: dict[str, Any] | None = None) -> None:
    """Update metadata preview card panel for given staged item."""
    if item is None:
        path_str = "N/A"
        size_str = "N/A"
        mtime_str = "N/A"
        status_str = "N/A"
    else:
        path_str = item.get("path", "N/A")
        size_str = item.get("size_str", "N/A")
        status_str = item.get("status", "N/A")
        if path_str and path_str != "N/A" and os.path.exists(path_str):
            try:
                mtime = os.path.getmtime(path_str)
                mtime_str = datetime.fromtimestamp(mtime).strftime(
                    "%Y-%m-%d %H:%M:%S"
                )
            except Exception:
                mtime_str = "Error reading timestamp"
        else:
            mtime_str = "N/A"

    try:
        self.query_one("#preview-path", Label).update(f"Path: {path_str}")
        self.query_one("#preview-size", Label).update(f"Size: {size_str}")
        self.query_one("#preview-mtime", Label).update(f"Modified: {mtime_str}")
        self.query_one("#preview-status", Label).update(f"Status: {status_str}")
    except Exception:
        pass

update_status_msg(msg, help_url=None)

Update live status message region and screen reader announcement.

Source code in app/ui/modals/drop_zone.py
1483
1484
1485
1486
1487
1488
1489
1490
1491
def update_status_msg(self, msg: str, help_url: str | None = None) -> None:
    """Update live status message region and screen reader announcement."""
    display_msg = f"{msg} [Help: {help_url}]" if help_url else msg
    try:
        lbl = self.query_one("#dropzone-status", Label)
        lbl.update(display_msg)
    except Exception:
        pass
    self.announce(msg, help_url=help_url)

app.ui.modals.edit

app.ui.modals.edit

Dialogs for editing the plan tree: rename, new folder, reassign, directory pickers and duplicate review.

DirectorySelectModal

Bases: _SubmittableModalMixin, ResponsiveModalScreen[str | list[str] | None]

Modal dialog for choosing target base directory or presets.

Source code in app/ui/modals/edit.py
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
class DirectorySelectModal(
    _SubmittableModalMixin,
    ResponsiveModalScreen[str | list[str] | None],
):
    """Modal dialog for choosing target base directory or presets."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .error-banner {
        color: $error;
        text-style: bold;
    }
    .preset-row {
        width: 100%;
        layout: grid;
        grid-size: 3;
        grid-gutter: 0 1;
        margin-top: 1;
        margin-bottom: 1;
        height: auto;
        min-height: 3;
    }
    .preset-row Button {
        width: 100%;
        min-width: 0;
    }
    .sources-list {
        margin-top: 1;
        margin-bottom: 1;
        color: $text;
        border: solid $primary;
        padding: 0 1;
    }
    .sources-rows-container {
        width: 100%;
        height: auto;
        margin-top: 1;
        margin-bottom: 1;
        border: solid $primary;
        padding: 0 1;
    }
    .source-item-row {
        width: 100%;
        height: auto;
        min-height: 1;
        align-vertical: middle;
    }
    .source-item-path {
        width: 1fr;
        height: auto;
        content-align: left middle;
    }
    .btn-remove-source {
        width: auto;
        min-width: 10;
        height: 1;
        min-height: 1;
        border: none;
        margin-left: 1;
    }
    .source-actions-row {
        width: 100%;
        layout: grid;
        grid-size: 2;
        grid-gutter: 0 1;
        margin-bottom: 1;
        height: auto;
        min-height: 3;
    }
    .source-actions-row Button {
        width: 100%;
        min-width: 0;
    }
    .button-row {
        layout: grid;
        grid-size: 3;
        grid-gutter: 0 1;
        min-height: 3;
    }
    .button-row Button {
        width: 100%;
        min-width: 0;
    }
    Button:focus, Input:focus {
        border: heavy $accent;
        text-style: bold;
    }
    .btn-remove-source:focus {
        height: 1;
        min-height: 1;
        border: none;
        background: $accent;
        color: $text;
        text-style: bold reverse;
    }
    DirectorySelectModal {
        &.compact .preset-row {
            margin-top: 0;
            margin-bottom: 0;
            min-height: 1;
        }
        &.compact .preset-row Button,
        &.compact .source-actions-row Button {
            height: 1;
            min-height: 1;
            border: none;
        }
        &.compact .sources-list,
        &.compact .sources-rows-container {
            margin-top: 0;
            margin-bottom: 0;
        }
        &.compact .source-actions-row {
            margin-bottom: 0;
            min-height: 1;
        }
        &.compact .button-row {
            grid-size: 3;
        }
        &.narrow .preset-row {
            grid-size: 2;
        }
        &.narrow .button-row {
            grid-size: 2;
        }
    }
    """

    def __init__(
        self,
        current_dir: str = "",
        source_dirs: list[str] | None = None,
        settings: Any = None,
    ):
        super().__init__()
        self.current_dir = current_dir
        self.settings = settings
        self._source_row_seq: int = 0
        self._configured_scopes: list[str] = (
            sorted((getattr(settings, "FOLDER_RULE_SCOPES", {}) or {}).keys())
            if settings is not None
            else []
        )
        if source_dirs:
            self.selected_sources: list[str] = []
            for raw_dir in source_dirs:
                if raw_dir:
                    norm_dir = os.path.abspath(os.path.expanduser(str(raw_dir)))
                    if norm_dir not in self.selected_sources:
                        self.selected_sources.append(norm_dir)
        elif current_dir:
            self.selected_sources = [
                os.path.abspath(os.path.expanduser(str(current_dir)))
            ]
        else:
            self.selected_sources = []

    @staticmethod
    def _validate_directory_path(path_str: str, settings: Any = None) -> str | None:
        """Validate existence, directory type, read access, and ScanFilter safety guards.

        Returns error message string if invalid, or None if valid.
        """
        if not path_str or not path_str.strip():
            return "Directory path cannot be empty."

        clean_path = path_str.strip()
        expanded = os.path.abspath(os.path.expanduser(clean_path))

        try:
            if not os.path.exists(expanded):
                return f"Target directory does not exist: {clean_path}"

            if not os.path.isdir(expanded):
                return f"Path is not a directory: {clean_path}"

            if not os.access(expanded, os.R_OK):
                return f"Permission denied for directory: {clean_path}"
        except Exception as exc:
            return f"Invalid directory path: {exc}"

        from app.config import AppSettings
        from app.core.scanner import ScanFilter

        eff_settings = (
            settings
            if settings is not None
            else getattr(AppSettings, "_instance", None)
        )
        parent_dir = os.path.dirname(expanded) or expanded
        scan_filter = ScanFilter.from_settings(
            settings=eff_settings,
            base_dir=parent_dir,
        )
        if scan_filter.is_quarantine(expanded, base_dir=parent_dir):
            return (
                f"Protected path cannot be scanned: {clean_path} "
                "(quarantine directory excluded by safety policy)"
            )
        if scan_filter.is_app_bundle(expanded, base_dir=parent_dir):
            return (
                f"Protected path cannot be scanned: {clean_path} "
                "(.app bundle excluded by safety policy)"
            )
        if scan_filter.is_protected(expanded, base_dir=parent_dir):
            return (
                f"Protected path cannot be scanned: {clean_path} "
                "(excluded by PROTECTED_PATHS safety policy)"
            )

        return None

    def _show_error(self, message: str) -> None:
        """Display inline error banner, announce message, and focus input."""
        try:
            lbl = self.query_one("#lbl-error", Static)
            lbl.update(message)
        except Exception:
            pass
        self.announce(message, priority="assertive")
        try:
            self.query_one("#input-dir", Input).focus()
        except Exception:
            pass

    @on(Input.Changed, "#input-dir")
    def on_input_changed(self, event: Input.Changed) -> None:
        """Clear error banner when user changes input text."""
        try:
            lbl = self.query_one("#lbl-error", Static)
            lbl.update("")
        except Exception:
            pass

    def _format_sources_heading(self) -> str:
        count = len(self.selected_sources)
        if count == 0:
            return "Selected Sources:"
        noun = "root" if count == 1 else "roots"
        return f"Selected Sources: ({count} {noun} staged)"

    def _format_confirm_label(self) -> str:
        count = len(self.selected_sources)
        if count > 1:
            return f"Select ({count} Folders)"
        return "Select"

    def _build_source_row_widget(self, idx: int, src: str) -> Horizontal:
        row_id = self._source_row_seq
        self._source_row_seq += 1
        path_lbl = Static(
            f"{idx + 1:02d}  {src}",
            classes="source-item-path",
            markup=False,
        )
        btn_rm = Button(
            "Remove",
            id=f"btn-remove-source-{row_id}",
            classes="btn-remove-source",
            variant="default",
        )
        btn_rm.tooltip = f"Remove source directory {src}"
        setattr(btn_rm, "_source_path", src)
        return Horizontal(path_lbl, btn_rm, classes="source-item-row")

    def compose(self) -> ComposeResult:
        """Compose modal dialog children."""
        with ModalBox(classes="modal-box"):
            with Vertical(classes="modal-body"):
                yield Heading(
                    "Select Target Directory",
                    level=1,
                    classes="modal-title",
                    id="modal-title",
                )
                inp = Input(
                    value="",
                    placeholder="Enter absolute directory path...",
                    id="input-dir",
                )
                inp.tooltip = "Enter absolute target directory path to scan"
                yield inp
                yield Static("", id="lbl-error", classes="error-banner")
                yield Label(self._format_sources_heading(), id="lbl-sources")
                empty_list = Static(
                    self._format_sources_display(),
                    id="static-sources-list",
                    classes="sources-list",
                    markup=False,
                )
                empty_list.display = len(self.selected_sources) == 0
                yield empty_list
                rows_container = Vertical(
                    *[
                        self._build_source_row_widget(idx, src)
                        for idx, src in enumerate(self.selected_sources)
                    ],
                    id="sources-rows-container",
                    classes="sources-rows-container",
                )
                rows_container.display = len(self.selected_sources) > 0
                yield rows_container
                with Horizontal(classes="source-actions-row"):
                    btn_add = Button("Add Path", id="btn-add-dir", variant="default")
                    btn_add.tooltip = "Add current path to multi-root source list"
                    yield btn_add
                    btn_clear = Button(
                        "Clear Sources", id="btn-clear-sources", variant="default"
                    )
                    btn_clear.tooltip = "Clear staged multi-root source directories"
                    yield btn_clear
                yield Label("Quick Presets (stages selection):")
                with Horizontal(classes="preset-row"):
                    p_demo = Button(
                        "Demo Workspace", id="preset-demo", variant="default"
                    )
                    p_demo.tooltip = "Stage sandbox demo workspace quick preset"
                    yield p_demo
                    p_dl = Button("Downloads", id="preset-downloads", variant="default")
                    p_dl.tooltip = "Stage user Downloads folder quick preset"
                    yield p_dl
                    p_docs = Button(
                        "Documents", id="preset-documents", variant="default"
                    )
                    p_docs.tooltip = "Stage user Documents folder quick preset"
                    yield p_docs
            with Horizontal(classes="button-row"):
                btn_browse = Button("Native Browse", id="btn-browse", variant="default")
                btn_browse.tooltip = "Launch native OS directory browser dialog"
                yield btn_browse
                btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
                btn_cancel.tooltip = "Cancel directory selection and close dialog"
                yield btn_cancel
                btn_confirm = Button(
                    self._format_confirm_label(), id="btn-confirm", variant="primary"
                )
                btn_confirm.tooltip = "Confirm directory selection"
                yield btn_confirm

    def _format_sources_display(self) -> str:
        if not self.selected_sources:
            return "(No source directories selected)"
        return "\n".join(f"• {d}" for d in self.selected_sources)

    def _update_sources_widget(self) -> None:
        with contextlib.suppress(Exception):
            lbl_src = self.query_one("#lbl-sources", Label)
            lbl_src.update(self._format_sources_heading())
        with contextlib.suppress(Exception):
            st = self.query_one("#static-sources-list", Static)
            st.update(self._format_sources_display())
            st.display = len(self.selected_sources) == 0
        with contextlib.suppress(Exception):
            rows_box = self.query_one("#sources-rows-container", Vertical)
            rows_box.remove_children()
            if self.selected_sources:
                rows_box.display = True
                for idx, src in enumerate(self.selected_sources):
                    rows_box.mount(self._build_source_row_widget(idx, src))
            else:
                rows_box.display = False
        with contextlib.suppress(Exception):
            btn_confirm = self.query_one("#btn-confirm", Button)
            btn_confirm.label = self._format_confirm_label()

    def _clear_input_dir(self) -> None:
        with contextlib.suppress(Exception):
            self.query_one("#input-dir", Input).value = ""

    def _stage_source_path(self, abs_path: str, announcement_label: str) -> None:
        if abs_path not in self.selected_sources:
            self.selected_sources.append(abs_path)
        self._update_sources_widget()
        with contextlib.suppress(Exception):
            self.query_one("#lbl-error", Static).update("")
        self.announce(f"Staged {announcement_label}: {abs_path}")

    def on_mount(self) -> None:
        """Focus input field on mount and emit screen reader announcement."""
        super().on_mount()
        try:
            self.query_one("#input-dir", Input).focus()
        except Exception:
            return
        self.announce("Opened target directory selection dialog.")

    @on(Button.Pressed, ".btn-remove-source")
    def on_remove_source_pressed(self, event: Button.Pressed) -> None:
        """Remove an individual staged root from selected_sources."""
        event.stop()
        target_src = getattr(event.button, "_source_path", None)
        if not target_src or target_src not in self.selected_sources:
            return
        self.selected_sources = [s for s in self.selected_sources if s != target_src]
        with contextlib.suppress(Exception):
            inp = self.query_one("#input-dir", Input)
            raw_val = inp.value.strip()
            if raw_val and os.path.abspath(os.path.expanduser(raw_val)) == target_src:
                inp.value = ""
        self._update_sources_widget()
        self.announce(f"Removed source directory: {target_src}")

    @on(Button.Pressed, "#btn-add-dir")
    def action_add_dir(self) -> None:
        """Add input directory path to selected source list and clear #input-dir."""
        val = self.query_one("#input-dir", Input).value.strip()
        if not val:
            return
        err = self._validate_directory_path(val, settings=self.settings)
        if err:
            self._show_error(err)
            return

        abs_p = os.path.abspath(os.path.expanduser(val))
        if abs_p not in self.selected_sources:
            self.selected_sources.append(abs_p)
            self.announce(f"Added directory path: {abs_p}")
        self._clear_input_dir()
        self._update_sources_widget()
        with contextlib.suppress(Exception):
            self.query_one("#lbl-error", Static).update("")

    @on(Button.Pressed, "#btn-clear-sources")
    def action_clear_sources(self) -> None:
        """Clear staged source directories and clear #input-dir."""
        self.selected_sources.clear()
        self._clear_input_dir()
        self._update_sources_widget()
        with contextlib.suppress(Exception):
            self.query_one("#lbl-error", Static).update("")
        self.announce("Cleared selected source directories.")

    @on(Button.Pressed, "#preset-demo")
    def action_demo(self) -> None:
        """Stage sandbox demo workspace preset without auto-dismissing."""
        from app.core.sample_corpus import generate_sample_corpus
        from app.ui.notifications import notify

        path = os.path.abspath("sandbox/demo_workspace")
        if not os.path.exists(path):
            try:
                os.makedirs(path, exist_ok=True)
                created_msg = f"Created demo workspace directory: {path}"
                self.announce(created_msg)
                notify(created_msg, type="info")
            except Exception as exc:
                err_msg = f"Failed to create directory '{path}': {exc}"
                self.announce(err_msg, priority="assertive")
                notify(err_msg, type="error")
                return

        err = self._validate_directory_path(path, settings=self.settings)
        if err:
            self._show_error(err)
            return

        try:
            generate_sample_corpus(path, overwrite=True)
            sample_msg = f"Generated sample corpus documents in '{path}'."
            self.announce(sample_msg)
            notify(sample_msg, type="info")
        except Exception as exc:
            logger.error(f"Failed to generate sample corpus in '{path}': {exc}")
            err_msg = f"Failed to generate sample corpus: {exc}"
            self.announce(err_msg, priority="assertive")
            notify(err_msg, type="error")

        self._stage_source_path(path, "demo workspace preset")

    @on(Button.Pressed, "#preset-downloads")
    def action_downloads(self) -> None:
        """Stage user Downloads directory preset without auto-dismissing."""
        path = os.path.abspath(os.path.expanduser("~/Downloads"))
        err = self._validate_directory_path(path, settings=self.settings)
        if err:
            self._show_error(err)
            return
        self._stage_source_path(path, "Downloads preset")

    @on(Button.Pressed, "#preset-documents")
    def action_documents(self) -> None:
        """Stage user Documents directory preset without auto-dismissing."""
        path = os.path.abspath(os.path.expanduser("~/Documents"))
        err = self._validate_directory_path(path, settings=self.settings)
        if err:
            self._show_error(err)
            return
        self._stage_source_path(path, "Documents preset")

    @on(Button.Pressed, "#btn-confirm")
    def action_confirm(self) -> None:
        """Confirm staged directory selection."""
        val = self.query_one("#input-dir", Input).value.strip()
        if val:
            err = self._validate_directory_path(val, settings=self.settings)
            if err:
                self._show_error(err)
                return

            abs_p = os.path.abspath(os.path.expanduser(val))
            if abs_p not in self.selected_sources:
                self.selected_sources.append(abs_p)
            self._update_sources_widget()

        if self.selected_sources:
            for source in self.selected_sources:
                err = self._validate_directory_path(source, settings=self.settings)
                if err:
                    self._show_error(err)
                    return

            self.announce(f"Confirmed directory selection: '{self.selected_sources}'")
            res = (
                list(self.selected_sources)
                if len(self.selected_sources) > 1
                else self.selected_sources[0]
            )
            self.dismiss(res)
        else:
            self.announce("Cancelled directory selection.")
            self.dismiss(None)

    @on(Button.Pressed, "#btn-cancel")
    def action_cancel(self) -> None:
        """Cancel directory selection."""
        self.announce("Cancelled directory selection.")
        self.dismiss(None)

    @on(Button.Pressed, "#btn-browse")
    @work(thread=True)
    def action_native_browse(self) -> None:
        """Launch native OS directory browser dialog in background worker thread."""
        from app.core.native_dialog import NativeDialogError, select_native_directory

        curr_val = ""
        try:
            inp = self.query_one("#input-dir", Input)
            curr_val = inp.value.strip()
        except Exception:
            pass

        initial_dir = curr_val or self.current_dir

        try:
            chosen = select_native_directory(initial_dir)
            if chosen:
                self.app.call_from_thread(self._on_native_dir_selected, chosen)
        except NativeDialogError as exc:
            self.app.call_from_thread(self._on_native_dir_failed, str(exc))
        except Exception as exc:
            self.app.call_from_thread(self._on_native_dir_failed, str(exc))

    def _on_native_dir_selected(self, path: str) -> None:
        """Handle decoded UTF-8 path string from native folder browser."""
        abs_p = os.path.abspath(os.path.expanduser(path))
        with contextlib.suppress(Exception):
            inp = self.query_one("#input-dir", Input)
            inp.value = abs_p
        err = self._validate_directory_path(abs_p, settings=self.settings)
        if err is None:
            if abs_p not in self.selected_sources:
                self.selected_sources.append(abs_p)
            self._update_sources_widget()
            self.announce(f"Selected native folder path: {abs_p}")
        elif os.path.exists(abs_p):
            self._show_error(err)
        else:
            self.announce(f"Selected native folder path: {abs_p}")

    def _on_native_dir_failed(self, reason: str) -> None:
        """Handle native folder dialog failure by falling back to manual path entry."""
        from app.ui.notifications import notify

        msg = "Native folder browser failed to launch. Please enter path manually."
        self.announce(msg, priority="assertive")
        notify(msg, type="warning")
        try:
            inp = self.query_one("#input-dir", Input)
            inp.focus()
        except Exception:
            pass

action_add_dir()

Add input directory path to selected source list and clear #input-dir.

Source code in app/ui/modals/edit.py
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
@on(Button.Pressed, "#btn-add-dir")
def action_add_dir(self) -> None:
    """Add input directory path to selected source list and clear #input-dir."""
    val = self.query_one("#input-dir", Input).value.strip()
    if not val:
        return
    err = self._validate_directory_path(val, settings=self.settings)
    if err:
        self._show_error(err)
        return

    abs_p = os.path.abspath(os.path.expanduser(val))
    if abs_p not in self.selected_sources:
        self.selected_sources.append(abs_p)
        self.announce(f"Added directory path: {abs_p}")
    self._clear_input_dir()
    self._update_sources_widget()
    with contextlib.suppress(Exception):
        self.query_one("#lbl-error", Static).update("")

action_cancel()

Cancel directory selection.

Source code in app/ui/modals/edit.py
2274
2275
2276
2277
2278
@on(Button.Pressed, "#btn-cancel")
def action_cancel(self) -> None:
    """Cancel directory selection."""
    self.announce("Cancelled directory selection.")
    self.dismiss(None)

action_clear_sources()

Clear staged source directories and clear #input-dir.

Source code in app/ui/modals/edit.py
2174
2175
2176
2177
2178
2179
2180
2181
2182
@on(Button.Pressed, "#btn-clear-sources")
def action_clear_sources(self) -> None:
    """Clear staged source directories and clear #input-dir."""
    self.selected_sources.clear()
    self._clear_input_dir()
    self._update_sources_widget()
    with contextlib.suppress(Exception):
        self.query_one("#lbl-error", Static).update("")
    self.announce("Cleared selected source directories.")

action_confirm()

Confirm staged directory selection.

Source code in app/ui/modals/edit.py
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
@on(Button.Pressed, "#btn-confirm")
def action_confirm(self) -> None:
    """Confirm staged directory selection."""
    val = self.query_one("#input-dir", Input).value.strip()
    if val:
        err = self._validate_directory_path(val, settings=self.settings)
        if err:
            self._show_error(err)
            return

        abs_p = os.path.abspath(os.path.expanduser(val))
        if abs_p not in self.selected_sources:
            self.selected_sources.append(abs_p)
        self._update_sources_widget()

    if self.selected_sources:
        for source in self.selected_sources:
            err = self._validate_directory_path(source, settings=self.settings)
            if err:
                self._show_error(err)
                return

        self.announce(f"Confirmed directory selection: '{self.selected_sources}'")
        res = (
            list(self.selected_sources)
            if len(self.selected_sources) > 1
            else self.selected_sources[0]
        )
        self.dismiss(res)
    else:
        self.announce("Cancelled directory selection.")
        self.dismiss(None)

action_demo()

Stage sandbox demo workspace preset without auto-dismissing.

Source code in app/ui/modals/edit.py
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
@on(Button.Pressed, "#preset-demo")
def action_demo(self) -> None:
    """Stage sandbox demo workspace preset without auto-dismissing."""
    from app.core.sample_corpus import generate_sample_corpus
    from app.ui.notifications import notify

    path = os.path.abspath("sandbox/demo_workspace")
    if not os.path.exists(path):
        try:
            os.makedirs(path, exist_ok=True)
            created_msg = f"Created demo workspace directory: {path}"
            self.announce(created_msg)
            notify(created_msg, type="info")
        except Exception as exc:
            err_msg = f"Failed to create directory '{path}': {exc}"
            self.announce(err_msg, priority="assertive")
            notify(err_msg, type="error")
            return

    err = self._validate_directory_path(path, settings=self.settings)
    if err:
        self._show_error(err)
        return

    try:
        generate_sample_corpus(path, overwrite=True)
        sample_msg = f"Generated sample corpus documents in '{path}'."
        self.announce(sample_msg)
        notify(sample_msg, type="info")
    except Exception as exc:
        logger.error(f"Failed to generate sample corpus in '{path}': {exc}")
        err_msg = f"Failed to generate sample corpus: {exc}"
        self.announce(err_msg, priority="assertive")
        notify(err_msg, type="error")

    self._stage_source_path(path, "demo workspace preset")

action_documents()

Stage user Documents directory preset without auto-dismissing.

Source code in app/ui/modals/edit.py
2231
2232
2233
2234
2235
2236
2237
2238
2239
@on(Button.Pressed, "#preset-documents")
def action_documents(self) -> None:
    """Stage user Documents directory preset without auto-dismissing."""
    path = os.path.abspath(os.path.expanduser("~/Documents"))
    err = self._validate_directory_path(path, settings=self.settings)
    if err:
        self._show_error(err)
        return
    self._stage_source_path(path, "Documents preset")

action_downloads()

Stage user Downloads directory preset without auto-dismissing.

Source code in app/ui/modals/edit.py
2221
2222
2223
2224
2225
2226
2227
2228
2229
@on(Button.Pressed, "#preset-downloads")
def action_downloads(self) -> None:
    """Stage user Downloads directory preset without auto-dismissing."""
    path = os.path.abspath(os.path.expanduser("~/Downloads"))
    err = self._validate_directory_path(path, settings=self.settings)
    if err:
        self._show_error(err)
        return
    self._stage_source_path(path, "Downloads preset")

action_native_browse()

Launch native OS directory browser dialog in background worker thread.

Source code in app/ui/modals/edit.py
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
@on(Button.Pressed, "#btn-browse")
@work(thread=True)
def action_native_browse(self) -> None:
    """Launch native OS directory browser dialog in background worker thread."""
    from app.core.native_dialog import NativeDialogError, select_native_directory

    curr_val = ""
    try:
        inp = self.query_one("#input-dir", Input)
        curr_val = inp.value.strip()
    except Exception:
        pass

    initial_dir = curr_val or self.current_dir

    try:
        chosen = select_native_directory(initial_dir)
        if chosen:
            self.app.call_from_thread(self._on_native_dir_selected, chosen)
    except NativeDialogError as exc:
        self.app.call_from_thread(self._on_native_dir_failed, str(exc))
    except Exception as exc:
        self.app.call_from_thread(self._on_native_dir_failed, str(exc))

compose()

Compose modal dialog children.

Source code in app/ui/modals/edit.py
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
def compose(self) -> ComposeResult:
    """Compose modal dialog children."""
    with ModalBox(classes="modal-box"):
        with Vertical(classes="modal-body"):
            yield Heading(
                "Select Target Directory",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            inp = Input(
                value="",
                placeholder="Enter absolute directory path...",
                id="input-dir",
            )
            inp.tooltip = "Enter absolute target directory path to scan"
            yield inp
            yield Static("", id="lbl-error", classes="error-banner")
            yield Label(self._format_sources_heading(), id="lbl-sources")
            empty_list = Static(
                self._format_sources_display(),
                id="static-sources-list",
                classes="sources-list",
                markup=False,
            )
            empty_list.display = len(self.selected_sources) == 0
            yield empty_list
            rows_container = Vertical(
                *[
                    self._build_source_row_widget(idx, src)
                    for idx, src in enumerate(self.selected_sources)
                ],
                id="sources-rows-container",
                classes="sources-rows-container",
            )
            rows_container.display = len(self.selected_sources) > 0
            yield rows_container
            with Horizontal(classes="source-actions-row"):
                btn_add = Button("Add Path", id="btn-add-dir", variant="default")
                btn_add.tooltip = "Add current path to multi-root source list"
                yield btn_add
                btn_clear = Button(
                    "Clear Sources", id="btn-clear-sources", variant="default"
                )
                btn_clear.tooltip = "Clear staged multi-root source directories"
                yield btn_clear
            yield Label("Quick Presets (stages selection):")
            with Horizontal(classes="preset-row"):
                p_demo = Button(
                    "Demo Workspace", id="preset-demo", variant="default"
                )
                p_demo.tooltip = "Stage sandbox demo workspace quick preset"
                yield p_demo
                p_dl = Button("Downloads", id="preset-downloads", variant="default")
                p_dl.tooltip = "Stage user Downloads folder quick preset"
                yield p_dl
                p_docs = Button(
                    "Documents", id="preset-documents", variant="default"
                )
                p_docs.tooltip = "Stage user Documents folder quick preset"
                yield p_docs
        with Horizontal(classes="button-row"):
            btn_browse = Button("Native Browse", id="btn-browse", variant="default")
            btn_browse.tooltip = "Launch native OS directory browser dialog"
            yield btn_browse
            btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
            btn_cancel.tooltip = "Cancel directory selection and close dialog"
            yield btn_cancel
            btn_confirm = Button(
                self._format_confirm_label(), id="btn-confirm", variant="primary"
            )
            btn_confirm.tooltip = "Confirm directory selection"
            yield btn_confirm

on_input_changed(event)

Clear error banner when user changes input text.

Source code in app/ui/modals/edit.py
1977
1978
1979
1980
1981
1982
1983
1984
@on(Input.Changed, "#input-dir")
def on_input_changed(self, event: Input.Changed) -> None:
    """Clear error banner when user changes input text."""
    try:
        lbl = self.query_one("#lbl-error", Static)
        lbl.update("")
    except Exception:
        pass

on_mount()

Focus input field on mount and emit screen reader announcement.

Source code in app/ui/modals/edit.py
2129
2130
2131
2132
2133
2134
2135
2136
def on_mount(self) -> None:
    """Focus input field on mount and emit screen reader announcement."""
    super().on_mount()
    try:
        self.query_one("#input-dir", Input).focus()
    except Exception:
        return
    self.announce("Opened target directory selection dialog.")

on_remove_source_pressed(event)

Remove an individual staged root from selected_sources.

Source code in app/ui/modals/edit.py
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
@on(Button.Pressed, ".btn-remove-source")
def on_remove_source_pressed(self, event: Button.Pressed) -> None:
    """Remove an individual staged root from selected_sources."""
    event.stop()
    target_src = getattr(event.button, "_source_path", None)
    if not target_src or target_src not in self.selected_sources:
        return
    self.selected_sources = [s for s in self.selected_sources if s != target_src]
    with contextlib.suppress(Exception):
        inp = self.query_one("#input-dir", Input)
        raw_val = inp.value.strip()
        if raw_val and os.path.abspath(os.path.expanduser(raw_val)) == target_src:
            inp.value = ""
    self._update_sources_widget()
    self.announce(f"Removed source directory: {target_src}")

DuplicateReviewModal

Bases: _BaseGroupSelectionModal

Dedicated review modal for exact byte-verified duplicate file clusters.

Source code in app/ui/modals/edit.py
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
class DuplicateReviewModal(_BaseGroupSelectionModal):
    """Dedicated review modal for exact byte-verified duplicate file clusters."""

    DEFAULT_BATCH_ACTION = "stage"
    OPEN_ANNOUNCEMENT = "Opened byte-verified duplicate review modal."
    APPLY_ALL_SCOPE_LABEL = "duplicate clusters"
    CONFIRM_ANNOUNCEMENT = "Applied duplicate cleanup selections."
    CANCEL_ANNOUNCEMENT = "Cancelled duplicate review dialog."

    DUPLICATE_OPTIONS = [
        ("Stage Duplicates for Undo (.sortify_duplicates)", "stage"),
        ("Move Duplicates to OS Trash (via staging)", "trash"),
        ("Keep Primary File Only (skip copies)", "keep"),
        ("Rename Copies (keep all with _1 suffix)", "rename"),
        ("Skip Cluster (leave all untouched)", "skip"),
    ]

    def __init__(
        self,
        duplicate_groups: list[dict[str, Any]] | None = None,
    ):
        super().__init__()
        self.duplicate_groups = duplicate_groups or []
        valid_values = {opt[1] for opt in self.DUPLICATE_OPTIONS}
        self.user_selections = {
            g["group_id"]: (
                str(g.get("default_action"))
                if g.get("default_action") in valid_values
                else "stage"
            )
            for g in self.duplicate_groups
        }

    def compose(self) -> ComposeResult:
        """Compose byte-verified duplicate cluster review dialog widgets."""
        from rich.markup import escape as rich_escape

        upper_tag_re = re.compile(r"(\\*)\[([A-Z][^[]*?)\]")

        def escape_markup(value: str) -> str:
            escaped = rich_escape(str(value))
            return upper_tag_re.sub(lambda m: f"{m.group(1)}\\[{m.group(2)}]", escaped)

        valid_values = {opt[1] for opt in self.DUPLICATE_OPTIONS}
        initial_batch = "stage"
        if self.duplicate_groups:
            first_def = self.duplicate_groups[0].get("default_action")
            if first_def in valid_values:
                initial_batch = str(first_def)
        has_initial_trash = any(val == "trash" for val in self.user_selections.values())
        warn_cls = (
            "trash-warning-banner"
            if has_initial_trash
            else "trash-warning-banner hidden"
        )

        with ModalBox(classes="modal-box"):
            with Vertical(classes="modal-body"):
                yield Heading(
                    "Byte-Verified Duplicate Review",
                    level=1,
                    classes="modal-title",
                    id="modal-title",
                )
                yield Label(
                    "Exact byte-identical copies detected. Redundant copies move only after the surviving original is verified:",
                    classes="modal-subtitle",
                )

                with Horizontal(classes="batch-bar", id="batch-action-bar"):
                    batch_sel = Select(
                        self.DUPLICATE_OPTIONS,
                        value=initial_batch,
                        id="batch-action-select",
                        classes="batch-select",
                        allow_blank=False,
                    )
                    batch_sel.tooltip = "Select batch cleanup action to apply to all byte-identical duplicate clusters"
                    setattr(
                        batch_sel,
                        "aria_label",
                        "Batch cleanup action for all byte-identical duplicate clusters",
                    )
                    yield batch_sel

                    btn_apply = Button("Apply to All", id="btn-apply-all")
                    btn_apply.tooltip = (
                        "Apply selected duplicate cleanup action to all clusters"
                    )
                    setattr(
                        btn_apply,
                        "aria_label",
                        "Apply selected duplicate cleanup action to all clusters",
                    )
                    yield btn_apply

                yield Label(
                    "Warning: Exporting duplicate copies to the OS Trash cannot be undone automatically by Sortify.",
                    id="lbl-trash-warning",
                    classes=warn_cls,
                )

                with Vertical(id="duplicate-groups-list"):
                    for group in self.duplicate_groups:
                        gid = group["group_id"]
                        tf_name = str(group.get("target_filename", "Duplicate"))
                        tf_escaped = escape_markup(tf_name)
                        items = group.get("items", [])
                        raw_default = group.get("default_action", "stage")
                        default_action = (
                            str(raw_default) if raw_default in valid_values else "stage"
                        )
                        byte_size = group.get("byte_size")
                        sha_val = str(group.get("sha256") or "")
                        sel_mode = escape_markup(
                            str(group.get("detect_original_by") or "first_seen")
                        )
                        meta_parts: list[str] = []
                        if isinstance(byte_size, int) and byte_size >= 0:
                            meta_parts.append(_format_file_size(byte_size))
                        if sha_val:
                            meta_parts.append(f"sha256:{sha_val[:12]}")
                        meta_suffix = (
                            escape_markup(f" ({', '.join(meta_parts)})")
                            if meta_parts
                            else ""
                        )

                        with Vertical(classes="duplicate-card", id=f"card-{gid}"):
                            yield Label(
                                f"Duplicate Cluster: {tf_escaped}{meta_suffix}",
                                classes="card-title",
                            )
                            yield Label(
                                f"Verified identical copies ({len(items)}) — original selector: {sel_mode}",
                                classes="card-subtitle",
                            )
                            if group.get("existing_file_on_disk") and group.get(
                                "primary_source_path"
                            ):
                                disk_src_escaped = escape_markup(
                                    str(group["primary_source_path"])
                                )
                                orig_disk_tag = escape_markup("[Original on Disk]")
                                yield Label(
                                    f"• {orig_disk_tag} {disk_src_escaped}",
                                    classes="source-item",
                                )
                            for idx, item in enumerate(items):
                                rel_src = str(
                                    item.get("relative_source")
                                    or item.get("source_path", "")
                                )
                                src_p = item.get("source_path", "")
                                role_tag = escape_markup(
                                    "[Original]"
                                    if (
                                        not group.get("existing_file_on_disk")
                                        and (item.get("is_primary") or idx == 0)
                                    )
                                    else "[Duplicate]"
                                )
                                size_info = ""
                                if isinstance(item.get("byte_size"), int):
                                    size_info = (
                                        f" ({_format_file_size(item['byte_size'])})"
                                    )
                                elif src_p and os.path.exists(src_p):
                                    try:
                                        sz = os.path.getsize(src_p)
                                        size_info = f" ({_format_file_size(sz)})"
                                    except OSError:
                                        pass
                                yield Label(
                                    f"• {role_tag} {escape_markup(rel_src)}{escape_markup(size_info)}",
                                    classes="source-item",
                                )

                            sel = Select(
                                self.DUPLICATE_OPTIONS,
                                value=default_action,
                                id=f"select-action-{gid}",
                                classes="action-select",
                                allow_blank=False,
                            )
                            sel.tooltip = (
                                f"Select duplicate cleanup action for {tf_name}"
                            )
                            setattr(
                                sel,
                                "aria_label",
                                f"Duplicate cleanup action for cluster {tf_name}",
                            )
                            yield sel

            with Horizontal(classes="button-row"):
                btn_confirm = Button(
                    "Confirm Duplicate Cleanup",
                    variant="primary",
                    id="btn-confirm-duplicates",
                )
                btn_confirm.tooltip = (
                    "Confirm duplicate cleanup actions and continue execution"
                )
                setattr(
                    btn_confirm,
                    "aria_label",
                    "Confirm duplicate cleanup actions and continue execution",
                )
                yield btn_confirm

                btn_cancel = Button("Cancel", id="btn-cancel-duplicates")
                btn_cancel.tooltip = "Cancel duplicate review and abort execution"
                setattr(
                    btn_cancel,
                    "aria_label",
                    "Cancel duplicate review and abort execution",
                )
                yield btn_cancel

    def _sync_trash_warning(self, announce_warning: bool = False) -> None:
        """Toggle the OS Trash irreversibility warning banner and optionally announce it."""
        has_trash = any(val == "trash" for val in self.user_selections.values())
        with contextlib.suppress(LookupError, AttributeError):
            warn_lbl = self.query_one("#lbl-trash-warning", Label)
            if has_trash:
                warn_lbl.remove_class("hidden")
            else:
                warn_lbl.add_class("hidden")
        if has_trash and announce_warning:
            self.announce(
                "Warning: Exporting duplicate copies to the OS Trash cannot be undone automatically by Sortify."
            )

    def action_apply_to_all(self) -> None:
        """Apply the selected batch action to all duplicate clusters and update trash warning."""
        super().action_apply_to_all()
        self._sync_trash_warning(announce_warning=True)

    def on_select_changed(self, event: Select.Changed) -> None:
        """Record cluster selection changes and warn when OS Trash disposal is chosen."""
        super().on_select_changed(event)
        if event.select.id and event.select.id.startswith("select-action-"):
            self._sync_trash_warning(announce_warning=(str(event.value) == "trash"))

action_apply_to_all()

Apply the selected batch action to all duplicate clusters and update trash warning.

Source code in app/ui/modals/edit.py
3160
3161
3162
3163
def action_apply_to_all(self) -> None:
    """Apply the selected batch action to all duplicate clusters and update trash warning."""
    super().action_apply_to_all()
    self._sync_trash_warning(announce_warning=True)

compose()

Compose byte-verified duplicate cluster review dialog widgets.

Source code in app/ui/modals/edit.py
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
def compose(self) -> ComposeResult:
    """Compose byte-verified duplicate cluster review dialog widgets."""
    from rich.markup import escape as rich_escape

    upper_tag_re = re.compile(r"(\\*)\[([A-Z][^[]*?)\]")

    def escape_markup(value: str) -> str:
        escaped = rich_escape(str(value))
        return upper_tag_re.sub(lambda m: f"{m.group(1)}\\[{m.group(2)}]", escaped)

    valid_values = {opt[1] for opt in self.DUPLICATE_OPTIONS}
    initial_batch = "stage"
    if self.duplicate_groups:
        first_def = self.duplicate_groups[0].get("default_action")
        if first_def in valid_values:
            initial_batch = str(first_def)
    has_initial_trash = any(val == "trash" for val in self.user_selections.values())
    warn_cls = (
        "trash-warning-banner"
        if has_initial_trash
        else "trash-warning-banner hidden"
    )

    with ModalBox(classes="modal-box"):
        with Vertical(classes="modal-body"):
            yield Heading(
                "Byte-Verified Duplicate Review",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            yield Label(
                "Exact byte-identical copies detected. Redundant copies move only after the surviving original is verified:",
                classes="modal-subtitle",
            )

            with Horizontal(classes="batch-bar", id="batch-action-bar"):
                batch_sel = Select(
                    self.DUPLICATE_OPTIONS,
                    value=initial_batch,
                    id="batch-action-select",
                    classes="batch-select",
                    allow_blank=False,
                )
                batch_sel.tooltip = "Select batch cleanup action to apply to all byte-identical duplicate clusters"
                setattr(
                    batch_sel,
                    "aria_label",
                    "Batch cleanup action for all byte-identical duplicate clusters",
                )
                yield batch_sel

                btn_apply = Button("Apply to All", id="btn-apply-all")
                btn_apply.tooltip = (
                    "Apply selected duplicate cleanup action to all clusters"
                )
                setattr(
                    btn_apply,
                    "aria_label",
                    "Apply selected duplicate cleanup action to all clusters",
                )
                yield btn_apply

            yield Label(
                "Warning: Exporting duplicate copies to the OS Trash cannot be undone automatically by Sortify.",
                id="lbl-trash-warning",
                classes=warn_cls,
            )

            with Vertical(id="duplicate-groups-list"):
                for group in self.duplicate_groups:
                    gid = group["group_id"]
                    tf_name = str(group.get("target_filename", "Duplicate"))
                    tf_escaped = escape_markup(tf_name)
                    items = group.get("items", [])
                    raw_default = group.get("default_action", "stage")
                    default_action = (
                        str(raw_default) if raw_default in valid_values else "stage"
                    )
                    byte_size = group.get("byte_size")
                    sha_val = str(group.get("sha256") or "")
                    sel_mode = escape_markup(
                        str(group.get("detect_original_by") or "first_seen")
                    )
                    meta_parts: list[str] = []
                    if isinstance(byte_size, int) and byte_size >= 0:
                        meta_parts.append(_format_file_size(byte_size))
                    if sha_val:
                        meta_parts.append(f"sha256:{sha_val[:12]}")
                    meta_suffix = (
                        escape_markup(f" ({', '.join(meta_parts)})")
                        if meta_parts
                        else ""
                    )

                    with Vertical(classes="duplicate-card", id=f"card-{gid}"):
                        yield Label(
                            f"Duplicate Cluster: {tf_escaped}{meta_suffix}",
                            classes="card-title",
                        )
                        yield Label(
                            f"Verified identical copies ({len(items)}) — original selector: {sel_mode}",
                            classes="card-subtitle",
                        )
                        if group.get("existing_file_on_disk") and group.get(
                            "primary_source_path"
                        ):
                            disk_src_escaped = escape_markup(
                                str(group["primary_source_path"])
                            )
                            orig_disk_tag = escape_markup("[Original on Disk]")
                            yield Label(
                                f"• {orig_disk_tag} {disk_src_escaped}",
                                classes="source-item",
                            )
                        for idx, item in enumerate(items):
                            rel_src = str(
                                item.get("relative_source")
                                or item.get("source_path", "")
                            )
                            src_p = item.get("source_path", "")
                            role_tag = escape_markup(
                                "[Original]"
                                if (
                                    not group.get("existing_file_on_disk")
                                    and (item.get("is_primary") or idx == 0)
                                )
                                else "[Duplicate]"
                            )
                            size_info = ""
                            if isinstance(item.get("byte_size"), int):
                                size_info = (
                                    f" ({_format_file_size(item['byte_size'])})"
                                )
                            elif src_p and os.path.exists(src_p):
                                try:
                                    sz = os.path.getsize(src_p)
                                    size_info = f" ({_format_file_size(sz)})"
                                except OSError:
                                    pass
                            yield Label(
                                f"• {role_tag} {escape_markup(rel_src)}{escape_markup(size_info)}",
                                classes="source-item",
                            )

                        sel = Select(
                            self.DUPLICATE_OPTIONS,
                            value=default_action,
                            id=f"select-action-{gid}",
                            classes="action-select",
                            allow_blank=False,
                        )
                        sel.tooltip = (
                            f"Select duplicate cleanup action for {tf_name}"
                        )
                        setattr(
                            sel,
                            "aria_label",
                            f"Duplicate cleanup action for cluster {tf_name}",
                        )
                        yield sel

        with Horizontal(classes="button-row"):
            btn_confirm = Button(
                "Confirm Duplicate Cleanup",
                variant="primary",
                id="btn-confirm-duplicates",
            )
            btn_confirm.tooltip = (
                "Confirm duplicate cleanup actions and continue execution"
            )
            setattr(
                btn_confirm,
                "aria_label",
                "Confirm duplicate cleanup actions and continue execution",
            )
            yield btn_confirm

            btn_cancel = Button("Cancel", id="btn-cancel-duplicates")
            btn_cancel.tooltip = "Cancel duplicate review and abort execution"
            setattr(
                btn_cancel,
                "aria_label",
                "Cancel duplicate review and abort execution",
            )
            yield btn_cancel

on_select_changed(event)

Record cluster selection changes and warn when OS Trash disposal is chosen.

Source code in app/ui/modals/edit.py
3165
3166
3167
3168
3169
def on_select_changed(self, event: Select.Changed) -> None:
    """Record cluster selection changes and warn when OS Trash disposal is chosen."""
    super().on_select_changed(event)
    if event.select.id and event.select.id.startswith("select-action-"):
        self._sync_trash_warning(announce_warning=(str(event.value) == "trash"))

FilteredExecutionConfirmModal

Bases: ResponsiveModalScreen[str | None]

Confirmation dialog shown when Ctrl+E runs while search hides included plan files.

Source code in app/ui/modals/edit.py
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
class FilteredExecutionConfirmModal(ResponsiveModalScreen[str | None]):
    """Confirmation dialog shown when Ctrl+E runs while search hides included plan files."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .filtered-exec-box {
        width: 88%;
        max-width: 86;
    }
    .filtered-exec-warning {
        width: 100%;
        color: $warning;
        text-style: bold;
        margin-top: 1;
        margin-bottom: 1;
    }
    .filtered-exec-summary {
        width: 100%;
        border: solid $primary;
        padding: 1 2;
        margin-bottom: 1;
        height: auto;
        background: $boost;
    }
    .filtered-exec-stat {
        width: 100%;
        color: $text;
    }
    .filtered-exec-note {
        width: 100%;
        color: $text-muted;
    }
    .button-row {
        min-height: 3;
    }
    .button-row Button {
        min-width: 0;
        width: auto;
        padding: 0 1;
        margin-left: 1;
    }
    Button:focus {
        border: heavy $accent;
        text-style: bold;
    }
    FilteredExecutionConfirmModal {
        &.compact .filtered-exec-box {
            width: 96%;
        }
        &.compact .filtered-exec-warning {
            margin-top: 0;
            margin-bottom: 0;
        }
        &.compact .filtered-exec-summary {
            padding: 0 1;
            margin-bottom: 0;
        }
        &.narrow .button-row {
            layout: grid;
            grid-size: 1;
            grid-rows: auto;
            height: auto;
            min-height: 0;
            margin-top: 0;
        }
        &.narrow .button-row Button {
            width: 100%;
            height: 1;
            min-height: 1;
            border: none;
            margin: 0;
            padding: 0 1;
        }
    }
    """

    def __init__(
        self,
        filter_query: str = "route:fallback",
        visible_included_count: int = 3,
        hidden_included_count: int = 4,
        total_included_count: int | None = None,
        hidden_folders: list[str] | None = None,
    ) -> None:
        super().__init__()
        self.filter_query = filter_query
        self.visible_included_count = max(0, int(visible_included_count))
        self.hidden_included_count = max(0, int(hidden_included_count))
        self.total_included_count = (
            max(0, int(total_included_count))
            if total_included_count is not None
            else self.visible_included_count + self.hidden_included_count
        )
        self.hidden_folders = [f for f in (hidden_folders or []) if f]

    def compose(self) -> ComposeResult:
        """Compose filtered execution confirmation dialog."""
        if self.hidden_folders:
            shown_folders = ", ".join(self.hidden_folders[:3])
            extra = (
                f" (+{len(self.hidden_folders) - 3} more)"
                if len(self.hidden_folders) > 3
                else ""
            )
            folder_clause = f" in {shown_folders}{extra}"
        else:
            folder_clause = ""

        warn_text = (
            f"Search filter hides {self.hidden_included_count} included file(s)"
            f"{folder_clause}."
        )

        with ModalBox(classes="modal-box filtered-exec-box"):
            with Vertical(classes="modal-body"):
                yield Heading(
                    "Confirm Filtered Execution",
                    level=1,
                    classes="modal-title",
                    id="modal-title",
                )
                yield Label(
                    warn_text,
                    id="lbl-filtered-exec-warning",
                    classes="filtered-exec-warning",
                    markup=False,
                )
                with Vertical(
                    id="filtered-exec-summary", classes="filtered-exec-summary"
                ):
                    yield Label(
                        f"Filter Query: {self.filter_query}",
                        id="lbl-filtered-exec-query",
                        classes="filtered-exec-stat",
                        markup=False,
                    )
                    yield Label(
                        f"Matching visible included files: {self.visible_included_count}",
                        id="lbl-filtered-exec-visible",
                        classes="filtered-exec-stat",
                        markup=False,
                    )
                    yield Label(
                        f"Hidden included files: {self.hidden_included_count} "
                        f"(Total included: {self.total_included_count})",
                        id="lbl-filtered-exec-hidden",
                        classes="filtered-exec-stat",
                        markup=False,
                    )
                yield Label(
                    "Choose whether to move only the visible included files or execute the full plan.",
                    id="lbl-filtered-exec-note",
                    classes="filtered-exec-note",
                    markup=False,
                )
            with Horizontal(classes="button-row"):
                btn_cancel = Button(
                    "Cancel",
                    id="btn-filtered-exec-cancel",
                    variant="default",
                )
                btn_cancel.tooltip = "Cancel execution and return to filtered plan tree"
                yield btn_cancel

                btn_full = Button(
                    f"Execute Full Plan ({self.total_included_count})",
                    id="btn-filtered-exec-full",
                    variant="default",
                )
                btn_full.tooltip = f"Execute all {self.total_included_count} included files in the full plan"
                yield btn_full

                btn_visible = Button(
                    f"Execute Visible Only ({self.visible_included_count})",
                    id="btn-filtered-exec-visible",
                    variant="primary",
                )
                btn_visible.tooltip = f"Execute only the {self.visible_included_count} visible included files"
                yield btn_visible

    def on_mount(self) -> None:
        """Focus primary action button and announce filtered execution dialog."""
        super().on_mount()
        matches = self.query("#btn-filtered-exec-visible")
        if matches:
            matches.first(Button).focus()
        self.announce(
            f"Confirm Filtered Execution: {self.hidden_included_count} included file(s) hidden by search filter."
        )

    @on(Button.Pressed, "#btn-filtered-exec-visible")
    def action_execute_visible(self) -> None:
        """Confirm executing visible included files only."""
        self.announce(
            f"Confirmed executing {self.visible_included_count} visible included file(s)."
        )
        self.dismiss("visible")

    @on(Button.Pressed, "#btn-filtered-exec-full")
    def action_execute_full(self) -> None:
        """Confirm executing the full unfiltered plan."""
        self.announce(
            f"Confirmed executing full plan ({self.total_included_count} included file(s))."
        )
        self.dismiss("full")

    @on(Button.Pressed, "#btn-filtered-exec-cancel")
    def action_cancel(self) -> None:
        """Cancel filtered execution confirmation dialog."""
        self.announce("Cancelled filtered execution.")
        self.dismiss(None)

action_cancel()

Cancel filtered execution confirmation dialog.

Source code in app/ui/modals/edit.py
3386
3387
3388
3389
3390
@on(Button.Pressed, "#btn-filtered-exec-cancel")
def action_cancel(self) -> None:
    """Cancel filtered execution confirmation dialog."""
    self.announce("Cancelled filtered execution.")
    self.dismiss(None)

action_execute_full()

Confirm executing the full unfiltered plan.

Source code in app/ui/modals/edit.py
3378
3379
3380
3381
3382
3383
3384
@on(Button.Pressed, "#btn-filtered-exec-full")
def action_execute_full(self) -> None:
    """Confirm executing the full unfiltered plan."""
    self.announce(
        f"Confirmed executing full plan ({self.total_included_count} included file(s))."
    )
    self.dismiss("full")

action_execute_visible()

Confirm executing visible included files only.

Source code in app/ui/modals/edit.py
3370
3371
3372
3373
3374
3375
3376
@on(Button.Pressed, "#btn-filtered-exec-visible")
def action_execute_visible(self) -> None:
    """Confirm executing visible included files only."""
    self.announce(
        f"Confirmed executing {self.visible_included_count} visible included file(s)."
    )
    self.dismiss("visible")

compose()

Compose filtered execution confirmation dialog.

Source code in app/ui/modals/edit.py
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
def compose(self) -> ComposeResult:
    """Compose filtered execution confirmation dialog."""
    if self.hidden_folders:
        shown_folders = ", ".join(self.hidden_folders[:3])
        extra = (
            f" (+{len(self.hidden_folders) - 3} more)"
            if len(self.hidden_folders) > 3
            else ""
        )
        folder_clause = f" in {shown_folders}{extra}"
    else:
        folder_clause = ""

    warn_text = (
        f"Search filter hides {self.hidden_included_count} included file(s)"
        f"{folder_clause}."
    )

    with ModalBox(classes="modal-box filtered-exec-box"):
        with Vertical(classes="modal-body"):
            yield Heading(
                "Confirm Filtered Execution",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            yield Label(
                warn_text,
                id="lbl-filtered-exec-warning",
                classes="filtered-exec-warning",
                markup=False,
            )
            with Vertical(
                id="filtered-exec-summary", classes="filtered-exec-summary"
            ):
                yield Label(
                    f"Filter Query: {self.filter_query}",
                    id="lbl-filtered-exec-query",
                    classes="filtered-exec-stat",
                    markup=False,
                )
                yield Label(
                    f"Matching visible included files: {self.visible_included_count}",
                    id="lbl-filtered-exec-visible",
                    classes="filtered-exec-stat",
                    markup=False,
                )
                yield Label(
                    f"Hidden included files: {self.hidden_included_count} "
                    f"(Total included: {self.total_included_count})",
                    id="lbl-filtered-exec-hidden",
                    classes="filtered-exec-stat",
                    markup=False,
                )
            yield Label(
                "Choose whether to move only the visible included files or execute the full plan.",
                id="lbl-filtered-exec-note",
                classes="filtered-exec-note",
                markup=False,
            )
        with Horizontal(classes="button-row"):
            btn_cancel = Button(
                "Cancel",
                id="btn-filtered-exec-cancel",
                variant="default",
            )
            btn_cancel.tooltip = "Cancel execution and return to filtered plan tree"
            yield btn_cancel

            btn_full = Button(
                f"Execute Full Plan ({self.total_included_count})",
                id="btn-filtered-exec-full",
                variant="default",
            )
            btn_full.tooltip = f"Execute all {self.total_included_count} included files in the full plan"
            yield btn_full

            btn_visible = Button(
                f"Execute Visible Only ({self.visible_included_count})",
                id="btn-filtered-exec-visible",
                variant="primary",
            )
            btn_visible.tooltip = f"Execute only the {self.visible_included_count} visible included files"
            yield btn_visible

on_mount()

Focus primary action button and announce filtered execution dialog.

Source code in app/ui/modals/edit.py
3360
3361
3362
3363
3364
3365
3366
3367
3368
def on_mount(self) -> None:
    """Focus primary action button and announce filtered execution dialog."""
    super().on_mount()
    matches = self.query("#btn-filtered-exec-visible")
    if matches:
        matches.first(Button).focus()
    self.announce(
        f"Confirm Filtered Execution: {self.hidden_included_count} included file(s) hidden by search filter."
    )

InteractiveCollisionResolverModal

Bases: _BaseGroupSelectionModal

Interactive per-file collision resolution modal before execution.

Source code in app/ui/modals/edit.py
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
class InteractiveCollisionResolverModal(_BaseGroupSelectionModal):
    """Interactive per-file collision resolution modal before execution."""

    DEFAULT_BATCH_ACTION = "rename"
    OPEN_ANNOUNCEMENT = "Opened interactive collision resolver modal."
    APPLY_ALL_SCOPE_LABEL = "collision groups"
    CONFIRM_ANNOUNCEMENT = "Applied collision resolution selections."
    CANCEL_ANNOUNCEMENT = "Cancelled collision resolver dialog."

    RESOLVER_OPTIONS = [
        ("Rename (auto-number colliding files)", "rename"),
        ("Overwrite (replace target file)", "overwrite"),
        ("Skip (exclude colliding file)", "skip"),
        ("Keep Both (preserve destination & prefix source)", "keep_both"),
        ("Keep Primary File Only", "keep"),
    ]

    def __init__(
        self,
        duplicate_groups: list[dict[str, Any]] | None = None,
        collision_groups: list[dict[str, Any]] | None = None,
    ):
        super().__init__()
        groups = (
            collision_groups if collision_groups is not None else duplicate_groups
        ) or []
        self.collision_groups = groups
        self.duplicate_groups = groups
        valid_values = {opt[1] for opt in self.RESOLVER_OPTIONS}
        self.user_selections = {
            g["group_id"]: (
                str(g.get("default_action"))
                if g.get("default_action") in valid_values
                else "rename"
            )
            for g in self.collision_groups
        }

    def compose(self) -> ComposeResult:
        """Compose interactive collision resolution dialog widgets."""
        valid_values = {opt[1] for opt in self.RESOLVER_OPTIONS}
        with ModalBox(classes="modal-box"):
            with Vertical(classes="modal-body"):
                yield Heading(
                    "Interactive Collision Resolver",
                    level=1,
                    classes="modal-title",
                    id="modal-title",
                )
                yield Label(
                    "Distinct files share a proposed destination filename. Select per-target resolution actions:",
                    classes="modal-subtitle",
                )

                with Horizontal(classes="batch-bar", id="batch-action-bar"):
                    batch_sel = Select(
                        self.RESOLVER_OPTIONS,
                        value="rename",
                        id="batch-action-select",
                        classes="batch-select",
                        allow_blank=False,
                    )
                    batch_sel.tooltip = "Select batch collision action to apply to all colliding destination targets"
                    setattr(
                        batch_sel,
                        "aria_label",
                        "Batch resolution action for all destination collision groups",
                    )
                    yield batch_sel

                    btn_apply = Button("Apply to All", id="btn-apply-all")
                    btn_apply.tooltip = (
                        "Apply selected collision resolution action to all groups"
                    )
                    setattr(
                        btn_apply,
                        "aria_label",
                        "Apply selected collision resolution action to all groups",
                    )
                    yield btn_apply

                with Vertical(id="duplicate-groups-list"):
                    for group in self.collision_groups:
                        gid = group["group_id"]
                        tf_name = group.get("target_filename", "Collision")
                        t_dir = group.get("target_dir", "")
                        items = group.get("items", [])
                        raw_default = group.get("default_action", "rename")
                        default_action = (
                            str(raw_default)
                            if raw_default in valid_values
                            else "rename"
                        )

                        with Vertical(classes="duplicate-card", id=f"card-{gid}"):
                            yield Label(
                                f"Destination Target: {tf_name} ({t_dir})",
                                classes="card-title",
                            )
                            yield Label(
                                f"Colliding distinct source files ({len(items)}):",
                                classes="card-subtitle",
                            )
                            for item in items:
                                rel_src = item.get("relative_source") or item.get(
                                    "source_path", ""
                                )
                                src_p = item.get("source_path", "")
                                size_info = ""
                                if src_p and os.path.exists(src_p):
                                    try:
                                        sz = os.path.getsize(src_p)
                                        size_info = f" ({_format_file_size(sz)})"
                                    except OSError:
                                        pass
                                yield Label(
                                    f"• {rel_src}{size_info}", classes="source-item"
                                )

                            sel = Select(
                                self.RESOLVER_OPTIONS,
                                value=default_action,
                                id=f"select-action-{gid}",
                                classes="action-select",
                                allow_blank=False,
                            )
                            sel.tooltip = (
                                f"Select collision resolution action for {tf_name}"
                            )
                            setattr(
                                sel,
                                "aria_label",
                                f"Collision resolution action for {tf_name}",
                            )
                            yield sel

            with Horizontal(classes="button-row"):
                btn_confirm = Button(
                    "Apply & Execute Moves",
                    variant="primary",
                    id="btn-confirm-duplicates",
                )
                btn_confirm.tooltip = (
                    "Confirm collision resolution selections and continue execution"
                )
                setattr(
                    btn_confirm,
                    "aria_label",
                    "Confirm collision resolution selections and continue execution",
                )
                yield btn_confirm

                btn_cancel = Button("Cancel", id="btn-cancel-duplicates")
                btn_cancel.tooltip = "Cancel collision resolution and abort execution"
                setattr(
                    btn_cancel,
                    "aria_label",
                    "Cancel collision resolution and abort execution",
                )
                yield btn_cancel

compose()

Compose interactive collision resolution dialog widgets.

Source code in app/ui/modals/edit.py
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
def compose(self) -> ComposeResult:
    """Compose interactive collision resolution dialog widgets."""
    valid_values = {opt[1] for opt in self.RESOLVER_OPTIONS}
    with ModalBox(classes="modal-box"):
        with Vertical(classes="modal-body"):
            yield Heading(
                "Interactive Collision Resolver",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            yield Label(
                "Distinct files share a proposed destination filename. Select per-target resolution actions:",
                classes="modal-subtitle",
            )

            with Horizontal(classes="batch-bar", id="batch-action-bar"):
                batch_sel = Select(
                    self.RESOLVER_OPTIONS,
                    value="rename",
                    id="batch-action-select",
                    classes="batch-select",
                    allow_blank=False,
                )
                batch_sel.tooltip = "Select batch collision action to apply to all colliding destination targets"
                setattr(
                    batch_sel,
                    "aria_label",
                    "Batch resolution action for all destination collision groups",
                )
                yield batch_sel

                btn_apply = Button("Apply to All", id="btn-apply-all")
                btn_apply.tooltip = (
                    "Apply selected collision resolution action to all groups"
                )
                setattr(
                    btn_apply,
                    "aria_label",
                    "Apply selected collision resolution action to all groups",
                )
                yield btn_apply

            with Vertical(id="duplicate-groups-list"):
                for group in self.collision_groups:
                    gid = group["group_id"]
                    tf_name = group.get("target_filename", "Collision")
                    t_dir = group.get("target_dir", "")
                    items = group.get("items", [])
                    raw_default = group.get("default_action", "rename")
                    default_action = (
                        str(raw_default)
                        if raw_default in valid_values
                        else "rename"
                    )

                    with Vertical(classes="duplicate-card", id=f"card-{gid}"):
                        yield Label(
                            f"Destination Target: {tf_name} ({t_dir})",
                            classes="card-title",
                        )
                        yield Label(
                            f"Colliding distinct source files ({len(items)}):",
                            classes="card-subtitle",
                        )
                        for item in items:
                            rel_src = item.get("relative_source") or item.get(
                                "source_path", ""
                            )
                            src_p = item.get("source_path", "")
                            size_info = ""
                            if src_p and os.path.exists(src_p):
                                try:
                                    sz = os.path.getsize(src_p)
                                    size_info = f" ({_format_file_size(sz)})"
                                except OSError:
                                    pass
                            yield Label(
                                f"• {rel_src}{size_info}", classes="source-item"
                            )

                        sel = Select(
                            self.RESOLVER_OPTIONS,
                            value=default_action,
                            id=f"select-action-{gid}",
                            classes="action-select",
                            allow_blank=False,
                        )
                        sel.tooltip = (
                            f"Select collision resolution action for {tf_name}"
                        )
                        setattr(
                            sel,
                            "aria_label",
                            f"Collision resolution action for {tf_name}",
                        )
                        yield sel

        with Horizontal(classes="button-row"):
            btn_confirm = Button(
                "Apply & Execute Moves",
                variant="primary",
                id="btn-confirm-duplicates",
            )
            btn_confirm.tooltip = (
                "Confirm collision resolution selections and continue execution"
            )
            setattr(
                btn_confirm,
                "aria_label",
                "Confirm collision resolution selections and continue execution",
            )
            yield btn_confirm

            btn_cancel = Button("Cancel", id="btn-cancel-duplicates")
            btn_cancel.tooltip = "Cancel collision resolution and abort execution"
            setattr(
                btn_cancel,
                "aria_label",
                "Cancel collision resolution and abort execution",
            )
            yield btn_cancel

ManualPathFallbackModal

Bases: ResponsiveModalScreen[str | None]

Fallback modal dialog for manual directory path entry when native selection fails.

Source code in app/ui/modals/edit.py
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
class ManualPathFallbackModal(ResponsiveModalScreen[str | None]):
    """Fallback modal dialog for manual directory path entry when native selection fails."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-box {
        border: thick $warning;
        max-width: 70;
    }
    .button-row {
        min-height: 3;
    }
    .button-row Button {
        margin-left: 1;
    }
    """

    def __init__(self, current_dir: str = "", reason: str = ""):
        super().__init__()
        self.current_dir = current_dir
        self.reason = reason

    def compose(self) -> ComposeResult:
        """Compose modal fallback UI children."""
        with ModalBox(classes="modal-box"):
            with Vertical(classes="modal-body"):
                yield Heading("Manual Directory Entry", level=1, classes="modal-title")
                if self.reason:
                    yield Label(f"Native tool notice: {self.reason}", id="lbl-reason")
                yield Label("Please enter target directory path manually:")
                inp = Input(
                    value=self.current_dir,
                    placeholder="Enter absolute folder path...",
                    id="input-fallback-dir",
                )
                yield inp
            with Horizontal(classes="button-row"):
                btn_cancel = Button(
                    "Cancel", id="btn-cancel-fallback", variant="default"
                )
                yield btn_cancel
                btn_confirm = Button(
                    "Confirm", id="btn-confirm-fallback", variant="primary"
                )
                yield btn_confirm

    def on_mount(self) -> None:
        """Focus input field on mount and announce screen reader alert."""
        super().on_mount()
        self.query_one("#input-fallback-dir", Input).focus()
        self.announce("Opened manual directory entry fallback dialog.")

    @on(Button.Pressed, "#btn-confirm-fallback")
    @on(Input.Submitted, "#input-fallback-dir")
    def action_confirm(self) -> None:
        """Confirm manual path entry."""
        val = self.query_one("#input-fallback-dir", Input).value.strip()
        if val:
            abs_p = os.path.abspath(os.path.expanduser(val))
            self.announce(f"Confirmed manual directory entry: '{abs_p}'")
            self.dismiss(abs_p)
        else:
            self.announce("Cancelled manual directory entry.")
            self.dismiss(None)

    @on(Button.Pressed, "#btn-cancel-fallback")
    def action_cancel(self) -> None:
        """Cancel manual path entry."""
        self.announce("Cancelled manual directory entry.")
        self.dismiss(None)

action_cancel()

Cancel manual path entry.

Source code in app/ui/modals/edit.py
2541
2542
2543
2544
2545
@on(Button.Pressed, "#btn-cancel-fallback")
def action_cancel(self) -> None:
    """Cancel manual path entry."""
    self.announce("Cancelled manual directory entry.")
    self.dismiss(None)

action_confirm()

Confirm manual path entry.

Source code in app/ui/modals/edit.py
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
@on(Button.Pressed, "#btn-confirm-fallback")
@on(Input.Submitted, "#input-fallback-dir")
def action_confirm(self) -> None:
    """Confirm manual path entry."""
    val = self.query_one("#input-fallback-dir", Input).value.strip()
    if val:
        abs_p = os.path.abspath(os.path.expanduser(val))
        self.announce(f"Confirmed manual directory entry: '{abs_p}'")
        self.dismiss(abs_p)
    else:
        self.announce("Cancelled manual directory entry.")
        self.dismiss(None)

compose()

Compose modal fallback UI children.

Source code in app/ui/modals/edit.py
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
def compose(self) -> ComposeResult:
    """Compose modal fallback UI children."""
    with ModalBox(classes="modal-box"):
        with Vertical(classes="modal-body"):
            yield Heading("Manual Directory Entry", level=1, classes="modal-title")
            if self.reason:
                yield Label(f"Native tool notice: {self.reason}", id="lbl-reason")
            yield Label("Please enter target directory path manually:")
            inp = Input(
                value=self.current_dir,
                placeholder="Enter absolute folder path...",
                id="input-fallback-dir",
            )
            yield inp
        with Horizontal(classes="button-row"):
            btn_cancel = Button(
                "Cancel", id="btn-cancel-fallback", variant="default"
            )
            yield btn_cancel
            btn_confirm = Button(
                "Confirm", id="btn-confirm-fallback", variant="primary"
            )
            yield btn_confirm

on_mount()

Focus input field on mount and announce screen reader alert.

Source code in app/ui/modals/edit.py
2522
2523
2524
2525
2526
def on_mount(self) -> None:
    """Focus input field on mount and announce screen reader alert."""
    super().on_mount()
    self.query_one("#input-fallback-dir", Input).focus()
    self.announce("Opened manual directory entry fallback dialog.")

NewFolderModal

Bases: _CollisionWarningMixin, _SubmittableModalMixin, ResponsiveModalScreen[str | None]

Modal dialog for creating a new folder node in the plan.

Source code in app/ui/modals/edit.py
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
class NewFolderModal(
    _CollisionWarningMixin,
    _SubmittableModalMixin,
    ResponsiveModalScreen[str | None],
):
    """Modal dialog for creating a new folder node in the plan."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-warning {
        color: $warning;
        text-style: bold;
        margin-top: 1;
        margin-bottom: 1;
    }
    .modal-error {
        color: $error;
        text-style: bold;
        margin-top: 1;
        margin-bottom: 1;
    }
    .button-row {
        min-height: 3;
    }
    .button-row Button {
        margin-left: 1;
    }
    Button:focus, Input:focus {
        border: heavy $accent;
        text-style: bold;
    }
    """

    def compose(self) -> ComposeResult:
        """Compose modal dialog children."""
        with ModalBox(classes="modal-box"):
            with Vertical(classes="modal-body"):
                yield Heading(
                    "Create New Target Folder",
                    level=1,
                    classes="modal-title",
                    id="modal-title",
                )
                inp = Input(
                    placeholder="e.g. Financials, Financial/Audits, Contracts",
                    id="input-folder-name",
                )
                inp.tooltip = "Enter new target folder category name"
                yield inp
                yield Label("", id="warning-collision", classes="modal-warning")
            with Horizontal(classes="button-row"):
                btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
                btn_cancel.tooltip = "Cancel folder creation and close dialog"
                yield btn_cancel
                btn_confirm = Button("Create", id="btn-confirm", variant="primary")
                btn_confirm.tooltip = "Confirm new folder category creation"
                yield btn_confirm

    def on_mount(self) -> None:
        """Focus input field on mount and emit screen reader announcement."""
        super().on_mount()
        self.query_one("#input-folder-name", Input).focus()
        self.announce("Opened create new target folder dialog.")

    @on(Input.Changed, "#input-folder-name")
    def on_input_changed(self, event: Input.Changed) -> None:
        """Validate folder path inline as user types."""
        val = event.value.strip()
        if not val:
            self._set_collision_warning("", is_error=False)
            return
        try:
            validate_target_path(val)
            self._set_collision_warning("", is_error=False)
        except ValueError as ve:
            self._set_collision_warning(f"⚠️ Validation Error: {ve}", is_error=True)

    @on(Button.Pressed, "#btn-confirm")
    def action_confirm(self) -> None:
        """Confirm folder creation action."""
        val = self.query_one("#input-folder-name", Input).value.strip()
        if not val:
            self.announce("Cancelled folder creation.")
            self.dismiss(None)
            return
        try:
            validate_target_path(val)
        except ValueError as ve:
            self._set_collision_warning(f"⚠️ Validation Error: {ve}", is_error=True)
            self.announce(f"Cannot create folder: {ve}")
            return
        clean_val = "/".join(
            p for p in val.replace("\\", "/").strip("/").split("/") if p
        )
        self.announce(f"Confirmed folder creation for '{clean_val}'.")
        self.dismiss(clean_val)

    @on(Button.Pressed, "#btn-cancel")
    def action_cancel(self) -> None:
        """Cancel folder creation action."""
        self.announce("Cancelled folder creation.")
        self.dismiss(None)

action_cancel()

Cancel folder creation action.

Source code in app/ui/modals/edit.py
1121
1122
1123
1124
1125
@on(Button.Pressed, "#btn-cancel")
def action_cancel(self) -> None:
    """Cancel folder creation action."""
    self.announce("Cancelled folder creation.")
    self.dismiss(None)

action_confirm()

Confirm folder creation action.

Source code in app/ui/modals/edit.py
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
@on(Button.Pressed, "#btn-confirm")
def action_confirm(self) -> None:
    """Confirm folder creation action."""
    val = self.query_one("#input-folder-name", Input).value.strip()
    if not val:
        self.announce("Cancelled folder creation.")
        self.dismiss(None)
        return
    try:
        validate_target_path(val)
    except ValueError as ve:
        self._set_collision_warning(f"⚠️ Validation Error: {ve}", is_error=True)
        self.announce(f"Cannot create folder: {ve}")
        return
    clean_val = "/".join(
        p for p in val.replace("\\", "/").strip("/").split("/") if p
    )
    self.announce(f"Confirmed folder creation for '{clean_val}'.")
    self.dismiss(clean_val)

compose()

Compose modal dialog children.

Source code in app/ui/modals/edit.py
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
def compose(self) -> ComposeResult:
    """Compose modal dialog children."""
    with ModalBox(classes="modal-box"):
        with Vertical(classes="modal-body"):
            yield Heading(
                "Create New Target Folder",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            inp = Input(
                placeholder="e.g. Financials, Financial/Audits, Contracts",
                id="input-folder-name",
            )
            inp.tooltip = "Enter new target folder category name"
            yield inp
            yield Label("", id="warning-collision", classes="modal-warning")
        with Horizontal(classes="button-row"):
            btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
            btn_cancel.tooltip = "Cancel folder creation and close dialog"
            yield btn_cancel
            btn_confirm = Button("Create", id="btn-confirm", variant="primary")
            btn_confirm.tooltip = "Confirm new folder category creation"
            yield btn_confirm

on_input_changed(event)

Validate folder path inline as user types.

Source code in app/ui/modals/edit.py
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
@on(Input.Changed, "#input-folder-name")
def on_input_changed(self, event: Input.Changed) -> None:
    """Validate folder path inline as user types."""
    val = event.value.strip()
    if not val:
        self._set_collision_warning("", is_error=False)
        return
    try:
        validate_target_path(val)
        self._set_collision_warning("", is_error=False)
    except ValueError as ve:
        self._set_collision_warning(f"⚠️ Validation Error: {ve}", is_error=True)

on_mount()

Focus input field on mount and emit screen reader announcement.

Source code in app/ui/modals/edit.py
1082
1083
1084
1085
1086
def on_mount(self) -> None:
    """Focus input field on mount and emit screen reader announcement."""
    super().on_mount()
    self.query_one("#input-folder-name", Input).focus()
    self.announce("Opened create new target folder dialog.")

ReassignModal

Bases: _CollisionWarningMixin, _SubmittableModalMixin, ResponsiveModalScreen[str | None]

Modal dialog for reassigning checked file nodes to a target category folder.

Source code in app/ui/modals/edit.py
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
class ReassignModal(
    _CollisionWarningMixin,
    _SubmittableModalMixin,
    ResponsiveModalScreen[str | None],
):
    """Modal dialog for reassigning checked file nodes to a target category folder."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .reassign-subtitle {
        color: $text-muted;
        margin-bottom: 1;
    }
    .modal-warning {
        color: $warning;
        text-style: bold;
        margin-top: 1;
        margin-bottom: 1;
    }
    .modal-error {
        color: $error;
        text-style: bold;
        margin-top: 1;
        margin-bottom: 1;
    }
    .rule-preview-card {
        border: round $primary-darken-1;
        background: $surface;
        padding: 1;
        margin-top: 1;
        height: auto;
    }
    .rule-header-row {
        width: 100%;
        height: auto;
        align: left middle;
    }
    #chk-learn-rule {
        width: 1fr;
        border: none;
        padding: 0;
        background: transparent;
    }
    .rule-priority-badge {
        color: $accent;
        background: $boost;
        text-style: bold;
        padding: 0 1;
        width: auto;
    }
    #input-learned-pattern.rule-disabled {
        opacity: 0.6;
    }
    .rule-tokens-preview {
        width: 100%;
        height: auto;
        color: $text;
        margin-top: 0;
    }
    .rule-tokens-warning {
        color: $warning;
        text-style: bold;
    }
    .rule-match-count {
        width: 100%;
        height: auto;
        color: $success;
        text-style: bold;
        margin-top: 0;
    }
    .rule-scope-note {
        width: 100%;
        height: auto;
        color: $text-muted;
        margin-top: 0;
    }
    .button-row {
        min-height: 3;
    }
    .button-row Button {
        margin-left: 1;
    }
    Button:focus, Input:focus, Select:focus, Checkbox:focus {
        border: heavy $accent;
        text-style: bold;
    }
    ReassignModal {
        .modal-box {
            width: 86;
            max-width: 96%;
        }
        &.compact .modal-box, &.narrow .modal-box {
            width: 96%;
            max-height: 96%;
        }
        &.compact .modal-title {
            margin-bottom: 0;
        }
        &.compact .reassign-subtitle,
        &.compact .rule-scope-note {
            display: none;
        }
        &.compact .modal-warning,
        &.compact .modal-error {
            margin-top: 0;
            margin-bottom: 0;
        }
        &.compact .rule-preview-card {
            margin-top: 0;
            padding: 0 1;
        }
        &.compact .button-row {
            margin-top: 0;
            min-height: 1;
        }
        &.compact .button-row Button {
            height: 1;
            min-height: 1;
            border: none;
            padding: 0 1;
        }
        &.narrow .button-row Button {
            min-width: 0;
            padding: 0 1;
        }
    }
    """

    def __init__(
        self,
        existing_folders: list[str],
        count: int = 1,
        plan: dict[str, Any] | None = None,
        base_dir: str | None = None,
        target_files: list[dict[str, Any]] | None = None,
        dest_dir: str | None = None,
        settings: Any = None,
    ):
        super().__init__()
        from app.core.scanner import discover_existing_folders

        disk_folders = discover_existing_folders(
            base_dir, dest_dir=dest_dir, settings=settings
        )
        merged: list[str] = []
        seen_lower: set[str] = set()
        for folder in list(existing_folders or []) + disk_folders:
            if not folder:
                continue
            key = folder.lower()
            if key not in seen_lower:
                seen_lower.add(key)
                merged.append(folder)
        self.existing_folders = merged
        self.count = count
        self.plan = plan
        self.base_dir = base_dir
        self.dest_dir = dest_dir
        self.settings = settings
        self.target_files = target_files or []
        self._last_collision_state: str | None = None

        raw_sources: list[str] = []
        display_sources: list[str] = []
        for fi in self.target_files:
            if isinstance(fi, dict):
                raw_fn = (
                    fi.get("source_path")
                    or fi.get("source")
                    or fi.get("filepath")
                    or fi.get("key")
                    or fi.get("target_filename")
                )
            else:
                raw_fn = str(fi) if fi else None
            if raw_fn:
                s_fn = str(raw_fn)
                raw_sources.append(s_fn)
                clean_s = s_fn.split("::", 1)[1] if "::" in s_fn else s_fn
                display_sources.append(os.path.basename(clean_s.replace("\\", "/")))

        self._source_filenames = display_sources
        (
            self._initial_learned_pattern,
            self._stripped_stopwords,
            self._is_generic_only,
        ) = derive_learned_pattern_for_files(raw_sources)
        self._default_learn_rule = bool(
            self._initial_learned_pattern and not self._is_generic_only
        )
        self._user_toggled_rule = False
        self._syncing_rule_checkbox = False

    def _collect_plan_filenames(self) -> list[str]:
        """Collect distinct source filenames across ``self.plan`` (or ``target_files`` fallback)."""
        collected: list[str] = []

        def _walk(node_dict: dict[str, Any]) -> None:
            for k, v in node_dict.items():
                if not isinstance(v, dict):
                    continue
                if v.get("__type__") == "file":
                    raw = (
                        v.get("source_path")
                        or v.get("source")
                        or v.get("filepath")
                        or v.get("target_filename")
                        or k
                    )
                    clean = str(raw).split("::", 1)[1] if "::" in str(raw) else str(raw)
                    base = os.path.basename(clean.replace("\\", "/"))
                    if base:
                        collected.append(base)
                else:
                    _walk(v)

        if isinstance(self.plan, dict) and self.plan:
            _walk(self.plan)
        if not collected and self._source_filenames:
            collected.extend(self._source_filenames)
        return collected

    def _resolve_current_target_value(self) -> str:
        """Read trimmed destination folder from manual input or dropdown select."""
        target = ""
        with contextlib.suppress(Exception):
            target = self.query_one("#input-target-folder", Input).value.strip()
        if not target:
            with contextlib.suppress(Exception):
                sel = self.query_one("#select-folder", Select)
                if sel.value is not Select.BLANK and sel.value:
                    target = str(sel.value).strip()
        return target

    def _update_rule_preview_ui(self) -> None:
        """Refresh rule toggle state, token preview chips, and live plan match count."""
        try:
            chk = self.query_one("#chk-learn-rule", Checkbox)
            pat_inp = self.query_one("#input-learned-pattern", Input)
            lbl_tokens = self.query_one("#lbl-rule-tokens", Label)
            lbl_matches = self.query_one("#lbl-rule-matches", Label)
        except Exception:
            return

        target = self._resolve_current_target_value()
        is_external = bool(target and _is_absolute_path(target))
        pat_val = pat_inp.value.strip()

        self._syncing_rule_checkbox = True
        try:
            if is_external:
                chk.value = False
                chk.disabled = True
            else:
                chk.disabled = False
                if not self._user_toggled_rule:
                    chk.value = bool(self._default_learn_rule and pat_val)
        finally:
            self._syncing_rule_checkbox = False

        if chk.value:
            pat_inp.remove_class("rule-disabled")
        else:
            pat_inp.add_class("rule-disabled")

        if is_external:
            lbl_tokens.update(
                "External destination path — learned rules require relative workspace folders."
            )
            lbl_tokens.add_class("rule-tokens-warning")
            lbl_matches.update("Matches 0 files in current plan (file move only)")
            return

        if not pat_val:
            lbl_tokens.add_class("rule-tokens-warning")
            if self._is_generic_only and self._stripped_stopwords:
                stops_fmt = ", ".join(f"'{s}'" for s in self._stripped_stopwords[:3])
                lbl_tokens.update(
                    f"Generic stem {stops_fmt} stripped — rule learning disabled by default."
                )
            else:
                lbl_tokens.update(
                    "No generalized filename tokens — enter a pattern to save a rule."
                )
            lbl_matches.update("Matches 0 files in current plan (file move only)")
            return

        lbl_tokens.remove_class("rule-tokens-warning")
        tokens = [tok for tok in re.split(r"[_\-\s.]+", pat_val.lower().strip()) if tok]
        chips = " + ".join(f"[{tok}]" for tok in tokens) if tokens else f"[{pat_val}]"
        regex_expr = (
            "".join(f"(?=.*{re.escape(tok)})" for tok in tokens)
            if len(tokens) > 1
            else (re.escape(tokens[0]) if tokens else re.escape(pat_val))
        )
        lbl_tokens.update(f"Tokens: {chips}   Pattern: (?i){regex_expr}")

        candidates = self._collect_plan_filenames()
        matched_files = [
            fn for fn in candidates if matches_learned_rule_pattern(pat_val, fn)
        ]

        overridden_kw: list[str] = []
        if matched_files and self.settings is not None:
            scoped_cfg = resolve_scoped_settings(
                self.settings, self.base_dir, fallback_to_global=True
            )
            kw_rules = getattr(scoped_cfg, "KEYWORD_RULES", {}) or {}
            if isinstance(kw_rules, dict):
                for kw in kw_rules:
                    kw_s = str(kw).strip().lower()
                    if kw_s and any(kw_s in fn.lower() for fn in matched_files):
                        overridden_kw.append(str(kw))

        override_note = (
            f" • Overrides '{overridden_kw[0]}' keyword rule (priority 80)"
            if overridden_kw
            else ""
        )
        prefix = "Rule active:" if chk.value else "Rule off (move only):"
        lbl_matches.update(
            f"{prefix} Matches {len(matched_files)} file(s) in current plan{override_note}"
        )

    def compose(self) -> ComposeResult:
        """Compose modal dialog children."""
        with ModalBox(classes="modal-box"):
            with Vertical(classes="modal-body"):
                yield Heading(
                    f"Reassign {self.count} Selected File(s)",
                    level=1,
                    classes="modal-title",
                    id="modal-title",
                )
                if self._source_filenames:
                    if len(self._source_filenames) == 1:
                        src_desc = f"Source file: {self._source_filenames[0]}"
                    elif len(self._source_filenames) <= 2:
                        src_desc = "Source files: " + ", ".join(self._source_filenames)
                    else:
                        shown = ", ".join(self._source_filenames[:2])
                        src_desc = (
                            f"Source files: {shown} "
                            f"(+{len(self._source_filenames) - 2} more)"
                        )
                    yield Label(
                        src_desc,
                        id="lbl-reassign-source",
                        classes="reassign-subtitle",
                    )
                yield Heading("Select Existing Target Folder:", level=2)
                options = [(f, f) for f in sorted(self.existing_folders)]
                if options:
                    sel = Select(options, prompt="Choose folder...", id="select-folder")
                    sel.tooltip = (
                        "Choose an existing destination folder from workspace or plan"
                    )
                    yield sel
                yield Heading(
                    "Or Enter Target Category / External Directory Path:", level=2
                )
                inp = Input(
                    placeholder="e.g. Clients/Acme, /Volumes/Backup, or D:\\External\\Archive",
                    id="input-target-folder",
                )
                inp.tooltip = (
                    "Enter relative folder name or absolute external directory path"
                )
                yield inp
                yield Label("", id="warning-collision", classes="modal-warning")

                with Vertical(id="rule-preview-card", classes="rule-preview-card"):
                    with Horizontal(classes="rule-header-row"):
                        chk = Checkbox(
                            "Save as filename rule",
                            value=self._default_learn_rule,
                            id="chk-learn-rule",
                        )
                        chk.tooltip = (
                            "Toggle saving a priority-90 normalized filename rule"
                        )
                        yield chk
                        yield Label(
                            "PRIORITY: 90",
                            id="lbl-rule-priority",
                            classes="rule-priority-badge",
                        )
                    pat_inp = Input(
                        value=self._initial_learned_pattern,
                        placeholder="Enter generalized filename tokens (e.g. invoice acme)...",
                        id="input-learned-pattern",
                    )
                    pat_inp.tooltip = (
                        "Edit normalized filename tokens matched during future sorts"
                    )
                    yield pat_inp
                    yield Label(
                        "",
                        id="lbl-rule-tokens",
                        classes="rule-tokens-preview",
                        markup=False,
                    )
                    yield Label(
                        "",
                        id="lbl-rule-matches",
                        classes="rule-match-count",
                        markup=False,
                    )
                    yield Label(
                        "Evaluated on normalized filenames only (never document body text).",
                        id="lbl-rule-scope-note",
                        classes="rule-scope-note",
                    )
            with Horizontal(classes="button-row"):
                btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
                btn_cancel.tooltip = "Cancel reassign dialog"
                yield btn_cancel
                btn_confirm = Button("Reassign", id="btn-confirm", variant="primary")
                btn_confirm.tooltip = "Confirm bulk reassignment"
                yield btn_confirm

    def on_mount(self) -> None:
        """Focus input field on mount and emit announcement."""
        super().on_mount()
        self.query_one("#input-target-folder", Input).focus()
        self.announce(f"Opened bulk reassign dialog for {self.count} items.")
        self._check_collision_and_update_ui()
        self._update_rule_preview_ui()

    def _check_collision_and_update_ui(self) -> tuple[bool, str | None]:
        """Run live collision check and path validation across plan and filesystem."""
        try:
            inp = self.query_one("#input-target-folder", Input)
            target = inp.value.strip()
            if not target:
                sel = self.query_one("#select-folder", Select)
                if sel.value is not Select.BLANK and sel.value:
                    target = str(sel.value).strip()
        except Exception:
            return False, None

        if not target:
            self._set_collision_warning("", is_error=False)
            self._last_collision_state = None
            return False, None

        if "\x00" in target:
            msg = "Null bytes are not permitted in paths."
            self._set_collision_warning(f"⚠️ Security Error: {msg}", is_error=True)
            return True, msg

        segments = re.split(r"[/\\]+", target)
        if ".." in segments:
            msg = "Directory traversal ('..') segments are not permitted."
            self._set_collision_warning(f"⚠️ Security Error: {msg}", is_error=True)
            if self._last_collision_state != msg:
                self.announce(f"⚠️ Security Error: {msg}")
                self._last_collision_state = msg
            return True, msg

        s_check = re.sub(r"^[a-zA-Z]:", "", target)
        if any(c in s_check for c in '<>"|?*\x00'):
            msg = "Destination path contains illegal characters."
            self._set_collision_warning(f"⚠️ Validation Error: {msg}", is_error=True)
            return True, msg

        if not _is_absolute_path(target):
            try:
                validate_target_path(target)
            except ValueError as ve:
                msg = str(ve)
                self._set_collision_warning(f"⚠️ Validation Error: {msg}", is_error=True)
                return True, msg

        # Check collision across staging plan and filesystem
        collisions = []
        resolved_target_dict = (
            resolve_plan_folder_dict(self.plan, target, create=False)
            if self.plan
            else None
        )
        target_dict = (
            resolved_target_dict if isinstance(resolved_target_dict, dict) else {}
        )

        for fi in self.target_files:
            fn = (
                fi.get("target_filename")
                or fi.get("key")
                or (
                    os.path.basename(str(fi["source_path"]))
                    if fi.get("source_path")
                    else None
                )
                or (
                    os.path.basename(str(fi["filepath"]))
                    if fi.get("filepath")
                    else None
                )
            )
            src_fp = fi.get("filepath")
            if not fn:
                continue

            if fn in target_dict:
                existing_item = target_dict[fn]
                if (
                    isinstance(existing_item, dict)
                    and existing_item is not fi
                    and existing_item.get("filepath") != src_fp
                ):
                    collisions.append(fn)
            elif self.base_dir or _is_absolute_path(target):
                if _is_absolute_path(target):
                    dst_disk = os.path.normpath(os.path.join(target, fn))
                elif self.base_dir:
                    dst_disk = os.path.normpath(os.path.join(self.base_dir, target, fn))
                else:
                    dst_disk = None

                if dst_disk and os.path.lexists(dst_disk):
                    is_same = False
                    if src_fp and os.path.lexists(src_fp):
                        try:
                            is_same = os.path.samefile(dst_disk, src_fp)
                        except OSError:
                            is_same = os.path.normcase(
                                os.path.abspath(dst_disk)
                            ) == os.path.normcase(os.path.abspath(src_fp))
                    if not is_same:
                        collisions.append(fn)

        if collisions:
            preview_files = ", ".join(f"'{c}'" for c in collisions[:3])
            more = f" and {len(collisions) - 3} more" if len(collisions) > 3 else ""
            warn_msg = (
                f"Collision detected: File(s) {preview_files}{more} already exist in '{target}'. "
                "Accidental overwrites blocked (will disambiguate)."
            )
            full_warn = f"⚠️ {warn_msg}"
            self._set_collision_warning(full_warn, is_error=False)
            if self._last_collision_state != full_warn:
                self.announce(full_warn)
                self._last_collision_state = full_warn
            return False, warn_msg
        else:
            self._set_collision_warning("", is_error=False)
            self._last_collision_state = None
            return False, None

    @on(Input.Changed, "#input-target-folder")
    def on_input_changed(self, event: Input.Changed) -> None:
        """Update collision status and rule preview on manual target folder input change."""
        self._check_collision_and_update_ui()
        self._update_rule_preview_ui()

    @on(Select.Changed, "#select-folder")
    def on_select_changed(self, event: Select.Changed) -> None:
        """Update collision status and rule preview on select folder change."""
        self._check_collision_and_update_ui()
        self._update_rule_preview_ui()

    @on(Input.Changed, "#input-learned-pattern")
    def on_learned_pattern_changed(self, event: Input.Changed) -> None:
        """Refresh live token chips and plan match count when learned pattern is edited."""
        self._update_rule_preview_ui()

    @on(Checkbox.Changed, "#chk-learn-rule")
    def on_learn_rule_toggled(self, event: Checkbox.Changed) -> None:
        """Record explicit user opt-in/opt-out decision for saving filename rule."""
        if not self._syncing_rule_checkbox:
            self._user_toggled_rule = True
        self._update_rule_preview_ui()

    @on(Button.Pressed, "#btn-confirm")
    def action_confirm(self) -> None:
        """Confirm reassign action."""
        is_blocked, err = self._check_collision_and_update_ui()
        if is_blocked:
            self.announce(f"Cannot confirm reassignment: {err}")
            return

        val = self._resolve_current_target_value()
        if not val:
            self.announce("Cancelled bulk reassign.")
            self.dismiss(None)
            return

        learn_checked = False
        learned_pat: str | None = None
        with contextlib.suppress(Exception):
            chk = self.query_one("#chk-learn-rule", Checkbox)
            pat_inp = self.query_one("#input-learned-pattern", Input)
            raw_pat = re.sub(r"[_\-\s.]+", " ", pat_inp.value.strip().lower()).strip()
            if chk.value and raw_pat and not _is_absolute_path(val):
                learn_checked = True
                learned_pat = raw_pat

        self.announce(f"Reassigning to target folder '{val}'.")
        self.dismiss(
            ReassignResult(
                val,
                learn_rule=learn_checked,
                learned_pattern=learned_pat,
            )
        )

    @on(Button.Pressed, "#btn-cancel")
    def action_cancel(self) -> None:
        """Cancel reassign action."""
        self.announce("Cancelled bulk reassign.")
        self.dismiss(None)

action_cancel()

Cancel reassign action.

Source code in app/ui/modals/edit.py
1740
1741
1742
1743
1744
@on(Button.Pressed, "#btn-cancel")
def action_cancel(self) -> None:
    """Cancel reassign action."""
    self.announce("Cancelled bulk reassign.")
    self.dismiss(None)

action_confirm()

Confirm reassign action.

Source code in app/ui/modals/edit.py
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
@on(Button.Pressed, "#btn-confirm")
def action_confirm(self) -> None:
    """Confirm reassign action."""
    is_blocked, err = self._check_collision_and_update_ui()
    if is_blocked:
        self.announce(f"Cannot confirm reassignment: {err}")
        return

    val = self._resolve_current_target_value()
    if not val:
        self.announce("Cancelled bulk reassign.")
        self.dismiss(None)
        return

    learn_checked = False
    learned_pat: str | None = None
    with contextlib.suppress(Exception):
        chk = self.query_one("#chk-learn-rule", Checkbox)
        pat_inp = self.query_one("#input-learned-pattern", Input)
        raw_pat = re.sub(r"[_\-\s.]+", " ", pat_inp.value.strip().lower()).strip()
        if chk.value and raw_pat and not _is_absolute_path(val):
            learn_checked = True
            learned_pat = raw_pat

    self.announce(f"Reassigning to target folder '{val}'.")
    self.dismiss(
        ReassignResult(
            val,
            learn_rule=learn_checked,
            learned_pattern=learned_pat,
        )
    )

compose()

Compose modal dialog children.

Source code in app/ui/modals/edit.py
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
def compose(self) -> ComposeResult:
    """Compose modal dialog children."""
    with ModalBox(classes="modal-box"):
        with Vertical(classes="modal-body"):
            yield Heading(
                f"Reassign {self.count} Selected File(s)",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            if self._source_filenames:
                if len(self._source_filenames) == 1:
                    src_desc = f"Source file: {self._source_filenames[0]}"
                elif len(self._source_filenames) <= 2:
                    src_desc = "Source files: " + ", ".join(self._source_filenames)
                else:
                    shown = ", ".join(self._source_filenames[:2])
                    src_desc = (
                        f"Source files: {shown} "
                        f"(+{len(self._source_filenames) - 2} more)"
                    )
                yield Label(
                    src_desc,
                    id="lbl-reassign-source",
                    classes="reassign-subtitle",
                )
            yield Heading("Select Existing Target Folder:", level=2)
            options = [(f, f) for f in sorted(self.existing_folders)]
            if options:
                sel = Select(options, prompt="Choose folder...", id="select-folder")
                sel.tooltip = (
                    "Choose an existing destination folder from workspace or plan"
                )
                yield sel
            yield Heading(
                "Or Enter Target Category / External Directory Path:", level=2
            )
            inp = Input(
                placeholder="e.g. Clients/Acme, /Volumes/Backup, or D:\\External\\Archive",
                id="input-target-folder",
            )
            inp.tooltip = (
                "Enter relative folder name or absolute external directory path"
            )
            yield inp
            yield Label("", id="warning-collision", classes="modal-warning")

            with Vertical(id="rule-preview-card", classes="rule-preview-card"):
                with Horizontal(classes="rule-header-row"):
                    chk = Checkbox(
                        "Save as filename rule",
                        value=self._default_learn_rule,
                        id="chk-learn-rule",
                    )
                    chk.tooltip = (
                        "Toggle saving a priority-90 normalized filename rule"
                    )
                    yield chk
                    yield Label(
                        "PRIORITY: 90",
                        id="lbl-rule-priority",
                        classes="rule-priority-badge",
                    )
                pat_inp = Input(
                    value=self._initial_learned_pattern,
                    placeholder="Enter generalized filename tokens (e.g. invoice acme)...",
                    id="input-learned-pattern",
                )
                pat_inp.tooltip = (
                    "Edit normalized filename tokens matched during future sorts"
                )
                yield pat_inp
                yield Label(
                    "",
                    id="lbl-rule-tokens",
                    classes="rule-tokens-preview",
                    markup=False,
                )
                yield Label(
                    "",
                    id="lbl-rule-matches",
                    classes="rule-match-count",
                    markup=False,
                )
                yield Label(
                    "Evaluated on normalized filenames only (never document body text).",
                    id="lbl-rule-scope-note",
                    classes="rule-scope-note",
                )
        with Horizontal(classes="button-row"):
            btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
            btn_cancel.tooltip = "Cancel reassign dialog"
            yield btn_cancel
            btn_confirm = Button("Reassign", id="btn-confirm", variant="primary")
            btn_confirm.tooltip = "Confirm bulk reassignment"
            yield btn_confirm

on_input_changed(event)

Update collision status and rule preview on manual target folder input change.

Source code in app/ui/modals/edit.py
1683
1684
1685
1686
1687
@on(Input.Changed, "#input-target-folder")
def on_input_changed(self, event: Input.Changed) -> None:
    """Update collision status and rule preview on manual target folder input change."""
    self._check_collision_and_update_ui()
    self._update_rule_preview_ui()

on_learn_rule_toggled(event)

Record explicit user opt-in/opt-out decision for saving filename rule.

Source code in app/ui/modals/edit.py
1700
1701
1702
1703
1704
1705
@on(Checkbox.Changed, "#chk-learn-rule")
def on_learn_rule_toggled(self, event: Checkbox.Changed) -> None:
    """Record explicit user opt-in/opt-out decision for saving filename rule."""
    if not self._syncing_rule_checkbox:
        self._user_toggled_rule = True
    self._update_rule_preview_ui()

on_learned_pattern_changed(event)

Refresh live token chips and plan match count when learned pattern is edited.

Source code in app/ui/modals/edit.py
1695
1696
1697
1698
@on(Input.Changed, "#input-learned-pattern")
def on_learned_pattern_changed(self, event: Input.Changed) -> None:
    """Refresh live token chips and plan match count when learned pattern is edited."""
    self._update_rule_preview_ui()

on_mount()

Focus input field on mount and emit announcement.

Source code in app/ui/modals/edit.py
1554
1555
1556
1557
1558
1559
1560
def on_mount(self) -> None:
    """Focus input field on mount and emit announcement."""
    super().on_mount()
    self.query_one("#input-target-folder", Input).focus()
    self.announce(f"Opened bulk reassign dialog for {self.count} items.")
    self._check_collision_and_update_ui()
    self._update_rule_preview_ui()

on_select_changed(event)

Update collision status and rule preview on select folder change.

Source code in app/ui/modals/edit.py
1689
1690
1691
1692
1693
@on(Select.Changed, "#select-folder")
def on_select_changed(self, event: Select.Changed) -> None:
    """Update collision status and rule preview on select folder change."""
    self._check_collision_and_update_ui()
    self._update_rule_preview_ui()

ReassignResult

Bases: str

String subclass representing reassigned target folder with optional learned rule.

Source code in app/ui/modals/edit.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
class ReassignResult(str):
    """String subclass representing reassigned target folder with optional learned rule."""

    learn_rule: bool = False
    learned_pattern: str | None = None

    def __new__(
        cls,
        value: str,
        learn_rule: bool = False,
        learned_pattern: str | None = None,
    ):
        """Instantiate target folder string with rule-learning decision."""
        instance = super().__new__(cls, value)
        instance.learn_rule = bool(learn_rule)
        instance.learned_pattern = learned_pattern
        return instance

__new__(value, learn_rule=False, learned_pattern=None)

Instantiate target folder string with rule-learning decision.

Source code in app/ui/modals/edit.py
71
72
73
74
75
76
77
78
79
80
81
def __new__(
    cls,
    value: str,
    learn_rule: bool = False,
    learned_pattern: str | None = None,
):
    """Instantiate target folder string with rule-learning decision."""
    instance = super().__new__(cls, value)
    instance.learn_rule = bool(learn_rule)
    instance.learned_pattern = learned_pattern
    return instance

RenameModal

Bases: _CollisionWarningMixin, _SubmittableModalMixin, ResponsiveModalScreen[str | RenameResult | None]

Modal dialog for renaming a file or folder node with pattern token formatting and destination path override support.

Source code in app/ui/modals/edit.py
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
class RenameModal(
    _CollisionWarningMixin,
    _SubmittableModalMixin,
    ResponsiveModalScreen[str | RenameResult | None],
):
    """Modal dialog for renaming a file or folder node with pattern token formatting and destination path override support."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("alt+r", "reset_original", "Reset to Original", show=False),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-subtitle {
        width: 100%;
        color: $text-muted;
        margin-bottom: 1;
    }
    .token-help {
        width: 100%;
        color: $text-muted;
        margin-bottom: 1;
    }
    .modal-warning {
        color: $warning;
        text-style: bold;
        margin-top: 1;
        margin-bottom: 1;
    }
    .modal-preview {
        color: $accent;
        margin-top: 1;
        margin-bottom: 1;
        text-style: bold;
    }
    .button-row {
        min-height: 3;
    }
    .button-row Button {
        margin-left: 1;
    }
    RenameModal {
        &.narrow .button-row {
            layout: grid;
            grid-size: 2;
            grid-gutter: 0 1;
        }
        &.narrow .button-row Button {
            width: 100%;
            min-width: 0;
            margin-left: 0;
        }
    }
    Button:focus, Input:focus {
        border: heavy $accent;
        text-style: bold;
    }
    """

    def __init__(
        self,
        title: str,
        current_name: str = "",
        extension: str = "",
        category: str = "",
        file_date: str = "",
        seq: int = 1,
        destination_override: str = "",
        is_folder: bool = False,
        plan: dict[str, Any] | None = None,
        base_dir: str | None = None,
        source_path: str | None = None,
        files: list[Any] | None = None,
        original_name: str = "",
        keywords: str = "",
    ):
        super().__init__()
        self.modal_title = title
        self.files = list(files) if files is not None else None
        self.current_name = current_name
        self.extension = extension
        self.category = category
        self.file_date = file_date
        self.seq = seq
        self.destination_override = destination_override
        self.is_folder = is_folder
        self.plan = plan
        self.base_dir = base_dir
        self.source_path = source_path
        if original_name:
            self.original_name = original_name
        elif not is_folder and source_path:
            clean_sp = str(source_path).split("::", 1)[-1].replace("\\", "/")
            sp_stem = os.path.splitext(os.path.basename(clean_sp))[0]
            self.original_name = sp_stem if sp_stem else current_name
        else:
            self.original_name = current_name
        self.keywords = keywords
        if not self.file_date and not self.is_folder and self.source_path:
            from app.core.pattern_formatter import resolve_disk_file_date

            self.file_date = resolve_disk_file_date(
                self.source_path, base_dir=self.base_dir
            )
        self._last_collision_state: str | None = None

    def _extract_file_metadata(
        self, f: Any, seq: int
    ) -> tuple[dict[str, Any], str, str, str, dict[str, Any] | None]:
        """Extract metadata dict, fallback filename, key, folder, and info dict from a file item."""
        from app.core.pattern_formatter import resolve_disk_file_date

        if isinstance(f, str):
            key = f
            stem, ext = os.path.splitext(os.path.basename(f))
            cat = self.category
            date = self.file_date or resolve_disk_file_date(f, base_dir=self.base_dir)
            info = None
            folder = self.category
            fallback = f"{stem}{ext}" if ext else stem
            meta = {
                "original": stem,
                "stem": stem,
                "extension": ext,
                "category": cat,
                "date": date,
                "seq": seq,
                "base_dir": self.base_dir,
                "filepath": f,
            }
            return meta, fallback, key, folder, info

        if isinstance(f, dict):
            key = (
                f.get("key")
                or f.get("target_filename")
                or f.get("name")
                or f.get("original")
                or ""
            )
            info = f.get("info") if isinstance(f.get("info"), dict) else f
            if not key and info and isinstance(info, dict):
                key = info.get("target_filename") or info.get("key", "")

            item_fp = (
                f.get("filepath")
                or f.get("source_path")
                or (
                    (info.get("filepath") or info.get("source_path"))
                    if isinstance(info, dict)
                    else None
                )
            )
            if not item_fp and key and self.base_dir:
                item_fp = os.path.join(self.base_dir, str(key))

            immutable_src = (
                f.get("source_path")
                or (info.get("source_path") if isinstance(info, dict) else None)
                or f.get("filepath")
                or (info.get("filepath") if isinstance(info, dict) else None)
            )
            imm_stem = ""
            imm_ext: str | None = None
            if immutable_src:
                clean_imm = str(immutable_src).split("::", 1)[-1].replace("\\", "/")
                imm_stem, imm_ext = os.path.splitext(os.path.basename(clean_imm))

            stem = (
                f.get("original") or f.get("current_name") or f.get("stem") or imm_stem
            )
            ext = f.get("extension") if f.get("extension") is not None else f.get("ext")
            if ext is None and imm_stem and imm_ext is not None:
                ext = imm_ext
            if not stem or ext is None:
                base = os.path.basename(str(key or (item_fp or "")).replace("\\", "/"))
                base_stem, base_ext = os.path.splitext(base)
                if not stem:
                    stem = base_stem
                if ext is None:
                    ext = base_ext

            folder = (
                f.get("folder")
                or f.get("category")
                or (info.get("folder") if isinstance(info, dict) else None)
                or self.category
            )
            date = (
                f.get("date")
                or f.get("file_date")
                or (
                    (info.get("date") or info.get("file_date"))
                    if isinstance(info, dict)
                    else None
                )
                or resolve_disk_file_date(
                    str(item_fp) if item_fp else None,
                    base_dir=(
                        info.get("source_root")
                        if isinstance(info, dict) and info.get("source_root")
                        else self.base_dir
                    ),
                )
                or self.file_date
            )
            item_kw = str(
                f.get("keywords")
                or (info.get("keywords") if isinstance(info, dict) else "")
                or ""
            )
            seq_val = f.get("seq", seq)
            fallback = f"{stem}{ext}" if ext else stem
            meta = {
                "original": stem,
                "stem": stem,
                "keywords": item_kw,
                "extension": ext,
                "category": folder,
                "date": date,
                "seq": seq_val,
                "base_dir": self.base_dir,
                "filepath": item_fp,
            }
            return meta, fallback, key, folder, info

        key_str = str(f)
        stem, ext = os.path.splitext(os.path.basename(key_str))
        meta = {
            "original": stem,
            "stem": stem,
            "extension": ext,
            "category": self.category,
            "date": self.file_date,
            "seq": seq,
            "base_dir": self.base_dir,
        }
        return meta, key_str, key_str, self.category, None

    def get_batch_previews(self, pattern_str: str) -> list[str]:
        """Calculate sequential seq numbering and preview token substitution for each checked file."""
        if not self.files:
            return []
        from app.core.pattern_formatter import PatternTokenFormatter

        previews = []
        for idx, f in enumerate(self.files):
            file_seq = self.seq + idx
            meta, fallback, _, _, _ = self._extract_file_metadata(f, file_seq)
            item_fp = meta.get("filepath")
            formatted = PatternTokenFormatter.format_pattern(
                pattern=pattern_str,
                metadata=meta,
                seq=file_seq,
                fallback_original=fallback,
                file_path=str(item_fp) if item_fp else None,
            )
            previews.append(formatted)
        return previews

    def _evaluate_preview(self, pattern_str: str) -> str:
        """Evaluate formatted pattern string for live preview."""
        if self.files:
            previews = self.get_batch_previews(pattern_str)
            if not previews:
                return ""
            if len(previews) == 1:
                return previews[0]
            if len(previews) <= 3:
                return ", ".join(previews)
            return f"{previews[0]}, {previews[1]}, ... (+{len(previews) - 2} more)"

        from app.core.pattern_formatter import PatternTokenFormatter

        source_stem = (
            self.current_name
            if self.is_folder
            else (self.original_name or self.current_name)
        )
        metadata = {
            "original": source_stem,
            "stem": source_stem,
            "keywords": self.keywords,
            "extension": self.extension,
            "category": self.category,
            "date": self.file_date,
            "seq": self.seq,
            "base_dir": self.base_dir,
        }
        fallback = f"{source_stem}{self.extension}" if self.extension else source_stem
        if self.is_folder and ("/" in pattern_str or "\\" in pattern_str):
            if _is_absolute_path(pattern_str):
                return pattern_str
            segments = [
                seg for seg in pattern_str.replace("\\", "/").split("/") if seg != ""
            ]
            rendered_segments: list[str] = []
            for seg in segments:
                if PatternTokenFormatter.parse_tokens(seg):
                    rendered_segments.append(
                        PatternTokenFormatter.format_pattern(
                            pattern=seg,
                            metadata=metadata,
                            seq=self.seq,
                            fallback_original=fallback,
                            file_path=None,
                        )
                    )
                else:
                    rendered_segments.append(seg)
            return "/".join(rendered_segments)

        return PatternTokenFormatter.format_pattern(
            pattern=pattern_str,
            metadata=metadata,
            seq=self.seq,
            fallback_original=fallback,
            file_path=None if self.is_folder else self.source_path,
        )

    def compose(self) -> ComposeResult:
        """Compose modal dialog children."""
        with ModalBox(classes="modal-box"):
            with Vertical(classes="modal-body"):
                yield Heading(
                    self.modal_title,
                    level=1,
                    classes="modal-title",
                    id="modal-title",
                )
                if self.files:
                    yield Label(
                        f"Batch renaming {len(self.files)} files. Sequential index starts at {self.seq:02d}.",
                        classes="modal-subtitle",
                    )
                elif not self.is_folder:
                    orig_full = (
                        f"{self.original_name}{self.extension}"
                        if self.original_name
                        else ""
                    )
                    if orig_full and self.original_name != self.current_name:
                        subtitle_txt = (
                            f"Original file: {orig_full} • Extension '{self.extension}' is locked unless modified in template"
                            if self.extension
                            else f"Original file: {orig_full}"
                        )
                        yield Label(subtitle_txt, classes="modal-subtitle")
                    elif self.extension:
                        yield Label(
                            f"Extension '{self.extension}' is locked unless modified in template",
                            classes="modal-subtitle",
                        )
                yield Label(
                    "Tokens: {date}, {category}, {stem}, {keywords}, {original}, {extension}, {seq}",
                    classes="token-help",
                )
                inp = Input(
                    value=self.current_name,
                    placeholder="Enter new name or pattern (e.g. {date}_{category}_{original})...",
                    id="input-name",
                )
                inp.tooltip = "Enter new file or folder name or pattern template"
                yield inp

                yield Heading(
                    "Optional Destination Path Override (relative or absolute):",
                    level=2,
                )
                dest_inp = Input(
                    value=self.destination_override,
                    placeholder="e.g. /external/backup, D:\\Archive, or subcategory...",
                    id="input-destination",
                )
                dest_inp.tooltip = "Enter optional destination directory path override (absolute or relative)"
                yield dest_inp

                yield Label("", id="warning-collision", classes="modal-warning")

                yield Label(
                    f"Preview: {self._evaluate_preview(self.current_name)}",
                    id="label-preview",
                    classes="modal-preview",
                )
            with Horizontal(classes="button-row"):
                if not self.is_folder and not self.files:
                    btn_reset = Button(
                        "Reset to Original",
                        id="btn-reset-original",
                        variant="default",
                    )
                    btn_reset.tooltip = "Restore original source filename and clear rename suggestion [Alt+R]"
                    yield btn_reset
                btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
                btn_cancel.tooltip = "Cancel rename action and close dialog"
                yield btn_cancel
                btn_confirm = Button("Rename", id="btn-confirm", variant="primary")
                btn_confirm.tooltip = "Confirm renaming action"
                yield btn_confirm

    def on_mount(self) -> None:
        """Focus input field on mount and emit screen reader announcement."""
        super().on_mount()
        self.query_one("#input-name", Input).focus()
        self.announce(
            f"Opened rename dialog for '{self.modal_title}'. Enter new name or pattern and press Enter or click Rename."
        )
        self._check_collision_and_update_ui()

    def _validate_path_security(self, path_str: str) -> str | None:
        """Validate path string for directory traversal and illegal characters."""
        if not path_str:
            return None
        if "\x00" in path_str:
            return "Null bytes are not permitted in paths."
        segments = re.split(r"[/\\]+", path_str)
        if ".." in segments:
            return "Directory traversal ('..') segments are not permitted."
        return None

    def _check_collision_and_update_ui(self) -> tuple[bool, str | None]:
        """Run live collision check and path validation across plan and filesystem.

        Returns (is_blocked, message).
        """
        try:
            name_inp = self.query_one("#input-name", Input)
            name_val = name_inp.value.strip()
        except Exception:
            return False, None

        try:
            dest_inp = self.query_one("#input-destination", Input)
            dest_val = dest_inp.value.strip()
        except Exception:
            dest_val = ""

        # Check directory traversal segments (..) and null bytes
        err = self._validate_path_security(name_val) or self._validate_path_security(
            dest_val
        )
        if err:
            msg = f"⚠️ Security Error: {err}"
            self._set_collision_warning(msg, is_error=True)
            if self._last_collision_state != msg:
                self.announce(msg)
                self._last_collision_state = msg
            return True, err

        # Check illegal characters in filename
        if self.files:
            batch_previews = self.get_batch_previews(name_val) if name_val else []
            for formatted_name in batch_previews:
                if any(c in formatted_name for c in '<>:"/\\|?*\x00'):
                    msg = "Filename contains illegal filesystem characters."
                    self._set_collision_warning(
                        f"⚠️ Validation Error: {msg}", is_error=True
                    )
                    return True, msg
        else:
            formatted = self._evaluate_preview(name_val) if name_val else ""
            if self.extension and formatted and not formatted.endswith(self.extension):
                formatted_name = f"{formatted}{self.extension}"
            else:
                formatted_name = formatted

            if not self.is_folder and formatted_name:
                if any(c in formatted_name for c in '<>:"/\\|?*\x00'):
                    msg = "Filename contains illegal filesystem characters."
                    self._set_collision_warning(
                        f"⚠️ Validation Error: {msg}", is_error=True
                    )
                    return True, msg

        if dest_val:
            s_check = re.sub(r"^[a-zA-Z]:", "", dest_val)
            if any(c in s_check for c in '<>"|?*\x00'):
                msg = "Destination path contains illegal characters."
                self._set_collision_warning(f"⚠️ Validation Error: {msg}", is_error=True)
                return True, msg
            if not _is_absolute_path(dest_val):
                try:
                    validate_target_path(dest_val)
                except ValueError as ve:
                    msg = str(ve)
                    self._set_collision_warning(
                        f"⚠️ Validation Error: {msg}", is_error=True
                    )
                    return True, msg

        collision_msg: str | None = None

        if self.is_folder:
            if not dest_val and name_val and not _is_absolute_path(name_val):
                try:
                    validate_target_path(name_val)
                except ValueError as ve:
                    msg = str(ve)
                    self._set_collision_warning(
                        f"⚠️ Validation Error: {msg}", is_error=True
                    )
                    return True, msg
            raw_target = dest_val if dest_val else formatted_name
            if raw_target and not _is_absolute_path(raw_target):
                try:
                    validate_target_path(raw_target)
                except ValueError as ve:
                    msg = str(ve)
                    self._set_collision_warning(
                        f"⚠️ Validation Error: {msg}", is_error=True
                    )
                    return True, msg

            if raw_target:
                if (
                    dest_val
                    or _is_absolute_path(raw_target)
                    or "/" in raw_target
                    or "\\" in raw_target
                ):
                    target_folder = (
                        raw_target
                        if _is_absolute_path(raw_target)
                        else raw_target.replace("\\", "/").strip("/")
                    )
                elif (
                    "/" in self.category
                    and not _is_absolute_path(self.category)
                    and not (self.plan and self.category in self.plan)
                ):
                    parent_prefix = self.category.rsplit("/", 1)[0]
                    target_folder = f"{parent_prefix}/{raw_target}"
                else:
                    target_folder = raw_target
            else:
                target_folder = ""

            orig_folder = self.category or self.current_name
            if target_folder and target_folder != orig_folder:
                if (
                    self.plan
                    and resolve_plan_folder_dict(self.plan, target_folder, create=False)
                    is not None
                ):
                    collision_msg = (
                        f"Folder '{target_folder}' already exists in plan. "
                        "Confirming will merge folder contents safely."
                    )
                elif self.base_dir or _is_absolute_path(target_folder):
                    disk_path = (
                        target_folder
                        if _is_absolute_path(target_folder)
                        else os.path.join(self.base_dir or "", target_folder)
                    )
                    if os.path.isdir(disk_path):
                        collision_msg = (
                            f"Target folder '{target_folder}' exists on disk. "
                            "Contents will merge safely."
                        )
        elif self.files:
            if batch_previews:
                batch_resolved: list[
                    tuple[str, str, str, str | None, dict[str, Any] | None]
                ] = []
                batch_info_ids: set[int] = set()
                batch_fps_norm: set[str] = set()

                for idx, item in enumerate(self.files):
                    if idx >= len(batch_previews):
                        break
                    _meta, _fb, _key, item_folder, item_info = (
                        self._extract_file_metadata(item, self.seq + idx)
                    )
                    fn = batch_previews[idx]
                    eff_folder = str(dest_val if dest_val else (item_folder or ""))
                    norm_folder = (
                        eff_folder
                        if _is_absolute_path(eff_folder)
                        else eff_folder.replace("\\", "/").strip("/")
                    )
                    item_fp_raw = _meta.get("filepath")
                    item_fp_str = str(item_fp_raw) if item_fp_raw else None
                    if isinstance(item_info, dict):
                        batch_info_ids.add(id(item_info))
                        for src_k in ("filepath", "source_path"):
                            if item_info.get(src_k):
                                batch_fps_norm.add(
                                    os.path.normcase(
                                        os.path.normpath(str(item_info[src_k]))
                                    )
                                )
                    if isinstance(item, dict):
                        for src_k in ("filepath", "source_path"):
                            if item.get(src_k):
                                batch_fps_norm.add(
                                    os.path.normcase(os.path.normpath(str(item[src_k])))
                                )
                    if item_fp_str:
                        batch_fps_norm.add(
                            os.path.normcase(os.path.normpath(item_fp_str))
                        )
                    batch_resolved.append(
                        (eff_folder, norm_folder, fn, item_fp_str, item_info)
                    )

                # 1. Group duplicates per resolved destination folder
                seen_per_folder: dict[str, set[str]] = {}
                dup_name: str | None = None
                dup_folder: str = ""
                for eff_folder, norm_folder, fn, _fp, _info in batch_resolved:
                    fld_bucket = seen_per_folder.setdefault(norm_folder.lower(), set())
                    if fn.lower() in fld_bucket:
                        dup_name = fn
                        dup_folder = eff_folder
                        break
                    fld_bucket.add(fn.lower())

                if dup_name:
                    collision_msg = (
                        f"Collision detected: Multiple files resolve to duplicate name '{dup_name}' "
                        f"in '{dup_folder or 'root'}'. Names will be disambiguated upon renaming."
                    )

                # 2. Inspect every checked target folder in self.plan
                if not collision_msg and self.plan:
                    for eff_folder, _norm_folder, fn, _fp, _info in batch_resolved:
                        folder_dict = resolve_plan_folder_dict(
                            self.plan, eff_folder, create=False
                        )
                        if not isinstance(folder_dict, dict):
                            continue
                        for sib_key, sib_node in folder_dict.items():
                            if isinstance(sib_node, dict):
                                if id(sib_node) in batch_info_ids:
                                    continue
                                sib_fp = sib_node.get("filepath") or sib_node.get(
                                    "source_path"
                                )
                                if (
                                    sib_fp
                                    and os.path.normcase(os.path.normpath(str(sib_fp)))
                                    in batch_fps_norm
                                ):
                                    continue
                                sib_tf = sib_node.get("target_filename")
                                if sib_key.lower() == fn.lower() or (
                                    sib_tf and str(sib_tf).lower() == fn.lower()
                                ):
                                    collision_msg = (
                                        f"Collision detected: '{fn}' already exists in "
                                        f"'{eff_folder or 'root'}'. Overwrite will be blocked (names disambiguated)."
                                    )
                                    break
                            elif sib_key.lower() == fn.lower():
                                collision_msg = (
                                    f"Collision detected: '{fn}' already exists in "
                                    f"'{eff_folder or 'root'}'. Overwrite will be blocked (names disambiguated)."
                                )
                                break
                        if collision_msg:
                            break

                # 3. Run os.path.lexists disk checks per destination folder
                if not collision_msg:
                    for (
                        eff_folder,
                        _norm_folder,
                        fn,
                        item_fp_str,
                        _info,
                    ) in batch_resolved:
                        if not (
                            self.base_dir
                            or (eff_folder and _is_absolute_path(eff_folder))
                        ):
                            continue
                        if eff_folder and _is_absolute_path(eff_folder):
                            dest_file_path = os.path.normpath(
                                os.path.join(eff_folder, fn)
                            )
                        elif self.base_dir:
                            dest_file_path = os.path.normpath(
                                os.path.join(self.base_dir, eff_folder, fn)
                            )
                        else:
                            dest_file_path = None

                        if dest_file_path and os.path.lexists(dest_file_path):
                            is_same = False
                            if item_fp_str and os.path.lexists(item_fp_str):
                                try:
                                    is_same = os.path.samefile(
                                        dest_file_path, item_fp_str
                                    )
                                except OSError:
                                    is_same = os.path.normcase(
                                        os.path.abspath(dest_file_path)
                                    ) == os.path.normcase(os.path.abspath(item_fp_str))
                            if not is_same:
                                collision_msg = (
                                    f"Collision detected: File '{fn}' exists on disk at destination. "
                                    "Overwrite will be blocked (names disambiguated)."
                                )
                                break
        else:
            target_folder = dest_val if dest_val else self.category
            if formatted_name:
                if self.plan:
                    folder_dict = resolve_plan_folder_dict(
                        self.plan, target_folder, create=False
                    )
                    if isinstance(folder_dict, dict):
                        for sib_key, existing_node in folder_dict.items():
                            if isinstance(existing_node, dict):
                                sib_fp = existing_node.get(
                                    "filepath"
                                ) or existing_node.get("source_path")
                                if (
                                    sib_fp
                                    and self.source_path
                                    and os.path.normcase(os.path.normpath(str(sib_fp)))
                                    == os.path.normcase(
                                        os.path.normpath(str(self.source_path))
                                    )
                                ):
                                    continue
                                sib_tf = existing_node.get("target_filename")
                                if sib_key.lower() == formatted_name.lower() or (
                                    sib_tf
                                    and str(sib_tf).lower() == formatted_name.lower()
                                ):
                                    collision_msg = (
                                        f"Collision detected: '{formatted_name}' already exists in "
                                        f"'{target_folder or 'root'}'. Overwrite will be blocked (names disambiguated)."
                                    )
                                    break
                            elif sib_key.lower() == formatted_name.lower():
                                collision_msg = (
                                    f"Collision detected: '{formatted_name}' already exists in "
                                    f"'{target_folder or 'root'}'. Overwrite will be blocked (names disambiguated)."
                                )
                                break

                if not collision_msg and (
                    self.base_dir
                    or (target_folder and _is_absolute_path(target_folder))
                ):
                    if target_folder and _is_absolute_path(target_folder):
                        dest_file_path = os.path.normpath(
                            os.path.join(target_folder, formatted_name)
                        )
                    elif self.base_dir:
                        dest_file_path = os.path.normpath(
                            os.path.join(self.base_dir, target_folder, formatted_name)
                        )
                    else:
                        dest_file_path = None

                    if dest_file_path and os.path.lexists(dest_file_path):
                        is_same = False
                        if self.source_path and os.path.lexists(self.source_path):
                            try:
                                is_same = os.path.samefile(
                                    dest_file_path, self.source_path
                                )
                            except OSError:
                                is_same = os.path.normcase(
                                    os.path.abspath(dest_file_path)
                                ) == os.path.normcase(os.path.abspath(self.source_path))
                        if not is_same:
                            collision_msg = (
                                f"Collision detected: File '{formatted_name}' exists on disk at destination. "
                                "Overwrite will be blocked (names disambiguated)."
                            )

        if collision_msg:
            full_warn = f"⚠️ {collision_msg}"
            self._set_collision_warning(full_warn, is_error=False)
            if self._last_collision_state != full_warn:
                self.announce(full_warn)
                self._last_collision_state = full_warn
            return False, collision_msg
        else:
            self._set_collision_warning("", is_error=False)
            self._last_collision_state = None
            return False, None

    @on(Input.Changed, "#input-name")
    def on_input_changed(self, event: Input.Changed) -> None:
        """Update live preview and collision status on input value change."""
        try:
            preview_str = self._evaluate_preview(event.value)
            lbl = self.query_one("#label-preview", Label)
            lbl.update(f"Preview: {preview_str}")
        except Exception:
            pass
        self._check_collision_and_update_ui()

    @on(Input.Changed, "#input-destination")
    def on_destination_changed(self, event: Input.Changed) -> None:
        """Update collision status on destination path override change."""
        self._check_collision_and_update_ui()

    @on(Button.Pressed, "#btn-confirm")
    def action_confirm(self) -> None:
        """Confirm renaming action."""
        is_blocked, err = self._check_collision_and_update_ui()
        if is_blocked:
            self.announce(f"Cannot confirm rename: {err}")
            return

        val = self.query_one("#input-name", Input).value.strip()
        dest_val = self.query_one("#input-destination", Input).value.strip()

        if self.files:
            if not val and not dest_val:
                self.announce("Cancelled rename action.")
                self.dismiss(None)
                return

            batch_previews = self.get_batch_previews(val)
            batch_items = []
            for idx, f in enumerate(self.files):
                file_seq = self.seq + idx
                _meta, fallback, key, folder, info = self._extract_file_metadata(
                    f, file_seq
                )
                formatted_name = (
                    batch_previews[idx] if idx < len(batch_previews) else fallback
                )
                target_folder = dest_val if dest_val else folder
                batch_items.append(
                    {
                        "file": f,
                        "key": key,
                        "old_name": key,
                        "new_name": formatted_name,
                        "folder": target_folder,
                        "old_folder": folder,
                        "info": info,
                    }
                )
            result = RenameResult(
                val,
                destination_override=dest_val if dest_val else None,
                batch_items=batch_items,
                is_batch=True,
            )
            dest_desc = f" with destination override '{dest_val}'" if dest_val else ""
            self.announce(
                f"Confirmed batch rename for {len(batch_items)} files{dest_desc}."
            )
            self.dismiss(result)
            return

        formatted = self._evaluate_preview(val) if val else ""

        if formatted:
            result = RenameResult(
                formatted, destination_override=dest_val if dest_val else None
            )
            dest_desc = f" with destination override '{dest_val}'" if dest_val else ""
            self.announce(f"Confirmed rename to '{formatted}'{dest_desc}.")
            self.dismiss(result)
        else:
            self.announce("Cancelled rename action.")
            self.dismiss(None)

    @on(Button.Pressed, "#btn-reset-original")
    def action_reset_original(self) -> None:
        """Reset single-file rename input to original source stem and confirm revert."""
        if self.is_folder or self.files:
            return
        orig_stem = self.original_name or self.current_name
        if not orig_stem:
            return
        with contextlib.suppress(Exception):
            self.query_one("#input-name", Input).value = orig_stem
            self.query_one("#input-destination", Input).value = ""
            lbl = self.query_one("#label-preview", Label)
            lbl.update(f"Preview: {self._evaluate_preview(orig_stem)}")
        restored = f"{orig_stem}{self.extension}" if self.extension else orig_stem
        result = RenameResult(
            restored,
            destination_override=None,
            is_reset=True,
        )
        self.announce(f"Reset filename to original '{restored}'.")
        self.dismiss(result)

    @on(Button.Pressed, "#btn-cancel")
    def action_cancel(self) -> None:
        """Cancel renaming action."""
        self.announce("Cancelled rename action.")
        self.dismiss(None)

action_cancel()

Cancel renaming action.

Source code in app/ui/modals/edit.py
1012
1013
1014
1015
1016
@on(Button.Pressed, "#btn-cancel")
def action_cancel(self) -> None:
    """Cancel renaming action."""
    self.announce("Cancelled rename action.")
    self.dismiss(None)

action_confirm()

Confirm renaming action.

Source code in app/ui/modals/edit.py
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
@on(Button.Pressed, "#btn-confirm")
def action_confirm(self) -> None:
    """Confirm renaming action."""
    is_blocked, err = self._check_collision_and_update_ui()
    if is_blocked:
        self.announce(f"Cannot confirm rename: {err}")
        return

    val = self.query_one("#input-name", Input).value.strip()
    dest_val = self.query_one("#input-destination", Input).value.strip()

    if self.files:
        if not val and not dest_val:
            self.announce("Cancelled rename action.")
            self.dismiss(None)
            return

        batch_previews = self.get_batch_previews(val)
        batch_items = []
        for idx, f in enumerate(self.files):
            file_seq = self.seq + idx
            _meta, fallback, key, folder, info = self._extract_file_metadata(
                f, file_seq
            )
            formatted_name = (
                batch_previews[idx] if idx < len(batch_previews) else fallback
            )
            target_folder = dest_val if dest_val else folder
            batch_items.append(
                {
                    "file": f,
                    "key": key,
                    "old_name": key,
                    "new_name": formatted_name,
                    "folder": target_folder,
                    "old_folder": folder,
                    "info": info,
                }
            )
        result = RenameResult(
            val,
            destination_override=dest_val if dest_val else None,
            batch_items=batch_items,
            is_batch=True,
        )
        dest_desc = f" with destination override '{dest_val}'" if dest_val else ""
        self.announce(
            f"Confirmed batch rename for {len(batch_items)} files{dest_desc}."
        )
        self.dismiss(result)
        return

    formatted = self._evaluate_preview(val) if val else ""

    if formatted:
        result = RenameResult(
            formatted, destination_override=dest_val if dest_val else None
        )
        dest_desc = f" with destination override '{dest_val}'" if dest_val else ""
        self.announce(f"Confirmed rename to '{formatted}'{dest_desc}.")
        self.dismiss(result)
    else:
        self.announce("Cancelled rename action.")
        self.dismiss(None)

action_reset_original()

Reset single-file rename input to original source stem and confirm revert.

Source code in app/ui/modals/edit.py
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
@on(Button.Pressed, "#btn-reset-original")
def action_reset_original(self) -> None:
    """Reset single-file rename input to original source stem and confirm revert."""
    if self.is_folder or self.files:
        return
    orig_stem = self.original_name or self.current_name
    if not orig_stem:
        return
    with contextlib.suppress(Exception):
        self.query_one("#input-name", Input).value = orig_stem
        self.query_one("#input-destination", Input).value = ""
        lbl = self.query_one("#label-preview", Label)
        lbl.update(f"Preview: {self._evaluate_preview(orig_stem)}")
    restored = f"{orig_stem}{self.extension}" if self.extension else orig_stem
    result = RenameResult(
        restored,
        destination_override=None,
        is_reset=True,
    )
    self.announce(f"Reset filename to original '{restored}'.")
    self.dismiss(result)

compose()

Compose modal dialog children.

Source code in app/ui/modals/edit.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
def compose(self) -> ComposeResult:
    """Compose modal dialog children."""
    with ModalBox(classes="modal-box"):
        with Vertical(classes="modal-body"):
            yield Heading(
                self.modal_title,
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            if self.files:
                yield Label(
                    f"Batch renaming {len(self.files)} files. Sequential index starts at {self.seq:02d}.",
                    classes="modal-subtitle",
                )
            elif not self.is_folder:
                orig_full = (
                    f"{self.original_name}{self.extension}"
                    if self.original_name
                    else ""
                )
                if orig_full and self.original_name != self.current_name:
                    subtitle_txt = (
                        f"Original file: {orig_full} • Extension '{self.extension}' is locked unless modified in template"
                        if self.extension
                        else f"Original file: {orig_full}"
                    )
                    yield Label(subtitle_txt, classes="modal-subtitle")
                elif self.extension:
                    yield Label(
                        f"Extension '{self.extension}' is locked unless modified in template",
                        classes="modal-subtitle",
                    )
            yield Label(
                "Tokens: {date}, {category}, {stem}, {keywords}, {original}, {extension}, {seq}",
                classes="token-help",
            )
            inp = Input(
                value=self.current_name,
                placeholder="Enter new name or pattern (e.g. {date}_{category}_{original})...",
                id="input-name",
            )
            inp.tooltip = "Enter new file or folder name or pattern template"
            yield inp

            yield Heading(
                "Optional Destination Path Override (relative or absolute):",
                level=2,
            )
            dest_inp = Input(
                value=self.destination_override,
                placeholder="e.g. /external/backup, D:\\Archive, or subcategory...",
                id="input-destination",
            )
            dest_inp.tooltip = "Enter optional destination directory path override (absolute or relative)"
            yield dest_inp

            yield Label("", id="warning-collision", classes="modal-warning")

            yield Label(
                f"Preview: {self._evaluate_preview(self.current_name)}",
                id="label-preview",
                classes="modal-preview",
            )
        with Horizontal(classes="button-row"):
            if not self.is_folder and not self.files:
                btn_reset = Button(
                    "Reset to Original",
                    id="btn-reset-original",
                    variant="default",
                )
                btn_reset.tooltip = "Restore original source filename and clear rename suggestion [Alt+R]"
                yield btn_reset
            btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
            btn_cancel.tooltip = "Cancel rename action and close dialog"
            yield btn_cancel
            btn_confirm = Button("Rename", id="btn-confirm", variant="primary")
            btn_confirm.tooltip = "Confirm renaming action"
            yield btn_confirm

get_batch_previews(pattern_str)

Calculate sequential seq numbering and preview token substitution for each checked file.

Source code in app/ui/modals/edit.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
def get_batch_previews(self, pattern_str: str) -> list[str]:
    """Calculate sequential seq numbering and preview token substitution for each checked file."""
    if not self.files:
        return []
    from app.core.pattern_formatter import PatternTokenFormatter

    previews = []
    for idx, f in enumerate(self.files):
        file_seq = self.seq + idx
        meta, fallback, _, _, _ = self._extract_file_metadata(f, file_seq)
        item_fp = meta.get("filepath")
        formatted = PatternTokenFormatter.format_pattern(
            pattern=pattern_str,
            metadata=meta,
            seq=file_seq,
            fallback_original=fallback,
            file_path=str(item_fp) if item_fp else None,
        )
        previews.append(formatted)
    return previews

on_destination_changed(event)

Update collision status on destination path override change.

Source code in app/ui/modals/edit.py
920
921
922
923
@on(Input.Changed, "#input-destination")
def on_destination_changed(self, event: Input.Changed) -> None:
    """Update collision status on destination path override change."""
    self._check_collision_and_update_ui()

on_input_changed(event)

Update live preview and collision status on input value change.

Source code in app/ui/modals/edit.py
909
910
911
912
913
914
915
916
917
918
@on(Input.Changed, "#input-name")
def on_input_changed(self, event: Input.Changed) -> None:
    """Update live preview and collision status on input value change."""
    try:
        preview_str = self._evaluate_preview(event.value)
        lbl = self.query_one("#label-preview", Label)
        lbl.update(f"Preview: {preview_str}")
    except Exception:
        pass
    self._check_collision_and_update_ui()

on_mount()

Focus input field on mount and emit screen reader announcement.

Source code in app/ui/modals/edit.py
522
523
524
525
526
527
528
529
def on_mount(self) -> None:
    """Focus input field on mount and emit screen reader announcement."""
    super().on_mount()
    self.query_one("#input-name", Input).focus()
    self.announce(
        f"Opened rename dialog for '{self.modal_title}'. Enter new name or pattern and press Enter or click Rename."
    )
    self._check_collision_and_update_ui()

RenameResult

Bases: str

String subclass representing rename outcome with optional destination override.

Source code in app/ui/modals/edit.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class RenameResult(str):
    """String subclass representing rename outcome with optional destination override."""

    destination_override: str | None = None
    batch_items: list[dict[str, Any]] | None = None
    is_batch: bool = False
    is_reset: bool = False

    def __new__(
        cls,
        value: str,
        destination_override: str | None = None,
        batch_items: list[dict[str, Any]] | None = None,
        is_batch: bool = False,
        is_reset: bool = False,
    ):
        """Instantiate string value with optional destination path override."""
        instance = super().__new__(cls, value)
        instance.destination_override = destination_override
        instance.batch_items = batch_items
        instance.is_batch = is_batch
        instance.is_reset = is_reset
        return instance

    @property
    def name(self) -> str:
        """Return base string name value."""
        return str(self)

    def to_tuple(self) -> tuple[str, str | None]:
        """Return (name, destination_override) tuple representation."""
        return (str(self), self.destination_override)

name property

Return base string name value.

__new__(value, destination_override=None, batch_items=None, is_batch=False, is_reset=False)

Instantiate string value with optional destination path override.

Source code in app/ui/modals/edit.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def __new__(
    cls,
    value: str,
    destination_override: str | None = None,
    batch_items: list[dict[str, Any]] | None = None,
    is_batch: bool = False,
    is_reset: bool = False,
):
    """Instantiate string value with optional destination path override."""
    instance = super().__new__(cls, value)
    instance.destination_override = destination_override
    instance.batch_items = batch_items
    instance.is_batch = is_batch
    instance.is_reset = is_reset
    return instance

to_tuple()

Return (name, destination_override) tuple representation.

Source code in app/ui/modals/edit.py
60
61
62
def to_tuple(self) -> tuple[str, str | None]:
    """Return (name, destination_override) tuple representation."""
    return (str(self), self.destination_override)

UnsavedWorkspaceSwitchModal

Bases: ResponsiveModalScreen[bool]

Confirmation dialog protecting unsaved manual plan edits, empty folders, or file locks before switching workspaces.

Source code in app/ui/modals/edit.py
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
class UnsavedWorkspaceSwitchModal(ResponsiveModalScreen[bool]):
    """Confirmation dialog protecting unsaved manual plan edits, empty folders, or file locks before switching workspaces."""

    BINDINGS = [
        Binding("escape", "cancel", "Keep current workspace", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-box {
        border: thick $warning;
        max-width: 72;
    }
    .modal-title {
        color: $warning;
    }
    .switch-warning-detail {
        margin-top: 1;
        margin-bottom: 1;
        color: $text;
    }
    .button-row {
        layout: grid;
        grid-size: 2;
        grid-columns: 1fr 1fr;
        grid-gutter: 0 1;
        min-height: 3;
    }
    .button-row Button {
        width: 100%;
        min-width: 0;
        margin: 0;
    }
    Button:focus {
        border: heavy $accent;
        text-style: bold;
    }
    UnsavedWorkspaceSwitchModal {
        .modal-body {
            height: auto;
            overflow-y: auto;
        }
        .button-row {
            dock: none;
        }
        &.compact .switch-warning-detail {
            margin-top: 0;
            margin-bottom: 0;
        }
        &.compact .button-row Button {
            height: 1;
            min-height: 1;
            border: none;
        }
    }
    """

    def __init__(
        self,
        new_sources: list[str] | None = None,
        modification_summary: str = "",
    ):
        super().__init__()
        self.new_sources: list[str] = list(new_sources or [])
        self.modification_summary = modification_summary

    def compose(self) -> ComposeResult:
        """Compose unsaved workspace switch confirmation dialog."""
        target_str = (
            ", ".join(self.new_sources) if self.new_sources else "selected workspace"
        )
        detail = (
            f"Switching to {target_str} will clear {self.modification_summary}."
            if self.modification_summary
            else f"Switching to {target_str} will clear unsaved manual plan edits, manual empty folders, and file locks."
        )
        with ModalBox(classes="modal-box"):
            with Vertical(classes="modal-body"):
                yield Heading(
                    "Discard Unsaved Plan Edits?",
                    level=1,
                    classes="modal-title",
                    id="modal-title",
                )
                yield Static(
                    detail,
                    id="lbl-switch-warning",
                    classes="switch-warning-detail",
                    markup=False,
                )
            with Horizontal(classes="button-row"):
                btn_cancel = Button(
                    "Keep Current",
                    id="btn-cancel-switch",
                    variant="default",
                )
                btn_cancel.tooltip = (
                    "Cancel workspace switch and preserve manual plan edits and locks"
                )
                yield btn_cancel
                btn_confirm = Button(
                    "Discard & Switch",
                    id="btn-confirm-switch",
                    variant="warning",
                )
                btn_confirm.tooltip = (
                    "Discard unsaved plan edits and switch to the new workspace"
                )
                yield btn_confirm

    def on_mount(self) -> None:
        """Focus Keep Current button by default and emit screen reader announcement."""
        super().on_mount()
        with contextlib.suppress(Exception):
            self.query_one("#btn-cancel-switch", Button).focus()
        self.announce(
            "Unsaved manual plan modifications detected. Confirm before switching workspaces.",
            priority="assertive",
        )

    @on(Button.Pressed, "#btn-confirm-switch")
    def action_confirm(self) -> None:
        """Confirm discarding unsaved manual edits and switching workspaces."""
        self.announce(
            "Confirmed discarding unsaved plan edits and switching workspace."
        )
        self.dismiss(True)

    @on(Button.Pressed, "#btn-cancel-switch")
    def action_cancel(self) -> None:
        """Cancel workspace switch and preserve current manual edits."""
        self.announce("Cancelled workspace switch; kept unsaved plan edits.")
        self.dismiss(False)

action_cancel()

Cancel workspace switch and preserve current manual edits.

Source code in app/ui/modals/edit.py
2464
2465
2466
2467
2468
@on(Button.Pressed, "#btn-cancel-switch")
def action_cancel(self) -> None:
    """Cancel workspace switch and preserve current manual edits."""
    self.announce("Cancelled workspace switch; kept unsaved plan edits.")
    self.dismiss(False)

action_confirm()

Confirm discarding unsaved manual edits and switching workspaces.

Source code in app/ui/modals/edit.py
2456
2457
2458
2459
2460
2461
2462
@on(Button.Pressed, "#btn-confirm-switch")
def action_confirm(self) -> None:
    """Confirm discarding unsaved manual edits and switching workspaces."""
    self.announce(
        "Confirmed discarding unsaved plan edits and switching workspace."
    )
    self.dismiss(True)

compose()

Compose unsaved workspace switch confirmation dialog.

Source code in app/ui/modals/edit.py
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
def compose(self) -> ComposeResult:
    """Compose unsaved workspace switch confirmation dialog."""
    target_str = (
        ", ".join(self.new_sources) if self.new_sources else "selected workspace"
    )
    detail = (
        f"Switching to {target_str} will clear {self.modification_summary}."
        if self.modification_summary
        else f"Switching to {target_str} will clear unsaved manual plan edits, manual empty folders, and file locks."
    )
    with ModalBox(classes="modal-box"):
        with Vertical(classes="modal-body"):
            yield Heading(
                "Discard Unsaved Plan Edits?",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            yield Static(
                detail,
                id="lbl-switch-warning",
                classes="switch-warning-detail",
                markup=False,
            )
        with Horizontal(classes="button-row"):
            btn_cancel = Button(
                "Keep Current",
                id="btn-cancel-switch",
                variant="default",
            )
            btn_cancel.tooltip = (
                "Cancel workspace switch and preserve manual plan edits and locks"
            )
            yield btn_cancel
            btn_confirm = Button(
                "Discard & Switch",
                id="btn-confirm-switch",
                variant="warning",
            )
            btn_confirm.tooltip = (
                "Discard unsaved plan edits and switch to the new workspace"
            )
            yield btn_confirm

on_mount()

Focus Keep Current button by default and emit screen reader announcement.

Source code in app/ui/modals/edit.py
2446
2447
2448
2449
2450
2451
2452
2453
2454
def on_mount(self) -> None:
    """Focus Keep Current button by default and emit screen reader announcement."""
    super().on_mount()
    with contextlib.suppress(Exception):
        self.query_one("#btn-cancel-switch", Button).focus()
    self.announce(
        "Unsaved manual plan modifications detected. Confirm before switching workspaces.",
        priority="assertive",
    )

app.ui.modals.help

app.ui.modals.help

Keyboard shortcut cheat sheet and offline troubleshooting help dialogs.

ShortcutCheatSheetModal

Bases: ResponsiveModalScreen[None]

Modal dialog displaying categorized TUI keyboard shortcuts cheat sheet.

Source code in app/ui/modals/help.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
class ShortcutCheatSheetModal(ResponsiveModalScreen[None]):
    """Modal dialog displaying categorized TUI keyboard shortcuts cheat sheet."""

    BINDINGS = [
        Binding("escape", "close", "Close dialog", show=True),
        Binding("question_mark", "close", "Close dialog", show=False),
        Binding("f1", "close", "Close dialog", show=False),
    ]

    MODAL_CSS = """
    .section-title {
        text-style: bold;
        color: $primary-lighten-2;
        margin-top: 1;
        margin-bottom: 0;
    }
    .shortcut-row {
        margin-bottom: 0;
    }
    .button-row {
        min-height: 3;
    }
    Button:focus, Input:focus, Select:focus {
        border: heavy $accent;
        text-style: bold;
    }
    ShortcutCheatSheetModal {
        &.compact .section-title {
            margin-top: 0;
        }
    }
    """

    def compose(self) -> ComposeResult:
        """Compose shortcut cheat sheet modal children."""
        with ModalBox(classes="modal-box"):
            with Vertical(classes="modal-body"):
                yield Heading(
                    "Keyboard Shortcuts Cheat Sheet [? / F1]",
                    level=1,
                    classes="modal-title",
                    id="modal-title",
                )

                yield Heading(
                    "Navigation & Tree Controls:", level=2, classes="section-title"
                )
                yield Label(
                    "  j / k       - Move selection down / up (Vim motions)",
                    classes="shortcut-row",
                )
                yield Label(
                    "  h / l       - Collapse / expand folder or go to parent/child",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+L      - Lock / unlock focused, folder, or selected files",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+R      - Open active rule manager", classes="shortcut-row"
                )
                yield Label(
                    "  F2          - Rename focused node or batch-rename selected files",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+N      - Create new target folder", classes="shortcut-row"
                )
                yield Label(
                    "  + / -       - Rate classification quality (+ / -) on file or folder",
                    classes="shortcut-row",
                )

                yield Heading(
                    "Selection & Plan Inclusion:", level=2, classes="section-title"
                )
                yield Label(
                    "  Space       - Select / deselect file, folder, or visual range",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Shift+↑ / ↓ - Extend selection across adjacent tree rows",
                    classes="shortcut-row",
                )
                yield Label(
                    "  a           - Select or deselect all visible files",
                    classes="shortcut-row",
                )
                yield Label(
                    "  v           - Toggle visual range selection (j / k / ↑ / ↓)",
                    classes="shortcut-row",
                )
                yield Label(
                    "  x / i       - Exclude / include selected or focused files",
                    classes="shortcut-row",
                )
                yield Label(
                    "  r           - Reassign selected or focused files to a folder",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+F      - Search plan tree (badges, status:, route:, ext:, !, |)",
                    classes="shortcut-row",
                )

                yield Heading(
                    "Application Operations:", level=2, classes="section-title"
                )
                yield Label(
                    "  Ctrl+S      - Scan directory and generate plan",
                    classes="shortcut-row",
                )
                yield Label(
                    "  D           - Scan nested subfolders (Max Scan Depth 5)",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+Y      - Session history & audit log export",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+U      - Open Quarantine Vault dialog",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+E      - Execute sorting plan", classes="shortcut-row"
                )
                yield Label(
                    "  Ctrl+Z      - Undo last sorting session", classes="shortcut-row"
                )
                yield Label(
                    "  Ctrl+B      - Choose the folder to sort",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+O      - Open application settings", classes="shortcut-row"
                )
                yield Label(
                    "  Ctrl+G      - Open AI Model Manager dialog",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+W      - Open model onboarding wizard",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+X      - Launch PDF extraction strategy preview",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+D      - Open DropZone to sort dropped files",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+T / p  - Toggle background daemon pause / resume",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+A      - Open the audit report of the last run",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+K      - Open command palette overlay",
                    classes="shortcut-row",
                )
                yield Label(
                    "  G           - Create a sample dataset to try sorting on",
                    classes="shortcut-row",
                )

                yield Heading("Help & System:", level=2, classes="section-title")
                yield Label(
                    "  ? / F1      - Open shortcut cheat sheet", classes="shortcut-row"
                )
                yield Label(
                    "  Ctrl+Alt+K  - Toggle single-character keyboard shortcuts",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Escape      - Close modal dialog", classes="shortcut-row"
                )
                yield Label("  Ctrl+Q      - Quit application", classes="shortcut-row")

                yield Heading("Active Rule Manager:", level=2, classes="section-title")
                yield Label("  Space       - Toggle Rule", classes="shortcut-row")
                yield Label("  Enter       - Edit Rule", classes="shortcut-row")
                yield Label("  Delete      - Delete Rule", classes="shortcut-row")
                yield Label("  Ctrl+I / i  - Import Rules", classes="shortcut-row")
                yield Label("  Ctrl+E / e  - Export Rules", classes="shortcut-row")
                yield Label("  Ctrl+B / b  - Browse Templates", classes="shortcut-row")

                yield Heading("Audit Report:", level=2, classes="section-title")
                yield Label(
                    "  Ctrl+R      - Retry Selected Failed Item",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+T      - Retry All Failed Items",
                    classes="shortcut-row",
                )
                yield Label(
                    "  Ctrl+J      - Export JSON Report", classes="shortcut-row"
                )

                yield Heading("Command Palette:", level=2, classes="section-title")
                yield Label("  UP          - Move selection up", classes="shortcut-row")
                yield Label(
                    "  Down        - Move selection down", classes="shortcut-row"
                )

                yield Heading("Quarantine Vault:", level=2, classes="section-title")
                yield Label("  r           - Release file", classes="shortcut-row")
                yield Label("  d           - Dismiss item", classes="shortcut-row")
                yield Label("  i           - Re-inspect item", classes="shortcut-row")
                yield Label("  Ctrl+R      - Refresh vault", classes="shortcut-row")

                yield Heading("Rollback Confirm:", level=2, classes="section-title")
                yield Label("  Space       - Toggle selection", classes="shortcut-row")

            with Horizontal(classes="button-row"):
                btn_close = Button("Close", id="btn-close", variant="primary")
                btn_close.tooltip = "Close keyboard shortcut cheat sheet modal dialog"
                yield btn_close

    def on_mount(self) -> None:
        """Focus close button on mount and emit screen reader announcement."""
        super().on_mount()
        self.query_one("#btn-close", Button).focus()
        self.announce("Opened keyboard shortcut cheat sheet dialog.")

    @on(Button.Pressed, "#btn-close")
    def action_close(self) -> None:
        """Close shortcut cheat sheet modal."""
        self.announce("Closed keyboard shortcut cheat sheet dialog.")
        self.dismiss(None)

action_close()

Close shortcut cheat sheet modal.

Source code in app/ui/modals/help.py
346
347
348
349
350
@on(Button.Pressed, "#btn-close")
def action_close(self) -> None:
    """Close shortcut cheat sheet modal."""
    self.announce("Closed keyboard shortcut cheat sheet dialog.")
    self.dismiss(None)

compose()

Compose shortcut cheat sheet modal children.

Source code in app/ui/modals/help.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def compose(self) -> ComposeResult:
    """Compose shortcut cheat sheet modal children."""
    with ModalBox(classes="modal-box"):
        with Vertical(classes="modal-body"):
            yield Heading(
                "Keyboard Shortcuts Cheat Sheet [? / F1]",
                level=1,
                classes="modal-title",
                id="modal-title",
            )

            yield Heading(
                "Navigation & Tree Controls:", level=2, classes="section-title"
            )
            yield Label(
                "  j / k       - Move selection down / up (Vim motions)",
                classes="shortcut-row",
            )
            yield Label(
                "  h / l       - Collapse / expand folder or go to parent/child",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+L      - Lock / unlock focused, folder, or selected files",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+R      - Open active rule manager", classes="shortcut-row"
            )
            yield Label(
                "  F2          - Rename focused node or batch-rename selected files",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+N      - Create new target folder", classes="shortcut-row"
            )
            yield Label(
                "  + / -       - Rate classification quality (+ / -) on file or folder",
                classes="shortcut-row",
            )

            yield Heading(
                "Selection & Plan Inclusion:", level=2, classes="section-title"
            )
            yield Label(
                "  Space       - Select / deselect file, folder, or visual range",
                classes="shortcut-row",
            )
            yield Label(
                "  Shift+↑ / ↓ - Extend selection across adjacent tree rows",
                classes="shortcut-row",
            )
            yield Label(
                "  a           - Select or deselect all visible files",
                classes="shortcut-row",
            )
            yield Label(
                "  v           - Toggle visual range selection (j / k / ↑ / ↓)",
                classes="shortcut-row",
            )
            yield Label(
                "  x / i       - Exclude / include selected or focused files",
                classes="shortcut-row",
            )
            yield Label(
                "  r           - Reassign selected or focused files to a folder",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+F      - Search plan tree (badges, status:, route:, ext:, !, |)",
                classes="shortcut-row",
            )

            yield Heading(
                "Application Operations:", level=2, classes="section-title"
            )
            yield Label(
                "  Ctrl+S      - Scan directory and generate plan",
                classes="shortcut-row",
            )
            yield Label(
                "  D           - Scan nested subfolders (Max Scan Depth 5)",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+Y      - Session history & audit log export",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+U      - Open Quarantine Vault dialog",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+E      - Execute sorting plan", classes="shortcut-row"
            )
            yield Label(
                "  Ctrl+Z      - Undo last sorting session", classes="shortcut-row"
            )
            yield Label(
                "  Ctrl+B      - Choose the folder to sort",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+O      - Open application settings", classes="shortcut-row"
            )
            yield Label(
                "  Ctrl+G      - Open AI Model Manager dialog",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+W      - Open model onboarding wizard",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+X      - Launch PDF extraction strategy preview",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+D      - Open DropZone to sort dropped files",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+T / p  - Toggle background daemon pause / resume",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+A      - Open the audit report of the last run",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+K      - Open command palette overlay",
                classes="shortcut-row",
            )
            yield Label(
                "  G           - Create a sample dataset to try sorting on",
                classes="shortcut-row",
            )

            yield Heading("Help & System:", level=2, classes="section-title")
            yield Label(
                "  ? / F1      - Open shortcut cheat sheet", classes="shortcut-row"
            )
            yield Label(
                "  Ctrl+Alt+K  - Toggle single-character keyboard shortcuts",
                classes="shortcut-row",
            )
            yield Label(
                "  Escape      - Close modal dialog", classes="shortcut-row"
            )
            yield Label("  Ctrl+Q      - Quit application", classes="shortcut-row")

            yield Heading("Active Rule Manager:", level=2, classes="section-title")
            yield Label("  Space       - Toggle Rule", classes="shortcut-row")
            yield Label("  Enter       - Edit Rule", classes="shortcut-row")
            yield Label("  Delete      - Delete Rule", classes="shortcut-row")
            yield Label("  Ctrl+I / i  - Import Rules", classes="shortcut-row")
            yield Label("  Ctrl+E / e  - Export Rules", classes="shortcut-row")
            yield Label("  Ctrl+B / b  - Browse Templates", classes="shortcut-row")

            yield Heading("Audit Report:", level=2, classes="section-title")
            yield Label(
                "  Ctrl+R      - Retry Selected Failed Item",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+T      - Retry All Failed Items",
                classes="shortcut-row",
            )
            yield Label(
                "  Ctrl+J      - Export JSON Report", classes="shortcut-row"
            )

            yield Heading("Command Palette:", level=2, classes="section-title")
            yield Label("  UP          - Move selection up", classes="shortcut-row")
            yield Label(
                "  Down        - Move selection down", classes="shortcut-row"
            )

            yield Heading("Quarantine Vault:", level=2, classes="section-title")
            yield Label("  r           - Release file", classes="shortcut-row")
            yield Label("  d           - Dismiss item", classes="shortcut-row")
            yield Label("  i           - Re-inspect item", classes="shortcut-row")
            yield Label("  Ctrl+R      - Refresh vault", classes="shortcut-row")

            yield Heading("Rollback Confirm:", level=2, classes="section-title")
            yield Label("  Space       - Toggle selection", classes="shortcut-row")

        with Horizontal(classes="button-row"):
            btn_close = Button("Close", id="btn-close", variant="primary")
            btn_close.tooltip = "Close keyboard shortcut cheat sheet modal dialog"
            yield btn_close

on_mount()

Focus close button on mount and emit screen reader announcement.

Source code in app/ui/modals/help.py
340
341
342
343
344
def on_mount(self) -> None:
    """Focus close button on mount and emit screen reader announcement."""
    super().on_mount()
    self.query_one("#btn-close", Button).focus()
    self.announce("Opened keyboard shortcut cheat sheet dialog.")

TroubleshootingHelpModal

Bases: ResponsiveModalScreen[None]

Offline contextual troubleshooting viewer backed by bundled docs/troubleshooting.md.

Source code in app/ui/modals/help.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
class TroubleshootingHelpModal(ResponsiveModalScreen[None]):
    """Offline contextual troubleshooting viewer backed by bundled ``docs/troubleshooting.md``."""

    BINDINGS = [
        Binding("escape", "close", "Close dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-box {
        max-width: 84;
    }
    .button-row {
        min-height: 3;
    }
    .button-row Button {
        margin-left: 1;
    }
    Button:focus {
        border: heavy $accent;
        text-style: bold;
    }
    TroubleshootingHelpModal {
        background: rgba(0, 0, 0, 0.65);
        &.compact .modal-box, &.narrow .modal-box {
            max-height: 96%;
        }
        &.narrow .button-row Button {
            min-width: 0;
            padding: 0 1;
        }
    }
    """

    def __init__(
        self,
        help_url: str | None = None,
        docs_path: Path | str | None = None,
        anchor: str | None = None,
    ) -> None:
        super().__init__()
        from app.ui.notifications import TROUBLESHOOTING_URL

        if help_url is None and anchor:
            clean_anchor = anchor.lstrip("#").strip()
            resolved_url = f"{TROUBLESHOOTING_URL}#{clean_anchor}"
        else:
            resolved_url = help_url or TROUBLESHOOTING_URL

        self.help_url: str = resolved_url
        self.docs_path: Path | str | None = docs_path
        _, _, raw_anchor = self.help_url.partition("#")
        self.section_anchor: str = raw_anchor.strip().lower()
        (
            self.section_title,
            self.section_markdown,
            self.section_found,
        ) = extract_troubleshooting_section(self.help_url, docs_path=docs_path)

    def compose(self) -> ComposeResult:
        """Compose local troubleshooting section viewer and optional browser button."""
        with ModalBox(classes="modal-box"):
            yield Heading(
                f"Troubleshooting: {self.section_title}",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            with Vertical(classes="modal-body"):
                yield Markdown(self.section_markdown, id="help-markdown")
            with Horizontal(classes="button-row"):
                if self.help_url and self.help_url.startswith(("http:", "https:")):
                    btn_browser = Button(
                        "Open in Browser",
                        id="btn-open-browser",
                        variant="default",
                    )
                    btn_browser.tooltip = (
                        "Open online troubleshooting guide in external web browser"
                    )
                    yield btn_browser
                btn_close = Button("Close", id="btn-close", variant="primary")
                btn_close.tooltip = "Close troubleshooting help dialog"
                yield btn_close

    def on_mount(self) -> None:
        """Focus close button on mount and emit screen reader announcement."""
        super().on_mount()
        self.query_one("#btn-close", Button).focus()
        self.announce(f"Opened troubleshooting help: {self.section_title}.")

    @on(Button.Pressed, "#btn-open-browser")
    def action_open_browser(self) -> None:
        """Open online troubleshooting URL in user's default browser when requested."""
        open_url_fn = getattr(self.app, "open_url", None)
        if callable(open_url_fn) and self.help_url:
            open_url_fn(self.help_url)
        self.announce(f"Opened troubleshooting guide in browser: {self.help_url}")

    @on(Button.Pressed, "#btn-close")
    def action_close(self) -> None:
        """Close troubleshooting help modal."""
        self.announce("Closed troubleshooting help dialog.")
        self.dismiss(None)

action_close()

Close troubleshooting help modal.

Source code in app/ui/modals/help.py
453
454
455
456
457
@on(Button.Pressed, "#btn-close")
def action_close(self) -> None:
    """Close troubleshooting help modal."""
    self.announce("Closed troubleshooting help dialog.")
    self.dismiss(None)

action_open_browser()

Open online troubleshooting URL in user's default browser when requested.

Source code in app/ui/modals/help.py
445
446
447
448
449
450
451
@on(Button.Pressed, "#btn-open-browser")
def action_open_browser(self) -> None:
    """Open online troubleshooting URL in user's default browser when requested."""
    open_url_fn = getattr(self.app, "open_url", None)
    if callable(open_url_fn) and self.help_url:
        open_url_fn(self.help_url)
    self.announce(f"Opened troubleshooting guide in browser: {self.help_url}")

compose()

Compose local troubleshooting section viewer and optional browser button.

Source code in app/ui/modals/help.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
def compose(self) -> ComposeResult:
    """Compose local troubleshooting section viewer and optional browser button."""
    with ModalBox(classes="modal-box"):
        yield Heading(
            f"Troubleshooting: {self.section_title}",
            level=1,
            classes="modal-title",
            id="modal-title",
        )
        with Vertical(classes="modal-body"):
            yield Markdown(self.section_markdown, id="help-markdown")
        with Horizontal(classes="button-row"):
            if self.help_url and self.help_url.startswith(("http:", "https:")):
                btn_browser = Button(
                    "Open in Browser",
                    id="btn-open-browser",
                    variant="default",
                )
                btn_browser.tooltip = (
                    "Open online troubleshooting guide in external web browser"
                )
                yield btn_browser
            btn_close = Button("Close", id="btn-close", variant="primary")
            btn_close.tooltip = "Close troubleshooting help dialog"
            yield btn_close

on_mount()

Focus close button on mount and emit screen reader announcement.

Source code in app/ui/modals/help.py
439
440
441
442
443
def on_mount(self) -> None:
    """Focus close button on mount and emit screen reader announcement."""
    super().on_mount()
    self.query_one("#btn-close", Button).focus()
    self.announce(f"Opened troubleshooting help: {self.section_title}.")

extract_troubleshooting_section(help_url=None, docs_path=None)

Extract a Markdown section matching #anchor from bundled docs/troubleshooting.md.

Returns (section_title, section_markdown, found_exact).

Source code in app/ui/modals/help.py
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def extract_troubleshooting_section(
    help_url: str | None = None,
    docs_path: Path | str | None = None,
) -> tuple[str, str, bool]:
    """Extract a Markdown section matching ``#anchor`` from bundled ``docs/troubleshooting.md``.

    Returns ``(section_title, section_markdown, found_exact)``.
    """
    anchor = ""
    if help_url and "#" in help_url:
        _, _, raw_anchor = help_url.partition("#")
        anchor = raw_anchor.strip().lower()

    resolved_path = (
        Path(docs_path)
        if docs_path is not None
        else Path(get_base_path()) / "docs" / "troubleshooting.md"
    )

    try:
        raw_text = resolved_path.read_text(encoding="utf-8")
    except OSError:
        return _fallback_section(anchor)

    lines = [line for line in raw_text.splitlines() if not _IMAGE_LINE_RE.match(line)]
    if not lines:
        return _fallback_section(anchor)

    if not anchor:
        doc_title = "Troubleshooting Guide"
        for line in lines:
            match = _HEADING_RE.match(line)
            if match and len(match.group(1)) == 1:
                doc_title = match.group(2).strip()
                break
        return doc_title, "\n".join(lines).strip(), True

    in_fence = False
    capturing = False
    target_level = 0
    section_title = ""
    captured: list[str] = []

    for line in lines:
        if line.lstrip().startswith("```"):
            in_fence = not in_fence
            if capturing:
                captured.append(line)
            continue

        if not in_fence:
            match = _HEADING_RE.match(line)
            if match:
                level = len(match.group(1))
                heading_text = match.group(2).strip()
                if capturing:
                    if level <= target_level:
                        break
                    captured.append(line)
                    continue
                if slugify_heading(heading_text) == anchor:
                    capturing = True
                    target_level = level
                    section_title = heading_text.strip('"')
                    captured.append(line)
                    continue

        if capturing:
            captured.append(line)

    if not capturing or not captured:
        return _fallback_section(anchor)

    return section_title, "\n".join(captured).strip(), True

slugify_heading(heading)

Slugify a Markdown heading text into a GitHub-compatible anchor.

Source code in app/ui/modals/help.py
20
21
22
23
def slugify_heading(heading: str) -> str:
    """Slugify a Markdown heading text into a GitHub-compatible anchor."""
    slug = re.sub(r"[^\w\- ]", "", heading.strip().lower())
    return slug.replace(" ", "-")

app.ui.modals.models

app.ui.modals.models

Offline model manager dialog.

ModelManagerModal

Bases: ResponsiveModalScreen[None]

Modal screen for interactive local ONNX model management.

Source code in app/ui/modals/models.py
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
class ModelManagerModal(ResponsiveModalScreen[None]):
    """Modal screen for interactive local ONNX model management."""

    BINDINGS = [
        Binding("escape", "cancel", "Close dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-box {
        padding: 0 1;
        width: 92%;
        max-width: 88;
        max-height: 92%;
    }
    .modal-title {
        margin-bottom: 0;
    }
    .field-label {
        margin-top: 0;
        color: $text;
        text-style: bold;
    }
    .info-label {
        margin-top: 0;
        width: 100%;
        color: $text;
    }
    .path-label {
        margin-top: 0;
        width: 100%;
        max-height: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        color: $text;
    }
    .guidance-label {
        margin-top: 0;
        width: 100%;
        color: $warning;
    }
    .button-row {
        layout: grid;
        grid-size: 3;
        grid-columns: 1fr 1fr 1fr;
        grid-gutter: 0 1;
    }
    .button-row Button {
        width: 100%;
        min-width: 0;
        margin: 0;
    }
    Button:focus, Input:focus {
        border: heavy $accent;
        text-style: bold;
    }
    ModelManagerModal {
        &.compact .button-row {
            margin-top: 0;
        }
        &.narrow .button-row {
            grid-size: 2;
            grid-columns: 1fr 1fr;
        }
        &.compact .button-row Button {
            height: 1;
            min-height: 1;
            border: none;
        }
    }
    """

    def __init__(self, settings=None):
        super().__init__()
        self.settings = settings
        self._prev_is_downloading = False
        self._prev_status_text = ""

    def _resolve_model_dir(self) -> str:
        """Resolve primary model directory path."""
        from app.core.downloader import resolve_default_model_dir

        return resolve_default_model_dir()

    def compose(self) -> ComposeResult:
        """Compose modal dialog children."""
        with ModalBox(classes="modal-box"):
            yield Heading(
                "Interactive Model Management",
                level=1,
                classes="modal-title",
                id="modal-title",
            )

            with Vertical(classes="modal-body"):
                yield Heading(
                    "ONNX Semantic Embeddings (Managed Download):",
                    level=2,
                    classes="field-label",
                )
                yield Label(
                    "Status: Checking...",
                    id="lbl-model-status",
                    classes="info-label",
                    markup=False,
                )
                yield Label(
                    "Location: Checking...", id="lbl-model-path", classes="path-label"
                )
                yield Label(
                    "Size on Disk: 0 MB", id="lbl-model-size", classes="info-label"
                )
                yield Label(
                    "Verification: Checking...",
                    id="lbl-model-hash",
                    classes="info-label",
                )
                yield Label(
                    "",
                    id="lbl-ml-guidance",
                    classes="guidance-label",
                    markup=False,
                )

                yield Heading(
                    "Generative Folder Naming (Local GGUF):",
                    level=2,
                    classes="field-label",
                )
                yield Label(
                    "GGUF Status: Checking...",
                    id="lbl-gguf-status",
                    classes="info-label",
                    markup=False,
                )
                yield Label(
                    "GGUF Location: Checking...",
                    id="lbl-gguf-path",
                    classes="path-label",
                    markup=False,
                )
                yield Label(
                    "llama.cpp Runtime: Checking...",
                    id="lbl-gguf-runtime",
                    classes="info-label",
                    markup=False,
                )
                yield Label(
                    "",
                    id="lbl-gguf-guidance",
                    classes="guidance-label",
                    markup=False,
                )

                yield Heading(
                    "Download Progress & Throughput:", level=2, classes="field-label"
                )
                pb = ProgressBar(total=100, show_percentage=True, id="progress-bar")
                pb.tooltip = "Active model download percentage progress"
                yield pb

                lbl_progress = Label(
                    "Idle", id="lbl-progress-status", classes="info-label"
                )
                lbl_progress.tooltip = "Current download stage and throughput metrics"
                yield lbl_progress

                yield Heading("Network Proxy Options:", level=2, classes="field-label")
                proxy_val = getattr(self.settings, "PROXY", "") if self.settings else ""
                inp_proxy = Input(
                    value=proxy_val,
                    placeholder="http://proxy.example.com:8080",
                    id="input-proxy",
                )
                inp_proxy.tooltip = "HTTP/HTTPS proxy URL for model weight transfers"
                yield inp_proxy

            with Horizontal(classes="button-row"):
                btn_start = Button("Start Download", id="btn-start", variant="primary")
                btn_start.tooltip = "Start downloading local ONNX model weights"
                yield btn_start

                btn_cancel = Button("Cancel", id="btn-cancel-dl", variant="warning")
                btn_cancel.tooltip = "Cancel active model download thread"
                yield btn_cancel

                btn_retry = Button("Retry Download", id="btn-retry", variant="primary")
                btn_retry.tooltip = "Retry or restart model download"
                yield btn_retry

                btn_delete = Button("Delete Model", id="btn-delete", variant="error")
                btn_delete.tooltip = (
                    "Unload in-memory model instances and delete local files"
                )
                yield btn_delete

                btn_close = Button("Close", id="btn-close", variant="default")
                btn_close.tooltip = "Close Model Management dialog"
                yield btn_close

    def on_mount(self) -> None:
        """Focus initial input, set polling timer, and announce modal launch."""
        super().on_mount()
        self.query_one("#input-proxy", Input).focus()
        self.announce("Opened Model Management dialog.")
        self._refresh_ui_state()
        self.set_interval(0.2, self._poll_download_status)

    def _apply_proxy(self) -> str:
        p_val = self.query_one("#input-proxy", Input).value.strip()
        if self.settings:
            setattr(self.settings, "PROXY", p_val)
            if hasattr(self.settings, "_save"):
                try:
                    self.settings._save()
                except Exception:
                    pass
        from app.core.downloader import DownloadManager

        dm = DownloadManager.get_instance()
        dm.update_proxy(p_val)
        return p_val

    def _refresh_ui_state(self) -> None:
        """Update model file info labels, runtime guidance, and control button states."""
        from app.core.downloader import (
            DownloadManager,
            _inspect_model_bundle,
            get_ai_runtime_state,
            inspect_generative_runtime_state,
            verify_downloaded_model,
        )

        dm = DownloadManager.get_instance()

        model_dir = self._resolve_model_dir()
        runtime = get_ai_runtime_state(self.settings, model_dir=model_dir)
        gen_runtime = inspect_generative_runtime_state()
        onnx_available = bool(runtime.get("onnxruntime_available", False))
        onnx_file = os.path.join(model_dir, "model.onnx")
        tmp_file = os.path.join(model_dir, "model.onnx.tmp")

        lbl_status = self.query_one("#lbl-model-status", Label)
        lbl_path = self.query_one("#lbl-model-path", Label)
        lbl_size = self.query_one("#lbl-model-size", Label)
        lbl_hash = self.query_one("#lbl-model-hash", Label)
        lbl_ml = self.query_one("#lbl-ml-guidance", Label)

        lbl_path.update(f"Location: {model_dir}")

        if onnx_available:
            lbl_ml.update("")
            lbl_ml.display = False
        else:
            lbl_ml.update(
                "ML extra absent: install 'smart-autosorter[ml]' (uv sync --extra ml); TF-IDF fallback active."
            )
            lbl_ml.display = True

        lbl_gguf_status = self.query_one("#lbl-gguf-status", Label)
        lbl_gguf_path = self.query_one("#lbl-gguf-path", Label)
        lbl_gguf_runtime = self.query_one("#lbl-gguf-runtime", Label)
        lbl_gguf_guidance = self.query_one("#lbl-gguf-guidance", Label)

        gen_status_code = str(gen_runtime.get("status") or "NOT_CONFIGURED")
        if gen_runtime.get("ready"):
            gguf_size_mb = float(gen_runtime.get("size_bytes", 0) or 0) / (1024 * 1024)
            lbl_gguf_status.update(
                f"GGUF Status: Ready ({gguf_size_mb:.2f} MB verified)"
            )
            lbl_gguf_guidance.update("")
            lbl_gguf_guidance.display = False
        elif gen_status_code == "MISSING_ML_EXTRA":
            lbl_gguf_status.update("GGUF Status: Weights Present (ML Extra Missing)")
            lbl_gguf_guidance.update(str(gen_runtime.get("detail") or ""))
            lbl_gguf_guidance.display = True
        elif gen_status_code == "INVALID_WEIGHTS":
            lbl_gguf_status.update("GGUF Status: Invalid GGUF Weights")
            lbl_gguf_guidance.update(str(gen_runtime.get("detail") or ""))
            lbl_gguf_guidance.display = True
        else:
            lbl_gguf_status.update("GGUF Status: Not Configured (Local Setup Only)")
            lbl_gguf_guidance.update(str(gen_runtime.get("detail") or ""))
            lbl_gguf_guidance.display = True

        gguf_loc = (
            gen_runtime.get("gguf_file")
            or gen_runtime.get("model_path")
            or "Unconfigured"
        )
        lbl_gguf_path.update(f"GGUF Location: {gguf_loc}")
        lbl_gguf_runtime.update(
            "llama.cpp Runtime: Available"
            if gen_runtime.get("llama_cpp_available")
            else "llama.cpp Runtime: Not installed ('smart-autosorter[ml]')"
        )

        model_exists = os.path.exists(onnx_file) and os.path.getsize(onnx_file) > 0
        tmp_exists = os.path.exists(tmp_file)

        if model_exists:
            total_bytes = 0
            if os.path.isdir(model_dir):
                for entry in os.listdir(model_dir):
                    entry_p = os.path.join(model_dir, entry)
                    if os.path.isfile(entry_p):
                        total_bytes += os.path.getsize(entry_p)
            else:
                total_bytes = os.path.getsize(onnx_file)
            size_mb = total_bytes / (1024 * 1024)
            lbl_size.update(f"Size on Disk: {size_mb:.2f} MB")
            if verify_downloaded_model(model_dir):
                status_suffix = "" if onnx_available else " ([AI: Fallback])"
                lbl_status.update(f"Status: Downloaded & Present{status_suffix}")
                lbl_hash.update("Verification: Valid (Cryptographically Verified)")
            else:
                bundle_state, bundle_detail = _inspect_model_bundle(model_dir)
                if bundle_state == "incomplete":
                    lbl_status.update("Status: Incomplete Bundle")
                    lbl_hash.update(
                        f"Verification: Incomplete Warning ({bundle_detail})"
                    )
                else:
                    lbl_status.update("Status: Downloaded (Unverified)")
                    lbl_hash.update("Verification: Corrupted or Unverified")
        elif tmp_exists:
            size_mb = os.path.getsize(tmp_file) / (1024 * 1024)
            lbl_size.update(f"Size on Disk: {size_mb:.2f} MB (Incomplete)")
            lbl_status.update("Status: Downloading / Incomplete")
            lbl_hash.update("Verification: Pending Finalization")
        else:
            lbl_size.update("Size on Disk: 0 MB")
            lbl_status.update("Status: Missing (Not Downloaded)")
            lbl_hash.update("Verification: N/A")

        has_any_model_files = model_exists or (
            os.path.isdir(model_dir) and bool(os.listdir(model_dir))
        )
        is_dl = dm.state["is_downloading"]
        self.query_one("#btn-start", Button).disabled = is_dl
        self.query_one("#btn-cancel-dl", Button).disabled = not is_dl
        self.query_one("#btn-retry", Button).disabled = is_dl
        self.query_one("#btn-delete", Button).disabled = not (
            has_any_model_files or tmp_exists or is_dl
        )

    def _refresh_app_status(self) -> None:
        """Refresh parent application status bar badge if supported."""
        update_fn = getattr(self.app, "update_status", None)
        if callable(update_fn):
            try:
                update_fn()
            except (AttributeError, RuntimeError):
                return

    def _poll_download_status(self) -> None:
        """Periodic non-blocking timer callback to poll download status."""
        from app.core.downloader import DownloadManager, DownloadState

        dm = DownloadManager.get_instance()

        is_dl = dm.state["is_downloading"]
        prog = float(dm.state["progress"])
        status_text = str(dm.state["status_text"] or "")
        err = dm.state["error"]
        succ = dm.state["success"]
        status = dm.state.get("status")

        pb = self.query_one("#progress-bar", ProgressBar)
        pb.progress = min(100.0, max(0.0, prog * 100.0))

        is_cancelled = (
            status == DownloadState.CANCELLED
            or "cancelled" in status_text.lower()
            or (
                getattr(dm, "cancel_event", None) is not None
                and dm.cancel_event.is_set()
            )
        )

        lbl_prog = self.query_one("#lbl-progress-status", Label)
        if is_cancelled:
            lbl_prog.update("Download cancelled.")
        elif err:
            lbl_prog.update(f"Error: {err}")
        elif succ:
            lbl_prog.update("Download complete!")
        else:
            lbl_prog.update(
                status_text if status_text else ("Downloading..." if is_dl else "Idle")
            )

        if self._prev_is_downloading and not is_dl:
            if is_cancelled:
                self.announce("Model download cancelled.", priority="polite")
            elif succ:
                self.announce(
                    "Model download completed successfully.", priority="polite"
                )
            elif err:
                self.announce(f"Model download failed: {err}", priority="assertive")

        self._prev_is_downloading = is_dl
        self._prev_status_text = status_text

        self._refresh_ui_state()
        self._refresh_app_status()

    @on(Button.Pressed, "#btn-start")
    def action_start_download(self) -> None:
        """Start background model weight download."""
        p_val = self._apply_proxy()
        from app.core.downloader import DEFAULT_MODEL_URL, DownloadManager

        dm = DownloadManager.get_instance()
        model_dir = self._resolve_model_dir()
        try:
            dm.start_download(DEFAULT_MODEL_URL, model_dir, proxy=p_val)
            self._refresh_app_status()
            self.announce("Started model download.", priority="polite")
        except Exception as e:
            from app.ui.notifications import notify

            notify(f"Download error: {e}", type="error")
            self.announce(f"Download error: {e}", priority="assertive")

    @on(Button.Pressed, "#btn-cancel-dl")
    def action_cancel_download(self) -> None:
        """Cancel active model download thread."""
        from app.core.downloader import DownloadManager

        dm = DownloadManager.get_instance()
        dm.cancel_download()
        self._refresh_app_status()
        self.announce("Cancelled model download.", priority="polite")

    @on(Button.Pressed, "#btn-retry")
    def action_retry_download(self) -> None:
        """Retry model weight download operation."""
        p_val = self._apply_proxy()
        from app.core.downloader import DEFAULT_MODEL_URL, DownloadManager

        dm = DownloadManager.get_instance()
        if dm.state["is_downloading"]:
            dm.cancel_download()
        model_dir = self._resolve_model_dir()
        try:
            dm.start_download(DEFAULT_MODEL_URL, model_dir, proxy=p_val)
            self._refresh_app_status()
            self.announce("Retrying model download.", priority="polite")
        except Exception as e:
            from app.ui.notifications import notify

            notify(f"Download error: {e}", type="error")
            self.announce(f"Download error: {e}", priority="assertive")

    @on(Button.Pressed, "#btn-delete")
    def action_delete_model(self) -> None:
        """Asynchronously delete local model files."""
        from app.core.downloader import DownloadManager

        dm = DownloadManager.get_instance()
        model_dir = self._resolve_model_dir()

        def _on_done(success: bool, err: Exception | None):
            self._refresh_app_status()
            if success:
                self.announce("Model deleted successfully.", priority="polite")
            else:
                self.announce(f"Model deletion failed: {err}", priority="assertive")

        dm.delete_model_async(model_dir, on_done=_on_done)
        self.announce("Deleting model weights...", priority="polite")

    @on(Button.Pressed, "#btn-close")
    def action_close(self) -> None:
        """Close model management dialog."""
        self.announce("Closed Model Management dialog.")
        self.dismiss(None)

    action_cancel = action_close

action_cancel_download()

Cancel active model download thread.

Source code in app/ui/modals/models.py
442
443
444
445
446
447
448
449
450
@on(Button.Pressed, "#btn-cancel-dl")
def action_cancel_download(self) -> None:
    """Cancel active model download thread."""
    from app.core.downloader import DownloadManager

    dm = DownloadManager.get_instance()
    dm.cancel_download()
    self._refresh_app_status()
    self.announce("Cancelled model download.", priority="polite")

action_close()

Close model management dialog.

Source code in app/ui/modals/models.py
490
491
492
493
494
@on(Button.Pressed, "#btn-close")
def action_close(self) -> None:
    """Close model management dialog."""
    self.announce("Closed Model Management dialog.")
    self.dismiss(None)

action_delete_model()

Asynchronously delete local model files.

Source code in app/ui/modals/models.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
@on(Button.Pressed, "#btn-delete")
def action_delete_model(self) -> None:
    """Asynchronously delete local model files."""
    from app.core.downloader import DownloadManager

    dm = DownloadManager.get_instance()
    model_dir = self._resolve_model_dir()

    def _on_done(success: bool, err: Exception | None):
        self._refresh_app_status()
        if success:
            self.announce("Model deleted successfully.", priority="polite")
        else:
            self.announce(f"Model deletion failed: {err}", priority="assertive")

    dm.delete_model_async(model_dir, on_done=_on_done)
    self.announce("Deleting model weights...", priority="polite")

action_retry_download()

Retry model weight download operation.

Source code in app/ui/modals/models.py
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
@on(Button.Pressed, "#btn-retry")
def action_retry_download(self) -> None:
    """Retry model weight download operation."""
    p_val = self._apply_proxy()
    from app.core.downloader import DEFAULT_MODEL_URL, DownloadManager

    dm = DownloadManager.get_instance()
    if dm.state["is_downloading"]:
        dm.cancel_download()
    model_dir = self._resolve_model_dir()
    try:
        dm.start_download(DEFAULT_MODEL_URL, model_dir, proxy=p_val)
        self._refresh_app_status()
        self.announce("Retrying model download.", priority="polite")
    except Exception as e:
        from app.ui.notifications import notify

        notify(f"Download error: {e}", type="error")
        self.announce(f"Download error: {e}", priority="assertive")

action_start_download()

Start background model weight download.

Source code in app/ui/modals/models.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
@on(Button.Pressed, "#btn-start")
def action_start_download(self) -> None:
    """Start background model weight download."""
    p_val = self._apply_proxy()
    from app.core.downloader import DEFAULT_MODEL_URL, DownloadManager

    dm = DownloadManager.get_instance()
    model_dir = self._resolve_model_dir()
    try:
        dm.start_download(DEFAULT_MODEL_URL, model_dir, proxy=p_val)
        self._refresh_app_status()
        self.announce("Started model download.", priority="polite")
    except Exception as e:
        from app.ui.notifications import notify

        notify(f"Download error: {e}", type="error")
        self.announce(f"Download error: {e}", priority="assertive")

compose()

Compose modal dialog children.

Source code in app/ui/modals/models.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def compose(self) -> ComposeResult:
    """Compose modal dialog children."""
    with ModalBox(classes="modal-box"):
        yield Heading(
            "Interactive Model Management",
            level=1,
            classes="modal-title",
            id="modal-title",
        )

        with Vertical(classes="modal-body"):
            yield Heading(
                "ONNX Semantic Embeddings (Managed Download):",
                level=2,
                classes="field-label",
            )
            yield Label(
                "Status: Checking...",
                id="lbl-model-status",
                classes="info-label",
                markup=False,
            )
            yield Label(
                "Location: Checking...", id="lbl-model-path", classes="path-label"
            )
            yield Label(
                "Size on Disk: 0 MB", id="lbl-model-size", classes="info-label"
            )
            yield Label(
                "Verification: Checking...",
                id="lbl-model-hash",
                classes="info-label",
            )
            yield Label(
                "",
                id="lbl-ml-guidance",
                classes="guidance-label",
                markup=False,
            )

            yield Heading(
                "Generative Folder Naming (Local GGUF):",
                level=2,
                classes="field-label",
            )
            yield Label(
                "GGUF Status: Checking...",
                id="lbl-gguf-status",
                classes="info-label",
                markup=False,
            )
            yield Label(
                "GGUF Location: Checking...",
                id="lbl-gguf-path",
                classes="path-label",
                markup=False,
            )
            yield Label(
                "llama.cpp Runtime: Checking...",
                id="lbl-gguf-runtime",
                classes="info-label",
                markup=False,
            )
            yield Label(
                "",
                id="lbl-gguf-guidance",
                classes="guidance-label",
                markup=False,
            )

            yield Heading(
                "Download Progress & Throughput:", level=2, classes="field-label"
            )
            pb = ProgressBar(total=100, show_percentage=True, id="progress-bar")
            pb.tooltip = "Active model download percentage progress"
            yield pb

            lbl_progress = Label(
                "Idle", id="lbl-progress-status", classes="info-label"
            )
            lbl_progress.tooltip = "Current download stage and throughput metrics"
            yield lbl_progress

            yield Heading("Network Proxy Options:", level=2, classes="field-label")
            proxy_val = getattr(self.settings, "PROXY", "") if self.settings else ""
            inp_proxy = Input(
                value=proxy_val,
                placeholder="http://proxy.example.com:8080",
                id="input-proxy",
            )
            inp_proxy.tooltip = "HTTP/HTTPS proxy URL for model weight transfers"
            yield inp_proxy

        with Horizontal(classes="button-row"):
            btn_start = Button("Start Download", id="btn-start", variant="primary")
            btn_start.tooltip = "Start downloading local ONNX model weights"
            yield btn_start

            btn_cancel = Button("Cancel", id="btn-cancel-dl", variant="warning")
            btn_cancel.tooltip = "Cancel active model download thread"
            yield btn_cancel

            btn_retry = Button("Retry Download", id="btn-retry", variant="primary")
            btn_retry.tooltip = "Retry or restart model download"
            yield btn_retry

            btn_delete = Button("Delete Model", id="btn-delete", variant="error")
            btn_delete.tooltip = (
                "Unload in-memory model instances and delete local files"
            )
            yield btn_delete

            btn_close = Button("Close", id="btn-close", variant="default")
            btn_close.tooltip = "Close Model Management dialog"
            yield btn_close

on_mount()

Focus initial input, set polling timer, and announce modal launch.

Source code in app/ui/modals/models.py
216
217
218
219
220
221
222
def on_mount(self) -> None:
    """Focus initial input, set polling timer, and announce modal launch."""
    super().on_mount()
    self.query_one("#input-proxy", Input).focus()
    self.announce("Opened Model Management dialog.")
    self._refresh_ui_state()
    self.set_interval(0.2, self._poll_download_status)

app.ui.modals.quarantine

app.ui.modals.quarantine

Quarantine vault dialog.

QuarantineVaultModal

Bases: ResponsiveModalScreen[None]

Interactive Modal Screen for Compliance Quarantine Vault & Audit Log Review.

Source code in app/ui/modals/quarantine.py
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
class QuarantineVaultModal(ResponsiveModalScreen[None]):
    """Interactive Modal Screen for Compliance Quarantine Vault & Audit Log Review."""

    BINDINGS = [
        Binding("escape", "cancel", "Close quarantine vault", show=True),
        Binding("r", "release_selected", "Release file", show=True),
        Binding("d", "dismiss_selected", "Dismiss item", show=True),
        Binding("i", "reinspect_selected", "Re-inspect item", show=True),
        Binding("ctrl+r", "refresh_records", "Refresh vault", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .quarantine-modal-box {
        border: thick $warning;
        width: 95%;
        max-width: 110;
        min-width: 40;
        height: 92%;
        max-height: 92%;
        min-height: 20;
        layout: vertical;
    }
    .modal-body {
        height: 1fr;
    }
    .quarantine-title {
        text-style: bold;
        color: $warning;
        margin-bottom: 0;
    }
    .quarantine-subtitle {
        color: $text-muted;
        margin-bottom: 1;
    }
    .quarantine-filter-row {
        width: 100%;
        height: auto;
        margin-bottom: 1;
        layout: horizontal;
    }
    #quarantine-search-input {
        width: 1fr;
        margin-right: 1;
    }
    #quarantine-status-filter {
        width: 1fr;
        margin-right: 1;
    }
    #chk-select-all {
        width: auto;
        min-width: 16;
        height: 3;
    }
    #lbl-selection-count {
        width: 100%;
        text-style: bold;
        color: $accent;
    }
    .quarantine-content-split {
        height: 1fr;
        min-height: 8;
        layout: horizontal;
    }
    #quarantine-table-pane {
        width: 55%;
        height: 100%;
        min-height: 6;
        border: solid $primary;
        margin-right: 1;
    }
    #quarantine-table {
        width: 100%;
        height: 1fr;
        min-height: 5;
    }
    #quarantine-detail-pane {
        width: 45%;
        height: 100%;
        min-height: 6;
        border: solid $secondary;
        padding: 0 1;
        overflow-y: auto;
    }
    .quarantine-detail-header {
        text-style: bold;
        color: $accent;
        margin-bottom: 1;
    }
    .quarantine-detail-line {
        margin-bottom: 1;
    }
    .quarantine-audit-header {
        text-style: bold;
        color: $primary;
        margin-top: 1;
        margin-bottom: 1;
    }
    .quarantine-button-row {
        dock: bottom;
        width: 100%;
        margin-top: 1;
        layout: grid;
        grid-size: 3;
        grid-columns: 1fr 1fr 1fr;
        grid-gutter: 0 1;
        height: auto;
    }
    .quarantine-button-row Button {
        width: 100%;
        min-width: 0;
        margin: 0;
    }
    Button:focus, Input:focus, Select:focus, DataTable:focus, Checkbox:focus {
        border: heavy $accent;
        text-style: bold;
    }
    QuarantineVaultModal {
        background: rgba(0, 0, 0, 0.7);
        &.compact .quarantine-modal-box, &.narrow .quarantine-modal-box {
            padding: 0 1;
            width: 98%;
            height: 96%;
            max-height: 96%;
        }
        &.compact .quarantine-subtitle {
            margin-bottom: 0;
        }
        &.compact .quarantine-filter-row {
            margin-bottom: 0;
        }
        &.narrow .quarantine-content-split {
            layout: vertical;
            min-height: 0;
        }
        &.narrow #quarantine-table-pane {
            width: 100%;
            height: 60%;
            min-height: 6;
            margin-right: 0;
            margin-bottom: 0;
        }
        &.narrow #quarantine-detail-pane {
            width: 100%;
            height: 40%;
            min-height: 4;
        }
        &.compact .quarantine-button-row {
            margin-top: 0;
        }
        &.narrow .quarantine-button-row {
            grid-size: 2;
            grid-columns: 1fr 1fr;
        }
        &.compact .quarantine-button-row Button {
            height: 1;
            min-height: 1;
            border: none;
        }
    }
    """

    def __init__(
        self,
        db: Any | None = None,
        base_dir: str = "",
        policies: list[dict[str, Any]] | None = None,
    ):
        super().__init__()
        self.db = db
        self.base_dir = base_dir
        self.policies = policies or []
        self.records: list[dict[str, Any]] = []
        self.filtered_records: list[dict[str, Any]] = []
        self.selected_job_ids: set[str] = set()
        self.selected_job_id: str | None = None
        self._updating_select_all: bool = False

    def compose(self) -> ComposeResult:
        """Compose quarantine vault modal widgets."""
        with ModalBox(classes="quarantine-modal-box modal-box"):
            yield Heading(
                "Quarantine Vault & Compliance Audit Review [Ctrl+U]",
                level=1,
                classes="quarantine-title",
                id="modal-title",
            )
            yield Label(
                "Inspect staged files, view structured audit logs, release, or re-inspect compliance items:",
                classes="quarantine-subtitle",
            )

            with Vertical(classes="modal-body"):
                with Horizontal(classes="quarantine-filter-row"):
                    inp = Input(
                        placeholder="Search by job ID, filename, policy reason...",
                        id="quarantine-search-input",
                    )
                    inp.tooltip = "Filter quarantine records by job ID, filename, or policy reason"
                    yield inp

                    sel = Select(
                        [
                            ("ALL Statuses", "ALL"),
                            ("STAGED", "STAGED"),
                            ("QUARANTINED", "QUARANTINED"),
                            ("IN_INSPECTION", "IN_INSPECTION"),
                            ("RELEASED", "RELEASED"),
                            ("DISMISSED", "DISMISSED"),
                            ("DEAD_LETTER_QUEUE", "DEAD_LETTER_QUEUE"),
                        ],
                        value="ALL",
                        id="quarantine-status-filter",
                        allow_blank=False,
                    )
                    sel.tooltip = "Filter quarantine records by status"
                    yield sel

                    chk_all = Checkbox("Select All", id="chk-select-all", value=False)
                    chk_all.tooltip = (
                        "Select or deselect all visible quarantine records"
                    )
                    yield chk_all

                with Horizontal(classes="quarantine-content-split"):
                    dt = DataTable(id="quarantine-table")
                    dt.tooltip = "Table of staged quarantine compliance records"
                    dt.cursor_type = "row"
                    with Vertical(id="quarantine-table-pane"):
                        yield dt

                    with Vertical(id="quarantine-detail-pane"):
                        lbl = Heading(
                            "Select an item to view audit log & details",
                            level=2,
                            classes="quarantine-detail-header",
                            id="quarantine-detail-title",
                        )
                        lbl.tooltip = "Audit log and metadata details panel"
                        yield lbl
                        st = Static(
                            "No quarantine item selected.",
                            id="quarantine-detail-content",
                        )
                        st.tooltip = "Structured audit log timeline view"
                        yield st

            with Horizontal(classes="quarantine-button-row"):
                lbl_cnt = Label("Selected: 0/0", id="lbl-selection-count")
                lbl_cnt.tooltip = "Count of currently selected quarantine records"
                yield lbl_cnt

                btn_rel = Button(
                    "Release (r)", id="btn-quarantine-release", variant="success"
                )
                btn_rel.tooltip = (
                    "Release selected quarantined item(s) to destination directory"
                )
                yield btn_rel

                btn_dis = Button(
                    "Dismiss (d)", id="btn-quarantine-dismiss", variant="warning"
                )
                btn_dis.tooltip = (
                    "Dismiss selected quarantine item(s) without relocating file"
                )
                yield btn_dis

                btn_insp = Button(
                    "Re-inspect (i)", id="btn-quarantine-reinspect", variant="primary"
                )
                btn_insp.tooltip = "Trigger background forensic scan and policy evaluation for selected item(s)"
                yield btn_insp

                btn_ref = Button("Refresh", id="btn-quarantine-refresh")
                btn_ref.tooltip = "Refresh quarantine vault records from database"
                yield btn_ref

                btn_close = Button("Close (Esc)", id="btn-quarantine-close")
                btn_close.tooltip = "Close quarantine vault dialog"
                yield btn_close

    def on_mount(self) -> None:
        """Initialize data table columns and trigger initial record fetch on mount."""
        super().on_mount()
        dt = self.query_one("#quarantine-table", DataTable)
        dt.add_columns(
            ("Sel", "Sel"),
            "Job ID",
            "Filename",
            "Status",
            "Policy Action",
            "Created",
        )
        self.announce("Opened Quarantine Vault modal.")
        self.action_refresh_records()

    @on(Button.Pressed, "#btn-quarantine-close")
    def action_cancel(self) -> None:
        """Close quarantine vault modal on Escape key or Close button press."""
        self.dismiss(None)

    action_close_button = action_cancel

    @contextmanager
    def _open_db(self):
        if self.db is not None:
            yield self.db
        else:
            from app.core.services import acquire_services

            with acquire_services() as services:
                yield services.db

    @on(Button.Pressed, "#btn-quarantine-refresh")
    def action_refresh_records(self) -> None:
        """Refresh quarantine records from database."""
        self.fetch_records_async()

    @work(thread=True)
    def fetch_records_async(self) -> None:
        """Fetch quarantine records asynchronously on background worker thread."""
        try:
            with self._open_db() as db_inst:
                if self.base_dir:
                    recs = db_inst.get_quarantine_records_by_base_dir(self.base_dir)
                else:
                    recs = db_inst.get_all_quarantine_records()
                self._call_ui(self._on_records_loaded, recs)
        except Exception as e:
            logger.exception(f"Failed to fetch quarantine records: {e}")
            self._call_ui(self._on_records_loaded, [])
            self._call_ui(self.announce, f"Error loading quarantine records: {e}")

    def _on_records_loaded(self, records: list[dict[str, Any]]) -> None:
        self.records = records
        self._apply_filters()
        self.announce(f"Loaded {len(records)} quarantine record(s).")

    @on(Input.Changed, "#quarantine-search-input")
    @on(Select.Changed, "#quarantine-status-filter")
    def _on_filter_changed(self) -> None:
        self._apply_filters()

    @on(Checkbox.Changed, "#chk-select-all")
    def _on_select_all_changed(self, event: Checkbox.Changed) -> None:
        if self._updating_select_all:
            return
        if event.value:
            for r in self.filtered_records:
                if r.get("job_id"):
                    self.selected_job_ids.add(r["job_id"])
        else:
            self.selected_job_ids.clear()
        self._update_table_selections()
        self._update_selection_count_label()

    def _update_selection_count_label(self) -> None:
        try:
            lbl = self.query_one("#lbl-selection-count", Label)
            count = len(self.selected_job_ids)
            total = len(self.filtered_records)
            lbl.update(f"Selected: {count}/{total}")
        except Exception:
            pass

    def _update_table_selections(self) -> None:
        try:
            dt = self.query_one("#quarantine-table", DataTable)
            for r in self.filtered_records:
                job_id = r.get("job_id")
                if job_id and RowKey(job_id) in dt.rows and dt.ordered_columns:
                    sel_str = "[x]" if job_id in self.selected_job_ids else "[ ]"
                    col_key = (
                        "Sel"
                        if ColumnKey("Sel") in dt.columns
                        else dt.ordered_columns[0].key
                    )
                    dt.update_cell(job_id, col_key, sel_str)
        except Exception:
            pass

        try:
            chk = self.query_one("#chk-select-all", Checkbox)
            all_selected = len(self.filtered_records) > 0 and all(
                r.get("job_id") in self.selected_job_ids for r in self.filtered_records
            )
            if chk.value != all_selected:
                self._updating_select_all = True
                try:
                    with chk.prevent(Checkbox.Changed):
                        chk.value = all_selected
                finally:
                    self._updating_select_all = False
        except Exception:
            pass

    def _apply_filters(self) -> None:
        search_term = ""
        status_term = "ALL"
        try:
            search_term = (
                self.query_one("#quarantine-search-input", Input).value.strip().lower()
            )
            status_term = str(
                self.query_one("#quarantine-status-filter", Select).value or "ALL"
            )
        except Exception:
            pass

        filtered = []
        for r in self.records:
            st = r.get("status", "")
            if status_term != "ALL" and st != status_term:
                continue

            if search_term:
                job_id = (r.get("job_id") or "").lower()
                orig_file = (r.get("original_filepath") or "").lower()
                staged_file = (r.get("staged_filepath") or "").lower()
                action = (r.get("policy_action") or "").lower()
                if (
                    search_term not in job_id
                    and search_term not in orig_file
                    and search_term not in staged_file
                    and search_term not in action
                    and search_term not in st.lower()
                ):
                    continue
            filtered.append(r)

        self.filtered_records = filtered
        dt = self.query_one("#quarantine-table", DataTable)
        dt.clear()

        for r in filtered:
            job_id = r.get("job_id", "")
            orig_path = r.get("original_filepath", "")
            fname = os.path.basename(orig_path) if orig_path else job_id
            st = r.get("status", "")
            act = r.get("policy_action") or "-"
            created_ts = r.get("created_at", 0)
            created_str = (
                time.strftime("%Y-%m-%d %H:%M", time.localtime(created_ts))
                if created_ts
                else "-"
            )
            sel_str = "[x]" if job_id in self.selected_job_ids else "[ ]"
            dt.add_row(sel_str, job_id, fname, st, act, created_str, key=job_id)

        if filtered:
            if not self.selected_job_id or not any(
                x.get("job_id") == self.selected_job_id for x in filtered
            ):
                self.selected_job_id = filtered[0].get("job_id")
            self._render_detail_pane(self.selected_job_id)
        else:
            self.selected_job_id = None
            self._render_detail_pane(None)

        self._update_selection_count_label()

    @on(DataTable.RowSelected)
    def _on_row_selected(self, event: DataTable.RowSelected) -> None:
        if event.row_key and event.row_key.value:
            job_id = event.row_key.value
            self.selected_job_id = job_id
            if job_id in self.selected_job_ids:
                self.selected_job_ids.remove(job_id)
            else:
                self.selected_job_ids.add(job_id)
            self._update_table_selections()
            self._update_selection_count_label()
            self._render_detail_pane(job_id)

    @on(DataTable.CellHighlighted)
    def _on_cell_highlighted(self, event: DataTable.CellHighlighted) -> None:
        try:
            dt = self.query_one("#quarantine-table", DataTable)
            row_key = dt.coordinate_to_cell_key(event.coordinate).row_key
            if row_key and row_key.value:
                self.selected_job_id = row_key.value
                self._render_detail_pane(self.selected_job_id)
        except Exception:
            pass

    def _get_selected_record(self, job_id: str | None) -> dict[str, Any] | None:
        if not job_id:
            return None
        for r in self.records:
            if r.get("job_id") == job_id:
                return r
        return None

    def _get_target_job_ids(self) -> list[str]:
        if self.selected_job_ids:
            return list(self.selected_job_ids)
        if self.selected_job_id:
            return [self.selected_job_id]
        return []

    def _render_detail_pane(self, job_id: str | None) -> None:
        try:
            title_lbl = self.query_one("#quarantine-detail-title", Label)
            content_st = self.query_one("#quarantine-detail-content", Static)
        except Exception:
            return

        record = self._get_selected_record(job_id)
        if not record:
            title_lbl.update("No item selected")
            content_st.update(
                "Select a row in the quarantine table to view its detailed structured audit log."
            )
            return

        title_lbl.update(f"Job Details: {record.get('job_id')}")

        lines = [
            f"[bold]Original Path:[/bold] {record.get('original_filepath', '-')}",
            f"[bold]Staged Path:[/bold] {record.get('staged_filepath', '-')}",
            f"[bold]Status:[/bold] {record.get('status', '-')}",
            f"[bold]Policy Action:[/bold] {record.get('policy_action') or '-'}",
            f"[bold]File Hash:[/bold] {record.get('file_hash') or '-'}",
            f"[bold]Base Directory:[/bold] {record.get('base_dir', '-')}",
        ]
        if err := record.get("error_message"):
            lines.append(f"[bold red]Error:[/bold red] {err}")

        lines.append("")
        lines.append("[bold cyan]Structured Audit Log Timeline:[/bold cyan]")
        audit_log = record.get("audit_log", [])
        if audit_log:
            for entry in audit_log:
                if isinstance(entry, dict):
                    ts = entry.get("timestamp", 0)
                    ts_str = (
                        time.strftime("%H:%M:%S", time.localtime(ts))
                        if ts
                        else "--:--:--"
                    )
                    st = entry.get("status", "")
                    det = entry.get("details", "")
                    lines.append(f"  [dim]{ts_str}[/dim] [bold]{st}[/bold]: {det}")
                else:
                    lines.append(f"  • {entry}")
        else:
            lines.append("  (No audit log entries recorded)")

        content_st.update("\n".join(lines))

    @on(Button.Pressed, "#btn-quarantine-release")
    def action_release_selected(self) -> None:
        """Prompt target directory and trigger batch release for selected quarantine items."""
        job_ids = self._get_target_job_ids()
        if not job_ids:
            self.announce("No quarantine item selected for release.")
            return

        base_dir = self.base_dir or "."

        def _dir_selected_callback(target_dir: str | list[str] | None) -> None:
            if isinstance(target_dir, list):
                target_dir = target_dir[0] if target_dir else None
            if not target_dir:
                self.announce("Release operation cancelled.")
                return
            if not os.path.exists(target_dir) or not os.path.isdir(target_dir):
                from app.ui.notifications import notify

                err_msg = f"Target directory does not exist: {target_dir}"
                self.announce(err_msg, priority="assertive")
                notify(err_msg, type="error")
                return
            self.announce(f"Releasing {len(job_ids)} quarantine item(s)...")
            self.execute_batch_release_async(job_ids, target_dir)

        self.app.push_screen(DirectorySelectModal(base_dir), _dir_selected_callback)

    @staticmethod
    def _normalize_batch_job_ids(job_ids: Any) -> list[str]:
        """Normalize single or iterable job identifiers into a clean list of job IDs."""
        raw_list = [job_ids] if isinstance(job_ids, (str, dict)) else list(job_ids)
        return [
            str(j.get("job_id")) if isinstance(j, dict) else str(j)
            for j in raw_list
            if j and (not isinstance(j, dict) or j.get("job_id"))
        ]

    def _run_batch_operation(
        self,
        job_ids: Any,
        *,
        action_fn: Callable[[Any, list[str]], list[Any]],
        on_complete: Callable[[list[Any]], None],
        error_log_label: str,
        error_announce_label: str,
        include_policies: bool = True,
    ) -> None:
        """Execute a quarantine batch service action and dispatch UI completion."""
        try:
            clean_job_ids = self._normalize_batch_job_ids(job_ids)
            with self._open_db() as db_inst:
                from app.core.quarantine_interceptor import QuarantineInterceptorService

                if include_policies:
                    runtime_settings = getattr(
                        getattr(self, "app", None), "settings", None
                    )
                    service = QuarantineInterceptorService(
                        db=db_inst,
                        policies=self.policies,
                        runtime_settings=runtime_settings,
                    )
                else:
                    service = QuarantineInterceptorService(db=db_inst)
                results = action_fn(service, clean_job_ids)
                self._call_ui(on_complete, results)
        except Exception as e:
            logger.error(f"Failed {error_log_label}: {e}", exc_info=True)
            self._call_ui(self.announce, f"{error_announce_label} failed: {e}")

    def _complete_batch_operation(
        self,
        results: list[Any],
        *,
        title: str,
        is_success: Callable[[dict[str, Any]], bool],
        ok_notify_type: str,
    ) -> None:
        """Announce batch completion summary, notify user, clear selection, and refresh."""
        success_count = sum(1 for r in results if is_success(r))
        fail_count = len(results) - success_count
        msg = f"{title}: {success_count} succeeded, {fail_count} failed."
        self.announce(msg)
        try:
            from app.ui.notifications import notify

            notify(msg, type=ok_notify_type if fail_count == 0 else "warning")
        except Exception:
            pass
        self.selected_job_ids.clear()
        self.fetch_records_async()

    @work(thread=True)
    def execute_batch_release_async(
        self, job_ids: Any, target_dir: str, allow_external: bool = True
    ) -> None:
        """Asynchronously release batch of quarantine items on background worker thread."""
        self._run_batch_operation(
            job_ids,
            action_fn=lambda service, ids: service.release_quarantine_batch(
                ids, dest_dir=target_dir, allow_external=allow_external
            ),
            on_complete=self._on_batch_release_complete,
            error_log_label="batch quarantine release",
            error_announce_label="Batch release",
        )

    def execute_release_async(
        self, job_id: Any, dest_dir: str, allow_external: bool = True
    ) -> None:
        """Compatibility helper for single item release."""
        self.execute_batch_release_async(
            [job_id], dest_dir, allow_external=allow_external
        )

    def _on_batch_release_complete(self, results: list[dict[str, Any]]) -> None:
        self._complete_batch_operation(
            results,
            title="Batch Release Complete",
            is_success=lambda r: r.get("status") == "RELEASED",
            ok_notify_type="success",
        )

    @on(Button.Pressed, "#btn-quarantine-dismiss")
    def action_dismiss_selected(self) -> None:
        """Dismiss selected quarantine items without restoring files."""
        job_ids = self._get_target_job_ids()
        if not job_ids:
            self.announce("No quarantine item selected for dismissal.")
            return

        self.announce(f"Dismissing {len(job_ids)} quarantine item(s)...")
        self.execute_batch_dismiss_async(job_ids)

    @work(thread=True)
    def execute_batch_dismiss_async(self, job_ids: Any) -> None:
        """Asynchronously mark quarantine items as dismissed on background worker thread."""
        self._run_batch_operation(
            job_ids,
            action_fn=lambda service, ids: service.dismiss_quarantine_batch(ids),
            on_complete=self._on_batch_dismiss_complete,
            error_log_label="batch quarantine dismiss",
            error_announce_label="Batch dismiss",
            include_policies=False,
        )

    def execute_dismiss_async(self, job_id: Any) -> None:
        """Compatibility helper for single item dismissal."""
        self.execute_batch_dismiss_async([job_id])

    def _on_batch_dismiss_complete(self, results: list[dict[str, Any]]) -> None:
        self._complete_batch_operation(
            results,
            title="Batch Dismiss Complete",
            is_success=lambda r: r.get("status") == "DISMISSED",
            ok_notify_type="info",
        )

    @on(Button.Pressed, "#btn-quarantine-reinspect")
    def action_reinspect_selected(self) -> None:
        """Trigger background forensic re-inspection scan for selected items."""
        job_ids = self._get_target_job_ids()
        if not job_ids:
            self.announce("No quarantine item selected for re-inspection.")
            return

        self.announce(
            f"Initiating background forensic re-inspection for {len(job_ids)} item(s)..."
        )
        self.execute_batch_reinspect_async(job_ids)

    @work(thread=True)
    def execute_batch_reinspect_async(self, job_ids: Any) -> None:
        """Asynchronously re-inspect batch of quarantine items on worker thread."""
        self._run_batch_operation(
            job_ids,
            action_fn=lambda service, ids: service.process_quarantine_batch(ids),
            on_complete=self._on_batch_reinspect_complete,
            error_log_label="batch re-inspection",
            error_announce_label="Batch re-inspection",
        )

    def execute_reinspect_async(self, job_id: Any) -> None:
        """Compatibility helper for single item re-inspection."""
        self.execute_batch_reinspect_async([job_id])

    def _on_batch_reinspect_complete(self, results: list[Any]) -> None:
        self._complete_batch_operation(
            results,
            title="Batch Re-inspection Complete",
            is_success=lambda r: (
                (r.get("status") or "").upper() not in ("FAILED", "ERROR")
            ),
            ok_notify_type="info",
        )

action_cancel()

Close quarantine vault modal on Escape key or Close button press.

Source code in app/ui/modals/quarantine.py
322
323
324
325
@on(Button.Pressed, "#btn-quarantine-close")
def action_cancel(self) -> None:
    """Close quarantine vault modal on Escape key or Close button press."""
    self.dismiss(None)

action_dismiss_selected()

Dismiss selected quarantine items without restoring files.

Source code in app/ui/modals/quarantine.py
700
701
702
703
704
705
706
707
708
709
@on(Button.Pressed, "#btn-quarantine-dismiss")
def action_dismiss_selected(self) -> None:
    """Dismiss selected quarantine items without restoring files."""
    job_ids = self._get_target_job_ids()
    if not job_ids:
        self.announce("No quarantine item selected for dismissal.")
        return

    self.announce(f"Dismissing {len(job_ids)} quarantine item(s)...")
    self.execute_batch_dismiss_async(job_ids)

action_refresh_records()

Refresh quarantine records from database.

Source code in app/ui/modals/quarantine.py
339
340
341
342
@on(Button.Pressed, "#btn-quarantine-refresh")
def action_refresh_records(self) -> None:
    """Refresh quarantine records from database."""
    self.fetch_records_async()

action_reinspect_selected()

Trigger background forensic re-inspection scan for selected items.

Source code in app/ui/modals/quarantine.py
735
736
737
738
739
740
741
742
743
744
745
746
@on(Button.Pressed, "#btn-quarantine-reinspect")
def action_reinspect_selected(self) -> None:
    """Trigger background forensic re-inspection scan for selected items."""
    job_ids = self._get_target_job_ids()
    if not job_ids:
        self.announce("No quarantine item selected for re-inspection.")
        return

    self.announce(
        f"Initiating background forensic re-inspection for {len(job_ids)} item(s)..."
    )
    self.execute_batch_reinspect_async(job_ids)

action_release_selected()

Prompt target directory and trigger batch release for selected quarantine items.

Source code in app/ui/modals/quarantine.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
@on(Button.Pressed, "#btn-quarantine-release")
def action_release_selected(self) -> None:
    """Prompt target directory and trigger batch release for selected quarantine items."""
    job_ids = self._get_target_job_ids()
    if not job_ids:
        self.announce("No quarantine item selected for release.")
        return

    base_dir = self.base_dir or "."

    def _dir_selected_callback(target_dir: str | list[str] | None) -> None:
        if isinstance(target_dir, list):
            target_dir = target_dir[0] if target_dir else None
        if not target_dir:
            self.announce("Release operation cancelled.")
            return
        if not os.path.exists(target_dir) or not os.path.isdir(target_dir):
            from app.ui.notifications import notify

            err_msg = f"Target directory does not exist: {target_dir}"
            self.announce(err_msg, priority="assertive")
            notify(err_msg, type="error")
            return
        self.announce(f"Releasing {len(job_ids)} quarantine item(s)...")
        self.execute_batch_release_async(job_ids, target_dir)

    self.app.push_screen(DirectorySelectModal(base_dir), _dir_selected_callback)

compose()

Compose quarantine vault modal widgets.

Source code in app/ui/modals/quarantine.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def compose(self) -> ComposeResult:
    """Compose quarantine vault modal widgets."""
    with ModalBox(classes="quarantine-modal-box modal-box"):
        yield Heading(
            "Quarantine Vault & Compliance Audit Review [Ctrl+U]",
            level=1,
            classes="quarantine-title",
            id="modal-title",
        )
        yield Label(
            "Inspect staged files, view structured audit logs, release, or re-inspect compliance items:",
            classes="quarantine-subtitle",
        )

        with Vertical(classes="modal-body"):
            with Horizontal(classes="quarantine-filter-row"):
                inp = Input(
                    placeholder="Search by job ID, filename, policy reason...",
                    id="quarantine-search-input",
                )
                inp.tooltip = "Filter quarantine records by job ID, filename, or policy reason"
                yield inp

                sel = Select(
                    [
                        ("ALL Statuses", "ALL"),
                        ("STAGED", "STAGED"),
                        ("QUARANTINED", "QUARANTINED"),
                        ("IN_INSPECTION", "IN_INSPECTION"),
                        ("RELEASED", "RELEASED"),
                        ("DISMISSED", "DISMISSED"),
                        ("DEAD_LETTER_QUEUE", "DEAD_LETTER_QUEUE"),
                    ],
                    value="ALL",
                    id="quarantine-status-filter",
                    allow_blank=False,
                )
                sel.tooltip = "Filter quarantine records by status"
                yield sel

                chk_all = Checkbox("Select All", id="chk-select-all", value=False)
                chk_all.tooltip = (
                    "Select or deselect all visible quarantine records"
                )
                yield chk_all

            with Horizontal(classes="quarantine-content-split"):
                dt = DataTable(id="quarantine-table")
                dt.tooltip = "Table of staged quarantine compliance records"
                dt.cursor_type = "row"
                with Vertical(id="quarantine-table-pane"):
                    yield dt

                with Vertical(id="quarantine-detail-pane"):
                    lbl = Heading(
                        "Select an item to view audit log & details",
                        level=2,
                        classes="quarantine-detail-header",
                        id="quarantine-detail-title",
                    )
                    lbl.tooltip = "Audit log and metadata details panel"
                    yield lbl
                    st = Static(
                        "No quarantine item selected.",
                        id="quarantine-detail-content",
                    )
                    st.tooltip = "Structured audit log timeline view"
                    yield st

        with Horizontal(classes="quarantine-button-row"):
            lbl_cnt = Label("Selected: 0/0", id="lbl-selection-count")
            lbl_cnt.tooltip = "Count of currently selected quarantine records"
            yield lbl_cnt

            btn_rel = Button(
                "Release (r)", id="btn-quarantine-release", variant="success"
            )
            btn_rel.tooltip = (
                "Release selected quarantined item(s) to destination directory"
            )
            yield btn_rel

            btn_dis = Button(
                "Dismiss (d)", id="btn-quarantine-dismiss", variant="warning"
            )
            btn_dis.tooltip = (
                "Dismiss selected quarantine item(s) without relocating file"
            )
            yield btn_dis

            btn_insp = Button(
                "Re-inspect (i)", id="btn-quarantine-reinspect", variant="primary"
            )
            btn_insp.tooltip = "Trigger background forensic scan and policy evaluation for selected item(s)"
            yield btn_insp

            btn_ref = Button("Refresh", id="btn-quarantine-refresh")
            btn_ref.tooltip = "Refresh quarantine vault records from database"
            yield btn_ref

            btn_close = Button("Close (Esc)", id="btn-quarantine-close")
            btn_close.tooltip = "Close quarantine vault dialog"
            yield btn_close

execute_batch_dismiss_async(job_ids)

Asynchronously mark quarantine items as dismissed on background worker thread.

Source code in app/ui/modals/quarantine.py
711
712
713
714
715
716
717
718
719
720
721
@work(thread=True)
def execute_batch_dismiss_async(self, job_ids: Any) -> None:
    """Asynchronously mark quarantine items as dismissed on background worker thread."""
    self._run_batch_operation(
        job_ids,
        action_fn=lambda service, ids: service.dismiss_quarantine_batch(ids),
        on_complete=self._on_batch_dismiss_complete,
        error_log_label="batch quarantine dismiss",
        error_announce_label="Batch dismiss",
        include_policies=False,
    )

execute_batch_reinspect_async(job_ids)

Asynchronously re-inspect batch of quarantine items on worker thread.

Source code in app/ui/modals/quarantine.py
748
749
750
751
752
753
754
755
756
757
@work(thread=True)
def execute_batch_reinspect_async(self, job_ids: Any) -> None:
    """Asynchronously re-inspect batch of quarantine items on worker thread."""
    self._run_batch_operation(
        job_ids,
        action_fn=lambda service, ids: service.process_quarantine_batch(ids),
        on_complete=self._on_batch_reinspect_complete,
        error_log_label="batch re-inspection",
        error_announce_label="Batch re-inspection",
    )

execute_batch_release_async(job_ids, target_dir, allow_external=True)

Asynchronously release batch of quarantine items on background worker thread.

Source code in app/ui/modals/quarantine.py
669
670
671
672
673
674
675
676
677
678
679
680
681
682
@work(thread=True)
def execute_batch_release_async(
    self, job_ids: Any, target_dir: str, allow_external: bool = True
) -> None:
    """Asynchronously release batch of quarantine items on background worker thread."""
    self._run_batch_operation(
        job_ids,
        action_fn=lambda service, ids: service.release_quarantine_batch(
            ids, dest_dir=target_dir, allow_external=allow_external
        ),
        on_complete=self._on_batch_release_complete,
        error_log_label="batch quarantine release",
        error_announce_label="Batch release",
    )

execute_dismiss_async(job_id)

Compatibility helper for single item dismissal.

Source code in app/ui/modals/quarantine.py
723
724
725
def execute_dismiss_async(self, job_id: Any) -> None:
    """Compatibility helper for single item dismissal."""
    self.execute_batch_dismiss_async([job_id])

execute_reinspect_async(job_id)

Compatibility helper for single item re-inspection.

Source code in app/ui/modals/quarantine.py
759
760
761
def execute_reinspect_async(self, job_id: Any) -> None:
    """Compatibility helper for single item re-inspection."""
    self.execute_batch_reinspect_async([job_id])

execute_release_async(job_id, dest_dir, allow_external=True)

Compatibility helper for single item release.

Source code in app/ui/modals/quarantine.py
684
685
686
687
688
689
690
def execute_release_async(
    self, job_id: Any, dest_dir: str, allow_external: bool = True
) -> None:
    """Compatibility helper for single item release."""
    self.execute_batch_release_async(
        [job_id], dest_dir, allow_external=allow_external
    )

fetch_records_async()

Fetch quarantine records asynchronously on background worker thread.

Source code in app/ui/modals/quarantine.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
@work(thread=True)
def fetch_records_async(self) -> None:
    """Fetch quarantine records asynchronously on background worker thread."""
    try:
        with self._open_db() as db_inst:
            if self.base_dir:
                recs = db_inst.get_quarantine_records_by_base_dir(self.base_dir)
            else:
                recs = db_inst.get_all_quarantine_records()
            self._call_ui(self._on_records_loaded, recs)
    except Exception as e:
        logger.exception(f"Failed to fetch quarantine records: {e}")
        self._call_ui(self._on_records_loaded, [])
        self._call_ui(self.announce, f"Error loading quarantine records: {e}")

on_mount()

Initialize data table columns and trigger initial record fetch on mount.

Source code in app/ui/modals/quarantine.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def on_mount(self) -> None:
    """Initialize data table columns and trigger initial record fetch on mount."""
    super().on_mount()
    dt = self.query_one("#quarantine-table", DataTable)
    dt.add_columns(
        ("Sel", "Sel"),
        "Job ID",
        "Filename",
        "Status",
        "Policy Action",
        "Created",
    )
    self.announce("Opened Quarantine Vault modal.")
    self.action_refresh_records()

app.ui.modals.reports

app.ui.modals.reports

Report dialogs: extraction preview, report export and the audit report.

AuditReportModal

Bases: ResponsiveModalScreen[None]

Interactive Modal Screen for Tabular Verification Tree & Multi-Format Audit Export.

Source code in app/ui/modals/reports.py
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
class AuditReportModal(ResponsiveModalScreen[None]):
    """Interactive Modal Screen for Tabular Verification Tree & Multi-Format Audit Export."""

    BINDINGS = [
        Binding("escape", "cancel", "Close verification dialog", show=True),
        Binding("ctrl+r", "retry_selected", "Retry Selected Failed Item", show=True),
        Binding("ctrl+t", "retry_all", "Retry All Failed Items", show=True),
        Binding("ctrl+j", "export_json", "Export JSON Report", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .audit-modal-box {
        width: 95%;
        max-width: 108;
        min-width: 40;
        height: 90%;
        min-height: 20;
    }
    .modal-body {
        height: 1fr;
    }
    .audit-title {
        text-style: bold;
        color: $accent;
        margin-bottom: 0;
    }
    .audit-subtitle {
        color: $text-muted;
        margin-bottom: 1;
    }
    .audit-stats-row {
        width: 100%;
        height: auto;
        margin-bottom: 1;
        layout: horizontal;
    }
    .stat-card {
        width: 1fr;
        min-width: 0;
        padding: 0 1;
        margin-right: 1;
        border: solid $secondary;
        background: $surface;
    }
    .stat-pass {
        color: $success;
        border: solid $success;
    }
    .stat-fail {
        color: $error;
        border: solid $error;
    }
    .stat-skipped {
        color: $warning;
        border: solid $warning;
    }
    .stat-unverified {
        color: $text-muted;
        border: solid $secondary;
    }
    .filter-row {
        width: 100%;
        height: auto;
        margin-bottom: 1;
    }
    #audit-search-input {
        width: 1fr;
        margin-right: 1;
    }
    #audit-status-filter {
        width: 26;
    }
    #audit-table, #failed-items-table {
        width: 100%;
        height: auto;
        min-height: 7;
        max-height: 16;
        margin-bottom: 1;
        border: solid $accent;
    }
    #audit-tabs {
        height: auto;
        min-height: 11;
        margin-bottom: 1;
    }
    .button-row {
        layout: grid;
        grid-size: 3;
        grid-columns: 1fr 1fr 1fr;
        grid-gutter: 0 1;
    }
    .button-row Button {
        width: 100%;
        min-width: 0;
        margin: 0;
    }
    Button:focus, Input:focus, Select:focus, DataTable:focus {
        border: heavy $accent;
        text-style: bold;
    }
    AuditReportModal {
        background: rgba(0, 0, 0, 0.7);
        &.compact .audit-modal-box, &.narrow .audit-modal-box {
            padding: 0 1;
            width: 98%;
            height: 96%;
            max-height: 96%;
        }
        &.compact .audit-subtitle {
            margin-bottom: 0;
        }
        &.compact .audit-stats-row, &.narrow .audit-stats-row {
            margin-bottom: 0;
            layout: grid;
            grid-size: 3;
            grid-columns: 1fr 1fr 1fr;
            grid-gutter: 0 1;
        }
        &.compact .stat-card, &.narrow .stat-card {
            border: none;
            height: 1;
            margin-right: 0;
        }
        &.compact .filter-row {
            margin-bottom: 0;
        }
        &.narrow #audit-status-filter {
            width: 20;
        }
        &.compact #audit-table, &.compact #failed-items-table {
            margin-bottom: 0;
        }
        &.compact #audit-tabs {
            margin-bottom: 0;
        }
        &.compact .button-row {
            margin-top: 0;
        }
        &.narrow .button-row {
            grid-size: 2;
            grid-columns: 1fr 1fr;
        }
        &.compact .button-row Button {
            height: 1;
            min-height: 1;
            border: none;
        }
    }
    """

    def __init__(self, report_data: dict[str, Any], session: Any = None):
        super().__init__()
        self.report_data = report_data or {}
        self.session = session

    def compose(self) -> ComposeResult:
        """Compose verification audit report modal widgets."""
        with ModalBox(classes="audit-modal-box modal-box"):
            yield Heading(
                "Post-Sort File Integrity Verification Audit Report",
                level=1,
                classes="audit-title",
                id="modal-title",
            )
            base_dir_str = self.report_data.get("base_dir", "")
            yield Label(f"Target Directory: {base_dir_str}", classes="audit-subtitle")

            total = self.report_data.get("total_files", 0)
            pass_cnt = self.report_data.get("verified_pass_count", 0)
            fail_cnt = self.report_data.get("mismatch_fail_count", 0)
            skip_cnt = self.report_data.get("skipped_count", 0)
            unverified_cnt = self.report_data.get("unverified_count", 0)

            with Vertical(classes="modal-body"):
                with Horizontal(classes="audit-stats-row"):
                    yield Static(f"Total: {total}", classes="stat-card", markup=False)
                    yield Static(
                        f"[PASS]: {pass_cnt}",
                        classes="stat-card stat-pass",
                        markup=False,
                    )
                    yield Static(
                        f"[FAIL]: {fail_cnt}",
                        classes="stat-card stat-fail",
                        markup=False,
                    )
                    yield Static(
                        f"[SKIPPED]: {skip_cnt}",
                        classes="stat-card stat-skipped",
                        markup=False,
                    )
                    yield Static(
                        f"[UNVERIFIED]: {unverified_cnt}",
                        classes="stat-card stat-unverified",
                        markup=False,
                    )

                with TabbedContent(initial="tab-all-records", id="audit-tabs"):
                    with TabPane("All Verification Records", id="tab-all-records"):
                        with Horizontal(classes="filter-row"):
                            inp = Input(
                                placeholder="Search by filename or path...",
                                id="audit-search-input",
                            )
                            inp.tooltip = (
                                "Filter verification results by filename or path"
                            )
                            yield inp

                            status_sel = Select(
                                [
                                    (literal_content("All Statuses"), "ALL"),
                                    (
                                        literal_content("Verified Pass [PASS]"),
                                        "VERIFIED_PASS",
                                    ),
                                    (
                                        literal_content("Mismatch Fail [FAIL]"),
                                        "MISMATCH_FAIL",
                                    ),
                                    (
                                        literal_content("Move Fail [MOVE FAIL]"),
                                        "MOVE_FAIL",
                                    ),
                                    (literal_content("Skipped [SKIPPED]"), "SKIPPED"),
                                    (
                                        literal_content("Unverified [UNVERIFIED]"),
                                        "UNVERIFIED",
                                    ),
                                ],
                                value="ALL",
                                id="audit-status-filter",
                                allow_blank=False,
                            )
                            status_sel.tooltip = "Filter results by verification status"
                            yield status_sel

                        table = DataTable(id="audit-table")
                        table.cursor_type = "row"
                        table.tooltip = "Audit report tabular verification tree"
                        yield table

                    with TabPane("Failed Items Queue", id="tab-failed-queue"):
                        failed_table = DataTable(id="failed-items-table")
                        failed_table.cursor_type = "row"
                        failed_table.tooltip = "Dedicated Failed Items queue table"
                        yield failed_table

            with Horizontal(classes="button-row"):
                btn_retry_sel = Button(
                    "Retry Selected", id="btn-retry-selected", variant="warning"
                )
                btn_retry_sel.tooltip = (
                    "Re-attempt file move operation for selected failed item"
                )
                yield btn_retry_sel

                btn_retry_all = Button("Retry All", id="btn-retry-all", variant="error")
                btn_retry_all.tooltip = (
                    "Re-attempt file move operations for all failed items in queue"
                )
                yield btn_retry_all

                btn_json = Button(
                    "Export JSON", id="btn-export-json", variant="primary"
                )
                btn_json.tooltip = "Export audit report to an external JSON file"
                yield btn_json

                btn_csv = Button("Export CSV", id="btn-export-csv", variant="success")
                btn_csv.tooltip = "Export audit report to an external CSV file"
                yield btn_csv

                btn_close = Button("Close", id="btn-close", variant="default")
                btn_close.tooltip = "Close verification audit report dialog"
                yield btn_close

    def on_mount(self) -> None:
        """Initialize table rows, accessibility announcement, and initial focus."""
        super().on_mount()
        self._populate_table()
        total = self.report_data.get("total_files", 0)
        pass_cnt = self.report_data.get("verified_pass_count", 0)
        fail_cnt = self.report_data.get("mismatch_fail_count", 0)
        skip_cnt = self.report_data.get("skipped_count", 0)
        unverified_cnt = self.report_data.get("unverified_count", 0)
        self.query_one("#audit-search-input", Input).focus()
        self.announce(
            f"Opened Audit Verification Report dialog. {total} total files: "
            f"{pass_cnt} passed, {fail_cnt} failed, {skip_cnt} skipped, {unverified_cnt} unverified."
        )

    def _populate_table(
        self, search_query: str = "", status_filter: str = "ALL"
    ) -> None:
        """Populate DataTable with verification records matching filter criteria."""
        table = self.query_one("#audit-table", DataTable)
        table.clear(columns=True)
        table.add_columns(
            "Status",
            "Filename",
            "Pre-Sort SHA-256",
            "Post-Sort SHA-256",
            "Destination Path",
        )

        query = search_query.strip().lower()
        records = self.report_data.get("records", [])
        self._audit_row_records: dict[str, dict[str, Any]] = {}

        for idx, rec in enumerate(records):
            status = rec.get("status", "")
            filename = rec.get("filename", "")
            rel_dst = rec.get("relative_destination", "") or rec.get(
                "destination_path", ""
            )
            pre_h = rec.get("pre_hash", "") or ""
            post_h = rec.get("post_hash", "") or ""

            if status_filter != "ALL" and status != status_filter:
                continue

            if query:
                match_fn = query in filename.lower()
                match_src = query in rec.get("relative_source", "").lower()
                match_dst = query in rel_dst.lower()
                match_hash = query in pre_h.lower() or query in post_h.lower()
                if not (match_fn or match_src or match_dst or match_hash):
                    continue

            badge = rec.get("status_badge", f"[{status}]")
            pre_trunc = (pre_h[:12] + "...") if len(pre_h) > 12 else (pre_h or "N/A")
            post_trunc = (
                (post_h[:12] + "...") if len(post_h) > 12 else (post_h or "N/A")
            )

            row_key = f"rec-{idx}"
            self._audit_row_records[row_key] = rec
            table.add_row(badge, filename, pre_trunc, post_trunc, rel_dst, key=row_key)

        self._populate_failed_table()

    def _populate_failed_table(self) -> None:
        """Populate dedicated Failed Items queue table with error descriptions."""
        table = self.query_one("#failed-items-table", DataTable)
        table.clear(columns=True)
        table.add_columns(
            "Filename",
            "Status",
            "Error Description",
            "Source Path",
            "Destination Path",
        )

        failed_records = self._get_failed_records()
        self._failed_row_records: dict[str, dict[str, Any]] = {}

        for idx, rec in enumerate(failed_records):
            fn = rec.get("filename", "")
            st = rec.get("status_badge", rec.get("status", ""))
            err = rec.get("error") or rec.get("error_description") or "Operation failed"
            src = rec.get("relative_source") or rec.get("source_path", "")
            dst = rec.get("relative_destination") or rec.get("destination_path", "")
            row_key = f"failed-{idx}"
            self._failed_row_records[row_key] = rec
            table.add_row(fn, st, err, src, dst, key=row_key)

    def _get_failed_records(self) -> list[dict[str, Any]]:
        """Get list of failed item records from report data."""
        failed = self.report_data.get("failed_items", [])
        if not failed:
            records = self.report_data.get("records", [])
            failed = [
                r
                for r in records
                if r.get("status") in ("MISMATCH_FAIL", "MOVE_FAIL") or r.get("error")
            ]
        return failed

    @on(Input.Changed, "#audit-search-input")
    def on_search_changed(self, event: Input.Changed) -> None:
        """Handle search input filter update."""
        status_val = self.query_one("#audit-status-filter", Select).value
        self._populate_table(search_query=event.value, status_filter=str(status_val))

    @on(Select.Changed, "#audit-status-filter")
    def on_status_changed(self, event: Select.Changed) -> None:
        """Handle status filter dropdown update."""
        search_val = self.query_one("#audit-search-input", Input).value
        self._populate_table(search_query=search_val, status_filter=str(event.value))

    def _resolve_active_row_record(
        self, table: DataTable, row_map: dict[str, dict[str, Any]]
    ) -> dict[str, Any] | None:
        """Resolve the record bound to ``table.cursor_row`` via its Textual row key."""
        if table.cursor_row is None or table.row_count <= 0:
            return None
        if not (0 <= table.cursor_row < table.row_count):
            return None
        try:
            row_key_obj, _ = table.coordinate_to_cell_key(
                Coordinate(table.cursor_row, 0)
            )
            key_str = str(row_key_obj.value)
            return row_map.get(key_str)
        except (
            KeyError,
            ValueError,
            LookupError,
            TypeError,
            AppError,
            ScreenError,
            QueryError,
        ):
            return None

    def action_retry_selected(self) -> None:
        """Retry move operation for selected failed item on the active tab."""
        active_tab = "tab-all-records"
        with contextlib.suppress(QueryError):
            active_tab = str(
                self.query_one("#audit-tabs", TabbedContent).active or "tab-all-records"
            )

        selected_record: dict[str, Any] | None = None
        if active_tab == "tab-failed-queue":
            failed_table = self.query_one("#failed-items-table", DataTable)
            selected_record = self._resolve_active_row_record(
                failed_table, getattr(self, "_failed_row_records", {})
            )
        else:
            audit_table = self.query_one("#audit-table", DataTable)
            rec = self._resolve_active_row_record(
                audit_table, getattr(self, "_audit_row_records", {})
            )
            if rec and (
                rec.get("status") in ("MISMATCH_FAIL", "MOVE_FAIL") or rec.get("error")
            ):
                selected_record = rec

        if not selected_record:
            msg = "No failed item selected to retry."
            self.announce(msg)
            self.notify(msg, severity="warning")
            return

        self._execute_retry([selected_record])

    def action_retry_all(self) -> None:
        """Retry move operations for all failed items in queue."""
        failed_records = self._get_failed_records()
        if not failed_records:
            msg = "No failed items to retry."
            self.announce(msg)
            self.notify(msg, severity="warning")
            return

        self._execute_retry(failed_records)

    def _execute_retry(self, items_to_retry: list[dict[str, Any]]) -> None:
        """Execute mover retry for selected failed items via AppSession and refresh UI."""
        from app.config import AppSettings
        from app.core.audit_reporter import generate_audit_report
        from app.core.session import AppSession

        base_dir = self.report_data.get("base_dir", "")
        session_id = self.report_data.get("session_id")
        app_ref: Any = getattr(self, "app", None)

        active_session: Any = None
        for cand in (self.session, getattr(app_ref, "app_session", None)):
            if (
                cand is not None
                and not getattr(cand, "_closed", False)
                and callable(getattr(cand, "retry_failed_moves", None))
            ):
                active_session = cand
                break

        effective_base = base_dir or getattr(app_ref, "base_dir", None) or "."
        if active_session is not None:
            retry_res = active_session.retry_failed_moves(
                items_to_retry, session_id=session_id
            )
        else:
            settings = getattr(app_ref, "settings", None) or AppSettings()
            temp_session = AppSession(settings, effective_base)
            try:
                retry_res = temp_session.retry_failed_moves(
                    items_to_retry, session_id=session_id
                )
            finally:
                temp_session.close()

        new_audit = retry_res.get("audit_report", {})
        effective_session_id = (
            retry_res.get("session_id") or new_audit.get("session_id") or session_id
        )

        retried_map: dict[str, dict[str, Any]] = {}
        for r in new_audit.get("records", []):
            raw_src = r.get("source_path")
            if isinstance(raw_src, str) and raw_src:
                retried_map[raw_src] = r
                norm_src = os.path.normcase(
                    os.path.normpath(
                        os.path.abspath(
                            os.path.join(base_dir, raw_src)
                            if (base_dir and not os.path.isabs(raw_src))
                            else raw_src
                        )
                    )
                )
                retried_map[norm_src] = r

        records = list(self.report_data.get("records", []))
        for idx, rec in enumerate(records):
            src = rec.get("source_path")
            if isinstance(src, str) and src:
                if src in retried_map:
                    records[idx] = retried_map[src]
                    continue
                norm_rec_src = os.path.normcase(
                    os.path.normpath(
                        os.path.abspath(
                            os.path.join(base_dir, src)
                            if (base_dir and not os.path.isabs(src))
                            else src
                        )
                    )
                )
                if norm_rec_src in retried_map:
                    records[idx] = retried_map[norm_rec_src]

        self.report_data = generate_audit_report(
            base_dir, records, session_id=effective_session_id
        )

        self._populate_table()
        self._update_stats_cards()

        if (
            int(new_audit.get("verified_pass_count") or 0) > 0
            and app_ref is not None
            and getattr(app_ref, "source_dirs", None)
            and callable(getattr(app_ref, "_start_scan", None))
        ):
            try:
                app_ref._start_scan()
            except (
                AppError,
                ScreenError,
                QueryError,
                WorkerError,
                OSError,
                RuntimeError,
                LookupError,
                TypeError,
                ValueError,
            ) as exc:
                logger.debug("Skipping post-retry scan refresh: %s", exc)

        pass_cnt = self.report_data.get("verified_pass_count", 0)
        fail_cnt = self.report_data.get("mismatch_fail_count", 0)
        msg = f"Retried {len(items_to_retry)} item(s). Overall status: {pass_cnt} passed, {fail_cnt} failed."
        self.announce(msg)
        self.notify(msg, severity="information")

    def _update_stats_cards(self) -> None:
        """Update stat card labels with current metrics."""
        total = self.report_data.get("total_files", 0)
        pass_cnt = self.report_data.get("verified_pass_count", 0)
        fail_cnt = self.report_data.get("mismatch_fail_count", 0)
        skip_cnt = self.report_data.get("skipped_count", 0)
        unverified_cnt = self.report_data.get("unverified_count", 0)

        try:
            cards = list(self.query(".stat-card").results(Static))
            if len(cards) >= 5:
                cards[0].update(f"Total: {total}")
                cards[1].update(f"[PASS]: {pass_cnt}")
                cards[2].update(f"[FAIL]: {fail_cnt}")
                cards[3].update(f"[SKIPPED]: {skip_cnt}")
                cards[4].update(f"[UNVERIFIED]: {unverified_cnt}")
        except Exception:
            pass

    @on(Button.Pressed, "#btn-retry-selected")
    def on_btn_retry_selected(self) -> None:
        """Handle Retry Selected button press."""
        self.action_retry_selected()

    @on(Button.Pressed, "#btn-retry-all")
    def on_btn_retry_all(self) -> None:
        """Handle Retry All button press."""
        self.action_retry_all()

    def action_export_json(self) -> None:
        """Export audit report to JSON format."""
        self._export_report("json")

    def action_export_csv(self) -> None:
        """Export audit report to CSV format."""
        self._export_report("csv")

    def _perform_export_report(self, out_path: str, fmt: str) -> None:
        """Write audit report to ``out_path`` while guarding against sorted-folder writes."""
        base_dir = self.report_data.get("base_dir") or getattr(
            getattr(self, "app", None), "base_dir", None
        )
        effective_base = str(base_dir) if base_dir else None

        try:
            from app.core.audit_reporter import export_audit_report

            final_path = export_audit_report(
                self.report_data,
                out_path,
                format_type=fmt,
                base_dir=effective_base,
            )
            msg = f"Audit report successfully exported to {final_path}"
            self.announce(msg)
            self.notify(msg, severity="information")
        except Exception as err:
            err_msg = f"Failed to export audit report: {err}"
            logger.error(err_msg)
            self.announce(err_msg)
            self.notify(err_msg, severity="error")

    def _export_report(self, fmt: str) -> None:
        """Prompt for an external export path defaulting to ``<app_dir>/exports``."""
        from app.config import get_app_dir

        clean_fmt = (fmt or "json").strip().lower()
        default_out = str(Path(get_app_dir()) / "exports" / f"audit_report.{clean_fmt}")

        def handle_export_prompt(result: tuple[str, str] | None) -> None:
            if not result:
                return
            chosen_path, chosen_fmt = result
            self._perform_export_report(chosen_path, chosen_fmt or clean_fmt)

        app_ref = getattr(self, "app", None)
        if app_ref is not None and hasattr(app_ref, "push_screen"):
            app_ref.push_screen(
                ExportReportModal(
                    default_path=default_out,
                    default_format=clean_fmt,
                    title="Export Audit Verification Report",
                    format_options=[
                        ("JSON Report (*.json)", "json"),
                        ("CSV Report (*.csv)", "csv"),
                    ],
                ),
                handle_export_prompt,
            )
        else:
            self._perform_export_report(default_out, clean_fmt)

    def action_cancel(self) -> None:
        """Cancel dialog and dismiss modal."""
        self.announce("Closed verification report dialog.")
        self.dismiss()

    @on(Button.Pressed, "#btn-export-json")
    def on_btn_export_json(self) -> None:
        """Handle JSON export button press."""
        self.action_export_json()

    @on(Button.Pressed, "#btn-export-csv")
    def on_btn_export_csv(self) -> None:
        """Handle CSV export button press."""
        self.action_export_csv()

    @on(Button.Pressed, "#btn-close")
    def on_btn_close(self) -> None:
        """Handle Close button press."""
        self.action_cancel()

action_cancel()

Cancel dialog and dismiss modal.

Source code in app/ui/modals/reports.py
1171
1172
1173
1174
def action_cancel(self) -> None:
    """Cancel dialog and dismiss modal."""
    self.announce("Closed verification report dialog.")
    self.dismiss()

action_export_csv()

Export audit report to CSV format.

Source code in app/ui/modals/reports.py
1112
1113
1114
def action_export_csv(self) -> None:
    """Export audit report to CSV format."""
    self._export_report("csv")

action_export_json()

Export audit report to JSON format.

Source code in app/ui/modals/reports.py
1108
1109
1110
def action_export_json(self) -> None:
    """Export audit report to JSON format."""
    self._export_report("json")

action_retry_all()

Retry move operations for all failed items in queue.

Source code in app/ui/modals/reports.py
959
960
961
962
963
964
965
966
967
968
def action_retry_all(self) -> None:
    """Retry move operations for all failed items in queue."""
    failed_records = self._get_failed_records()
    if not failed_records:
        msg = "No failed items to retry."
        self.announce(msg)
        self.notify(msg, severity="warning")
        return

    self._execute_retry(failed_records)

action_retry_selected()

Retry move operation for selected failed item on the active tab.

Source code in app/ui/modals/reports.py
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
def action_retry_selected(self) -> None:
    """Retry move operation for selected failed item on the active tab."""
    active_tab = "tab-all-records"
    with contextlib.suppress(QueryError):
        active_tab = str(
            self.query_one("#audit-tabs", TabbedContent).active or "tab-all-records"
        )

    selected_record: dict[str, Any] | None = None
    if active_tab == "tab-failed-queue":
        failed_table = self.query_one("#failed-items-table", DataTable)
        selected_record = self._resolve_active_row_record(
            failed_table, getattr(self, "_failed_row_records", {})
        )
    else:
        audit_table = self.query_one("#audit-table", DataTable)
        rec = self._resolve_active_row_record(
            audit_table, getattr(self, "_audit_row_records", {})
        )
        if rec and (
            rec.get("status") in ("MISMATCH_FAIL", "MOVE_FAIL") or rec.get("error")
        ):
            selected_record = rec

    if not selected_record:
        msg = "No failed item selected to retry."
        self.announce(msg)
        self.notify(msg, severity="warning")
        return

    self._execute_retry([selected_record])

compose()

Compose verification audit report modal widgets.

Source code in app/ui/modals/reports.py
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
def compose(self) -> ComposeResult:
    """Compose verification audit report modal widgets."""
    with ModalBox(classes="audit-modal-box modal-box"):
        yield Heading(
            "Post-Sort File Integrity Verification Audit Report",
            level=1,
            classes="audit-title",
            id="modal-title",
        )
        base_dir_str = self.report_data.get("base_dir", "")
        yield Label(f"Target Directory: {base_dir_str}", classes="audit-subtitle")

        total = self.report_data.get("total_files", 0)
        pass_cnt = self.report_data.get("verified_pass_count", 0)
        fail_cnt = self.report_data.get("mismatch_fail_count", 0)
        skip_cnt = self.report_data.get("skipped_count", 0)
        unverified_cnt = self.report_data.get("unverified_count", 0)

        with Vertical(classes="modal-body"):
            with Horizontal(classes="audit-stats-row"):
                yield Static(f"Total: {total}", classes="stat-card", markup=False)
                yield Static(
                    f"[PASS]: {pass_cnt}",
                    classes="stat-card stat-pass",
                    markup=False,
                )
                yield Static(
                    f"[FAIL]: {fail_cnt}",
                    classes="stat-card stat-fail",
                    markup=False,
                )
                yield Static(
                    f"[SKIPPED]: {skip_cnt}",
                    classes="stat-card stat-skipped",
                    markup=False,
                )
                yield Static(
                    f"[UNVERIFIED]: {unverified_cnt}",
                    classes="stat-card stat-unverified",
                    markup=False,
                )

            with TabbedContent(initial="tab-all-records", id="audit-tabs"):
                with TabPane("All Verification Records", id="tab-all-records"):
                    with Horizontal(classes="filter-row"):
                        inp = Input(
                            placeholder="Search by filename or path...",
                            id="audit-search-input",
                        )
                        inp.tooltip = (
                            "Filter verification results by filename or path"
                        )
                        yield inp

                        status_sel = Select(
                            [
                                (literal_content("All Statuses"), "ALL"),
                                (
                                    literal_content("Verified Pass [PASS]"),
                                    "VERIFIED_PASS",
                                ),
                                (
                                    literal_content("Mismatch Fail [FAIL]"),
                                    "MISMATCH_FAIL",
                                ),
                                (
                                    literal_content("Move Fail [MOVE FAIL]"),
                                    "MOVE_FAIL",
                                ),
                                (literal_content("Skipped [SKIPPED]"), "SKIPPED"),
                                (
                                    literal_content("Unverified [UNVERIFIED]"),
                                    "UNVERIFIED",
                                ),
                            ],
                            value="ALL",
                            id="audit-status-filter",
                            allow_blank=False,
                        )
                        status_sel.tooltip = "Filter results by verification status"
                        yield status_sel

                    table = DataTable(id="audit-table")
                    table.cursor_type = "row"
                    table.tooltip = "Audit report tabular verification tree"
                    yield table

                with TabPane("Failed Items Queue", id="tab-failed-queue"):
                    failed_table = DataTable(id="failed-items-table")
                    failed_table.cursor_type = "row"
                    failed_table.tooltip = "Dedicated Failed Items queue table"
                    yield failed_table

        with Horizontal(classes="button-row"):
            btn_retry_sel = Button(
                "Retry Selected", id="btn-retry-selected", variant="warning"
            )
            btn_retry_sel.tooltip = (
                "Re-attempt file move operation for selected failed item"
            )
            yield btn_retry_sel

            btn_retry_all = Button("Retry All", id="btn-retry-all", variant="error")
            btn_retry_all.tooltip = (
                "Re-attempt file move operations for all failed items in queue"
            )
            yield btn_retry_all

            btn_json = Button(
                "Export JSON", id="btn-export-json", variant="primary"
            )
            btn_json.tooltip = "Export audit report to an external JSON file"
            yield btn_json

            btn_csv = Button("Export CSV", id="btn-export-csv", variant="success")
            btn_csv.tooltip = "Export audit report to an external CSV file"
            yield btn_csv

            btn_close = Button("Close", id="btn-close", variant="default")
            btn_close.tooltip = "Close verification audit report dialog"
            yield btn_close

on_btn_close()

Handle Close button press.

Source code in app/ui/modals/reports.py
1186
1187
1188
1189
@on(Button.Pressed, "#btn-close")
def on_btn_close(self) -> None:
    """Handle Close button press."""
    self.action_cancel()

on_btn_export_csv()

Handle CSV export button press.

Source code in app/ui/modals/reports.py
1181
1182
1183
1184
@on(Button.Pressed, "#btn-export-csv")
def on_btn_export_csv(self) -> None:
    """Handle CSV export button press."""
    self.action_export_csv()

on_btn_export_json()

Handle JSON export button press.

Source code in app/ui/modals/reports.py
1176
1177
1178
1179
@on(Button.Pressed, "#btn-export-json")
def on_btn_export_json(self) -> None:
    """Handle JSON export button press."""
    self.action_export_json()

on_btn_retry_all()

Handle Retry All button press.

Source code in app/ui/modals/reports.py
1103
1104
1105
1106
@on(Button.Pressed, "#btn-retry-all")
def on_btn_retry_all(self) -> None:
    """Handle Retry All button press."""
    self.action_retry_all()

on_btn_retry_selected()

Handle Retry Selected button press.

Source code in app/ui/modals/reports.py
1098
1099
1100
1101
@on(Button.Pressed, "#btn-retry-selected")
def on_btn_retry_selected(self) -> None:
    """Handle Retry Selected button press."""
    self.action_retry_selected()

on_mount()

Initialize table rows, accessibility announcement, and initial focus.

Source code in app/ui/modals/reports.py
788
789
790
791
792
793
794
795
796
797
798
799
800
801
def on_mount(self) -> None:
    """Initialize table rows, accessibility announcement, and initial focus."""
    super().on_mount()
    self._populate_table()
    total = self.report_data.get("total_files", 0)
    pass_cnt = self.report_data.get("verified_pass_count", 0)
    fail_cnt = self.report_data.get("mismatch_fail_count", 0)
    skip_cnt = self.report_data.get("skipped_count", 0)
    unverified_cnt = self.report_data.get("unverified_count", 0)
    self.query_one("#audit-search-input", Input).focus()
    self.announce(
        f"Opened Audit Verification Report dialog. {total} total files: "
        f"{pass_cnt} passed, {fail_cnt} failed, {skip_cnt} skipped, {unverified_cnt} unverified."
    )

on_search_changed(event)

Handle search input filter update.

Source code in app/ui/modals/reports.py
890
891
892
893
894
@on(Input.Changed, "#audit-search-input")
def on_search_changed(self, event: Input.Changed) -> None:
    """Handle search input filter update."""
    status_val = self.query_one("#audit-status-filter", Select).value
    self._populate_table(search_query=event.value, status_filter=str(status_val))

on_status_changed(event)

Handle status filter dropdown update.

Source code in app/ui/modals/reports.py
896
897
898
899
900
@on(Select.Changed, "#audit-status-filter")
def on_status_changed(self, event: Select.Changed) -> None:
    """Handle status filter dropdown update."""
    search_val = self.query_one("#audit-search-input", Input).value
    self._populate_table(search_query=search_val, status_filter=str(event.value))

ExportReportModal

Bases: ResponsiveModalScreen[tuple[str, str] | None]

Modal dialog for exporting dry-run simulation reports.

Source code in app/ui/modals/reports.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
class ExportReportModal(ResponsiveModalScreen[tuple[str, str] | None]):
    """Modal dialog for exporting dry-run simulation reports."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-subtitle {
        color: $text-muted;
        margin-bottom: 1;
    }
    Button:focus, Input:focus, Select:focus {
        border: heavy $accent;
        text-style: bold;
    }
    ExportReportModal {
        &.compact .modal-box, &.narrow .modal-box {
            width: 95%;
        }
        &.compact .modal-subtitle {
            margin-bottom: 0;
        }
    }
    """

    def __init__(
        self,
        default_path: str = "./simulation_report.html",
        default_format: str = "html",
        *,
        title: str = "Export Simulation Report",
        format_options: list[tuple[str, str]] | None = None,
    ):
        super().__init__()
        self.default_path = default_path
        self.default_format = default_format
        self.modal_title_text = title
        self.format_options = format_options or [
            ("HTML Report (*.html)", "html"),
            ("JSON Data (*.json)", "json"),
        ]

    def compose(self) -> ComposeResult:
        """Compose export report modal widgets."""
        with ModalBox(classes="modal-box"):
            yield Heading(
                self.modal_title_text,
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            with Vertical(classes="modal-body"):
                yield Label(
                    "Select output file path and report format:",
                    classes="modal-subtitle",
                )
                inp = Input(
                    value=self.default_path,
                    placeholder=f"Enter output path (e.g. {self.default_path})...",
                    id="input-export-path",
                )
                inp.tooltip = "Enter external path for exported report file"
                yield inp

                fmt_select = Select(
                    self.format_options,
                    value=self.default_format,
                    id="select-export-format",
                    allow_blank=False,
                )
                yield fmt_select

            with Horizontal(classes="button-row"):
                btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
                btn_cancel.tooltip = "Cancel report export action"
                yield btn_cancel
                btn_export = Button("Export Report", id="btn-export", variant="primary")
                btn_export.tooltip = "Export report to disk"
                yield btn_export

    def on_mount(self) -> None:
        """Focus input field on mount and emit accessibility announcement."""
        super().on_mount()
        self.query_one("#input-export-path", Input).focus()
        self.announce(f"Opened {self.modal_title_text.lower()} dialog.")

    @on(Select.Changed, "#select-export-format")
    def _on_format_changed(self, event: Select.Changed) -> None:
        """Update default file extension when user switches export format."""
        new_fmt = str(event.value or "").strip().lower()
        if not new_fmt:
            return
        for inp in self.query("#input-export-path").results(Input):
            curr = inp.value.strip()
            default_stem = str(Path(self.default_path).with_suffix(""))
            if curr and str(Path(curr).with_suffix("")) == default_stem:
                inp.value = f"{default_stem}.{new_fmt}"

    @on(Input.Submitted, "#input-export-path")
    def action_submit_input(self) -> None:
        """Handle input submission event."""
        self.action_export()

    @on(Button.Pressed, "#btn-export")
    def action_export(self) -> None:
        """Confirm report export and dismiss modal with export parameters."""
        path_val = self.query_one("#input-export-path", Input).value.strip()
        if not path_val:
            self.announce("Output path cannot be empty.")
            return
        format_val = self.query_one("#select-export-format", Select).value or "html"
        self.dismiss((path_val, str(format_val)))

    @on(Button.Pressed, "#btn-cancel")
    def action_cancel(self) -> None:
        """Cancel report export modal."""
        self.dismiss(None)

action_cancel()

Cancel report export modal.

Source code in app/ui/modals/reports.py
503
504
505
506
@on(Button.Pressed, "#btn-cancel")
def action_cancel(self) -> None:
    """Cancel report export modal."""
    self.dismiss(None)

action_export()

Confirm report export and dismiss modal with export parameters.

Source code in app/ui/modals/reports.py
493
494
495
496
497
498
499
500
501
@on(Button.Pressed, "#btn-export")
def action_export(self) -> None:
    """Confirm report export and dismiss modal with export parameters."""
    path_val = self.query_one("#input-export-path", Input).value.strip()
    if not path_val:
        self.announce("Output path cannot be empty.")
        return
    format_val = self.query_one("#select-export-format", Select).value or "html"
    self.dismiss((path_val, str(format_val)))

action_submit_input()

Handle input submission event.

Source code in app/ui/modals/reports.py
488
489
490
491
@on(Input.Submitted, "#input-export-path")
def action_submit_input(self) -> None:
    """Handle input submission event."""
    self.action_export()

compose()

Compose export report modal widgets.

Source code in app/ui/modals/reports.py
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
def compose(self) -> ComposeResult:
    """Compose export report modal widgets."""
    with ModalBox(classes="modal-box"):
        yield Heading(
            self.modal_title_text,
            level=1,
            classes="modal-title",
            id="modal-title",
        )
        with Vertical(classes="modal-body"):
            yield Label(
                "Select output file path and report format:",
                classes="modal-subtitle",
            )
            inp = Input(
                value=self.default_path,
                placeholder=f"Enter output path (e.g. {self.default_path})...",
                id="input-export-path",
            )
            inp.tooltip = "Enter external path for exported report file"
            yield inp

            fmt_select = Select(
                self.format_options,
                value=self.default_format,
                id="select-export-format",
                allow_blank=False,
            )
            yield fmt_select

        with Horizontal(classes="button-row"):
            btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
            btn_cancel.tooltip = "Cancel report export action"
            yield btn_cancel
            btn_export = Button("Export Report", id="btn-export", variant="primary")
            btn_export.tooltip = "Export report to disk"
            yield btn_export

on_mount()

Focus input field on mount and emit accessibility announcement.

Source code in app/ui/modals/reports.py
470
471
472
473
474
def on_mount(self) -> None:
    """Focus input field on mount and emit accessibility announcement."""
    super().on_mount()
    self.query_one("#input-export-path", Input).focus()
    self.announce(f"Opened {self.modal_title_text.lower()} dialog.")

ExtractionPreviewModal

Bases: ResponsiveModalScreen[int | None]

Modal dialog for inspecting sanitized document text and PDF page extraction density.

Source code in app/ui/modals/reports.py
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
class ExtractionPreviewModal(ResponsiveModalScreen[int | None]):
    """Modal dialog for inspecting sanitized document text and PDF page extraction density."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .preview-modal-box {
        max-width: 84;
        min-width: 35;
        max-height: 92%;
    }
    .hidden {
        display: none;
    }
    .file-path-label {
        color: $text-muted;
        margin-bottom: 1;
    }
    .field-label {
        margin-top: 1;
        text-style: bold;
    }
    .preview-table {
        height: auto;
        min-height: 6;
        max-height: 10;
        margin-top: 1;
        margin-bottom: 1;
        border: solid $primary-lighten-2;
    }
    .threshold-row {
        height: 3;
        align: left middle;
    }
    .narrow-input {
        width: 12;
        margin-right: 1;
    }
    .preview-text-box {
        width: 100%;
        height: auto;
        min-height: 3;
        max-height: 10;
        margin-top: 0;
        padding: 0 1;
        border: solid $accent;
        color: $text;
    }
    ExtractionPreviewModal {
        &.compact .preview-modal-box, &.narrow .preview-modal-box {
            padding: 0 1;
            width: 96%;
        }
        &.compact .modal-title {
            margin-bottom: 0;
        }
        &.compact .file-path-label {
            margin-bottom: 0;
        }
        &.compact .field-label {
            margin-top: 0;
        }
        &.compact .preview-table {
            margin-top: 0;
            margin-bottom: 0;
        }
        &.compact .threshold-row {
            height: 1;
        }
        &.compact .narrow-input {
            height: 1;
            border: none;
        }
        &.compact .preview-text-box {
            min-height: 2;
            max-height: 4;
        }
        &.compact .button-row {
            margin-top: 0;
        }
        &.compact .button-row Button {
            height: 1;
            min-height: 1;
            border: none;
            margin: 0;
        }
    }
    """

    MAX_PREVIEW_CHARS: int = 8000

    def __init__(
        self,
        file_path: str,
        settings: Any,
        db: Any = None,
        base_dir: str | None = None,
    ) -> None:
        super().__init__()
        self.file_path = file_path
        self.settings = settings
        self.db = db
        self.base_dir = base_dir
        self.is_pdf = str(file_path).lower().endswith(".pdf")
        self.initial_threshold = getattr(settings, "PDF_TEXT_DENSITY_THRESHOLD", 50)
        self.current_threshold = self.initial_threshold
        self.page_data: list[dict] = []
        self.sanitized_text: str = ""
        self.text_source: str = "missing"

    def compose(self) -> ComposeResult:
        """Compose modal dialog children widgets."""
        heading_title = (
            "PDF Extraction Strategy Preview"
            if self.is_pdf
            else "Document Extraction Preview"
        )
        pdf_section_cls = "" if self.is_pdf else "hidden"
        with ModalBox(classes="preview-modal-box modal-box"):
            yield Heading(
                heading_title,
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            with Vertical(classes="modal-body"):
                yield Label(
                    f"File: {os.path.basename(self.file_path)}",
                    classes="file-path-label",
                )

                with Vertical(id="pdf-density-section", classes=pdf_section_cls):
                    yield Label(
                        "Density Threshold (chars/page):", classes="field-label"
                    )
                    with Horizontal(classes="threshold-row"):
                        thresh_inp = Input(
                            value=str(self.current_threshold),
                            placeholder="Density Threshold (chars/page)",
                            name="Density Threshold",
                            id="preview-input-threshold",
                            classes="narrow-input",
                        )
                        thresh_inp.tooltip = (
                            "Adjust PDF text density threshold in characters per page"
                        )
                        setattr(thresh_inp, "label", "Density Threshold (chars/page)")
                        yield thresh_inp
                        slider = DensitySlider(
                            value=self.current_threshold,
                            min_value=0,
                            max_value=500,
                            step=5,
                            announce_formatter=self._format_slider_announcement,
                            id="preview-slider-threshold",
                        )
                        slider.tooltip = "Adjust PDF text density threshold slider"
                        yield slider

                    yield DataTable(id="preview-table", classes="preview-table")
                    yield Label("", id="preview-summary-label")

                yield Label(
                    "Sanitized Extracted Text:",
                    classes="field-label",
                    id="preview-text-heading",
                )
                yield Static(
                    "",
                    id="preview-extracted-text",
                    classes="preview-text-box",
                    markup=False,
                )

            with Horizontal(classes="button-row"):
                cancel_label = "Cancel" if self.is_pdf else "Close"
                btn_cancel = Button(
                    cancel_label, id="btn-preview-cancel", variant="default"
                )
                btn_cancel.tooltip = "Close preview dialog without saving settings"
                yield btn_cancel
                if self.is_pdf:
                    btn_save = Button(
                        "Save & Apply", id="btn-preview-save", variant="primary"
                    )
                    btn_save.tooltip = "Save density threshold to settings and apply"
                    yield btn_save

    def _load_sanitized_text(self) -> str:
        """Read and scrub extracted document text without network calls."""
        from app.core.extractor import _read_preview_text_offline
        from app.core.path_utils import scrub_user_home_paths
        from app.core.text_utils import sanitize_secret_patterns

        eff_db = self.db if self.db is not None else getattr(self.app, "db", None)
        eff_base = (
            self.base_dir
            if self.base_dir is not None
            else getattr(self.app, "base_dir", None)
        )

        raw_text, source_kind = _read_preview_text_offline(
            self.file_path,
            settings=self.settings,
            db=eff_db,
            base_dir=eff_base,
        )
        self.text_source = source_kind

        if not raw_text or not raw_text.strip():
            return "(No extractable text found in document.)"

        scrubbed = sanitize_secret_patterns(
            scrub_user_home_paths(raw_text),
            replacement="[REDACTED]",
        ).strip()
        if not scrubbed:
            return "(No extractable text found in document.)"

        if len(scrubbed) > self.MAX_PREVIEW_CHARS:
            scrubbed = scrubbed[: self.MAX_PREVIEW_CHARS] + "\n... [Preview truncated]"
        return scrubbed

    def on_mount(self) -> None:
        """Handle modal mount event and populate initial preview data."""
        super().on_mount()
        table = self.query_one("#preview-table", DataTable)
        table.add_columns("Page", "Embedded Chars", "Vector Paths", "Predicted Status")

        if self.is_pdf:
            from app.core.extractor_strategies import PdfExtractor

            extractor = PdfExtractor()
            # Light structural analysis without EasyOCR model passes
            self.page_data = extractor.preview_pdf_density(
                self.file_path, density_threshold=self.current_threshold
            )
            self._update_table()

        self.sanitized_text = self._load_sanitized_text()
        try:
            text_widget = self.query_one("#preview-extracted-text", Static)
            text_widget.update(self.sanitized_text)
        except Exception:
            pass

        fname = os.path.basename(self.file_path)
        if self.is_pdf:
            self.announce(
                f"Opened PDF extraction preview for '{fname}' ({len(self.page_data)} page(s))."
            )
        else:
            self.announce(f"Opened document text preview for '{fname}'.")

    def _update_table(self) -> None:
        """Re-evaluate page extraction decisions and update table display."""
        table = self.query_one("#preview-table", DataTable)
        table.clear()
        std_count = 0
        rast_count = 0

        for page in self.page_data:
            char_count = page["char_count"]
            has_vector = page["has_vector"]
            if char_count >= self.current_threshold and not has_vector:
                status_text = Text("STANDARD", style="bold green")
                std_count += 1
            else:
                status_text = Text("RASTERIZED", style="bold yellow")
                rast_count += 1

            vector_str = "Yes" if has_vector else "No"
            table.add_row(
                f"Page {page['page_index']}",
                str(char_count),
                vector_str,
                status_text,
            )

        summary_label = self.query_one("#preview-summary-label", Label)
        summary_label.update(
            f"Total Pages: {len(self.page_data)} | Standard: {std_count} | Rasterized (OCR): {rast_count}"
        )

    def _format_slider_announcement(self, val: int) -> str:
        """Format contextual screen reader announcement with page status totals."""
        std_count = sum(
            1
            for p in self.page_data
            if p.get("char_count", 0) >= val and not p.get("has_vector", False)
        )
        rast_count = len(self.page_data) - std_count
        return (
            f"Density threshold set to {val}: {len(self.page_data)} total pages "
            f"({std_count} standard, {rast_count} rasterized)"
        )

    @on(DensitySlider.Changed, "#preview-slider-threshold")
    def _on_slider_changed(self, event: DensitySlider.Changed) -> None:
        """Handle slider value changes by updating input and re-evaluating preview table."""
        if self.current_threshold != event.value:
            self.current_threshold = event.value
            try:
                inp = self.query_one("#preview-input-threshold", Input)
                if inp.value != str(event.value):
                    inp.value = str(event.value)
            except Exception:
                pass
            self._update_table()

    @on(Input.Changed, "#preview-input-threshold")
    def _on_input_changed(self, event: Input.Changed) -> None:
        """Handle input text changes by updating slider and re-evaluating preview table."""
        try:
            val = int(event.value.strip())
            if val >= 0 and self.current_threshold != val:
                self.current_threshold = val
                try:
                    slider = self.query_one("#preview-slider-threshold", DensitySlider)
                    if (
                        slider.value != val
                        and slider.min_value <= val <= slider.max_value
                    ):
                        slider.value = val
                except Exception:
                    pass
                self._update_table()
        except Exception:
            pass

    @on(Button.Pressed, "#btn-preview-save")
    def action_save_threshold(self) -> None:
        """Save updated density threshold to settings and dismiss modal."""
        if hasattr(self.settings, "PDF_TEXT_DENSITY_THRESHOLD"):
            self.settings.PDF_TEXT_DENSITY_THRESHOLD = self.current_threshold
        if hasattr(self.settings, "_save"):
            self.settings._save()
        self.announce(f"Saved PDF text density threshold: {self.current_threshold}")
        self.dismiss(self.current_threshold)

    @on(Button.Pressed, "#btn-preview-cancel")
    def action_cancel(self) -> None:
        """Cancel preview dialog and dismiss modal."""
        self.announce("Cancelled PDF extraction preview.")
        self.dismiss(None)

action_cancel()

Cancel preview dialog and dismiss modal.

Source code in app/ui/modals/reports.py
380
381
382
383
384
@on(Button.Pressed, "#btn-preview-cancel")
def action_cancel(self) -> None:
    """Cancel preview dialog and dismiss modal."""
    self.announce("Cancelled PDF extraction preview.")
    self.dismiss(None)

action_save_threshold()

Save updated density threshold to settings and dismiss modal.

Source code in app/ui/modals/reports.py
370
371
372
373
374
375
376
377
378
@on(Button.Pressed, "#btn-preview-save")
def action_save_threshold(self) -> None:
    """Save updated density threshold to settings and dismiss modal."""
    if hasattr(self.settings, "PDF_TEXT_DENSITY_THRESHOLD"):
        self.settings.PDF_TEXT_DENSITY_THRESHOLD = self.current_threshold
    if hasattr(self.settings, "_save"):
        self.settings._save()
    self.announce(f"Saved PDF text density threshold: {self.current_threshold}")
    self.dismiss(self.current_threshold)

compose()

Compose modal dialog children widgets.

Source code in app/ui/modals/reports.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def compose(self) -> ComposeResult:
    """Compose modal dialog children widgets."""
    heading_title = (
        "PDF Extraction Strategy Preview"
        if self.is_pdf
        else "Document Extraction Preview"
    )
    pdf_section_cls = "" if self.is_pdf else "hidden"
    with ModalBox(classes="preview-modal-box modal-box"):
        yield Heading(
            heading_title,
            level=1,
            classes="modal-title",
            id="modal-title",
        )
        with Vertical(classes="modal-body"):
            yield Label(
                f"File: {os.path.basename(self.file_path)}",
                classes="file-path-label",
            )

            with Vertical(id="pdf-density-section", classes=pdf_section_cls):
                yield Label(
                    "Density Threshold (chars/page):", classes="field-label"
                )
                with Horizontal(classes="threshold-row"):
                    thresh_inp = Input(
                        value=str(self.current_threshold),
                        placeholder="Density Threshold (chars/page)",
                        name="Density Threshold",
                        id="preview-input-threshold",
                        classes="narrow-input",
                    )
                    thresh_inp.tooltip = (
                        "Adjust PDF text density threshold in characters per page"
                    )
                    setattr(thresh_inp, "label", "Density Threshold (chars/page)")
                    yield thresh_inp
                    slider = DensitySlider(
                        value=self.current_threshold,
                        min_value=0,
                        max_value=500,
                        step=5,
                        announce_formatter=self._format_slider_announcement,
                        id="preview-slider-threshold",
                    )
                    slider.tooltip = "Adjust PDF text density threshold slider"
                    yield slider

                yield DataTable(id="preview-table", classes="preview-table")
                yield Label("", id="preview-summary-label")

            yield Label(
                "Sanitized Extracted Text:",
                classes="field-label",
                id="preview-text-heading",
            )
            yield Static(
                "",
                id="preview-extracted-text",
                classes="preview-text-box",
                markup=False,
            )

        with Horizontal(classes="button-row"):
            cancel_label = "Cancel" if self.is_pdf else "Close"
            btn_cancel = Button(
                cancel_label, id="btn-preview-cancel", variant="default"
            )
            btn_cancel.tooltip = "Close preview dialog without saving settings"
            yield btn_cancel
            if self.is_pdf:
                btn_save = Button(
                    "Save & Apply", id="btn-preview-save", variant="primary"
                )
                btn_save.tooltip = "Save density threshold to settings and apply"
                yield btn_save

on_mount()

Handle modal mount event and populate initial preview data.

Source code in app/ui/modals/reports.py
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def on_mount(self) -> None:
    """Handle modal mount event and populate initial preview data."""
    super().on_mount()
    table = self.query_one("#preview-table", DataTable)
    table.add_columns("Page", "Embedded Chars", "Vector Paths", "Predicted Status")

    if self.is_pdf:
        from app.core.extractor_strategies import PdfExtractor

        extractor = PdfExtractor()
        # Light structural analysis without EasyOCR model passes
        self.page_data = extractor.preview_pdf_density(
            self.file_path, density_threshold=self.current_threshold
        )
        self._update_table()

    self.sanitized_text = self._load_sanitized_text()
    try:
        text_widget = self.query_one("#preview-extracted-text", Static)
        text_widget.update(self.sanitized_text)
    except Exception:
        pass

    fname = os.path.basename(self.file_path)
    if self.is_pdf:
        self.announce(
            f"Opened PDF extraction preview for '{fname}' ({len(self.page_data)} page(s))."
        )
    else:
        self.announce(f"Opened document text preview for '{fname}'.")

app.ui.modals.rules

app.ui.modals.rules

Rule template gallery and rule import dialogs.

ActiveRuleManagerModal

Bases: _CancelToCloseMixin, ResponsiveModalScreen[bool]

Dedicated modal screen for viewing, adding, editing, toggling, and deleting rules.

Source code in app/ui/modals/rules.py
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
class ActiveRuleManagerModal(_CancelToCloseMixin, ResponsiveModalScreen[bool]):
    """Dedicated modal screen for viewing, adding, editing, toggling, and deleting rules."""

    BINDINGS = [
        Binding("escape", "cancel", "Close manager", show=True),
        Binding("space", "toggle_rule", "Toggle Rule", show=False),
        Binding("enter", "edit_rule", "Edit Rule", show=False),
        Binding("delete", "delete_rule", "Delete Rule", show=False),
        Binding("ctrl+i", "import_rules", "Import Rules", show=True),
        Binding("i", "import_rules", "Import Rules", show=False),
        Binding("ctrl+e", "export_rules", "Export Rules", show=True),
        Binding("e", "export_rules", "Export Rules", show=False),
        Binding("ctrl+b", "browse_templates", "Browse Templates", show=True),
        Binding("b", "browse_templates", "Browse Templates", show=False),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .rule-manager-box {
        max-width: 88;
        min-width: 35;
        max-height: 92%;
    }
    #rules-table {
        height: auto;
        max-height: 15;
        min-height: 6;
        margin-top: 1;
        margin-bottom: 1;
    }
    .button-row {
        layout: grid;
        grid-size: 4;
        grid-columns: 1fr 1fr 1fr 1fr;
        grid-gutter: 0 1;
    }
    .button-row Button {
        width: 100%;
        min-width: 0;
        padding: 0 1;
        margin: 0;
    }
    Button:focus, DataTable:focus {
        border: heavy $accent;
        text-style: bold;
    }
    ActiveRuleManagerModal {
        &.compact .modal-title {
            margin-bottom: 0;
        }
        &.compact #rules-table {
            margin-top: 0;
            margin-bottom: 0;
        }
        &.compact .button-row, &.narrow .button-row {
            margin-top: 0;
            grid-size: 2;
            grid-columns: 1fr 1fr;
        }
        &.compact .button-row Button, &.narrow .button-row Button {
            height: 1;
            min-height: 1;
            border: none;
            padding: 0;
            margin: 0;
        }
    }
    """

    def __init__(self, settings):
        super().__init__()
        self.settings = settings
        self._rules_data: list[dict] = []
        self._mutated: bool = False

    @staticmethod
    def _ensure_rules_table_columns(table: DataTable) -> None:
        """Configure ActiveRuleManagerModal table columns idempotently."""
        table.cursor_type = "row"
        if not table.columns:
            table.add_columns(
                "Status", "Type", "Action", "Pattern", "Target Folder", "Priority"
            )

    def _populate_rules_table(self, table: DataTable, prev_cursor: int = 0) -> None:
        """Populate rules table rows from current settings."""
        self._ensure_rules_table_columns(table)
        self._rules_data = self._load_rules_data()
        table.clear()
        for idx, r in enumerate(self._rules_data):
            table.add_row(
                r["status"],
                r["type"],
                r.get("action", "move"),
                r["pattern"],
                r["target_folder"],
                str(r["priority"]),
                key=f"rule_row_{idx}",
            )
        if self._rules_data:
            target_row = max(0, min(prev_cursor, len(self._rules_data) - 1))
            table.move_cursor(row=target_row)

    def compose(self) -> ComposeResult:
        """Compose active rule manager children."""
        with ModalBox(classes="rule-manager-box modal-box"):
            yield Heading(
                "Active Rule Manager",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            with Vertical(classes="modal-body"):
                yield Label(
                    "Manage keyword rules and policies. Select a rule to edit, toggle, or delete:",
                    id="lbl-rules-desc",
                )
                table = DataTable(id="rules-table")
                self._populate_rules_table(table)
                yield table
            with Vertical(classes="modal-footer"):
                with Horizontal(classes="button-row"):
                    btn_toggle = Button(
                        "Toggle Status", id="btn-toggle-rule", variant="default"
                    )
                    btn_toggle.tooltip = (
                        "Toggle active/disabled status of selected rule"
                    )
                    yield btn_toggle
                    btn_delete = Button(
                        "Delete Rule", id="btn-delete-rule", variant="error"
                    )
                    btn_delete.tooltip = "Delete selected rule after confirmation"
                    yield btn_delete
                    btn_edit = Button(
                        "Edit Rule", id="btn-edit-rule", variant="default"
                    )
                    btn_edit.tooltip = (
                        "Edit pattern or destination folder of selected rule"
                    )
                    yield btn_edit
                    btn_add = Button("Add Rule", id="btn-add-rule", variant="primary")
                    btn_add.tooltip = "Add a new keyword rule or policy"
                    yield btn_add

                with Horizontal(classes="button-row"):
                    btn_close = Button("Close", id="btn-close-rules", variant="default")
                    btn_close.tooltip = "Close active rule manager"
                    yield btn_close
                    btn_import = Button(
                        "Import Rules", id="btn-import-rules", variant="default"
                    )
                    btn_import.tooltip = "Import rules from Hazel, DropIt, or TagSpaces"
                    yield btn_import
                    btn_export = Button(
                        "Export Rules", id="btn-export-rules", variant="default"
                    )
                    btn_export.tooltip = (
                        "Export active rules to Sortify JSON, Hazel, or DropIt"
                    )
                    yield btn_export
                    btn_browse = Button(
                        "Browse Templates",
                        id="btn-browse-templates",
                        variant="primary",
                    )
                    btn_browse.tooltip = "Browse and apply starter rule templates"
                    yield btn_browse

    def on_mount(self) -> None:
        """Set up columns and load rules on mount."""
        super().on_mount()
        try:
            table = self.query_one("#rules-table", DataTable)
        except NoMatches:
            return
        if not table.columns:
            self._populate_rules_table(table)
        if self.focused is None:
            table.focus()
        masked_rows = [r for r in self._rules_data if r.get("masked_by")]
        if masked_rows:
            self.announce(
                f"Opened active rule manager. Warning: {len(masked_rows)} policy rule(s) masked by higher-priority rules."
            )
        else:
            self.announce("Opened active rule manager.")

    def _load_rules_data(self) -> list[dict]:
        """Aggregate active keyword rules, disabled keyword rules, learned rules, and policies with masking detection."""
        from app.core.policy_engine import compute_active_rule_masking

        masked_map = compute_active_rule_masking(self.settings)
        rules = []
        kw_rules = getattr(self.settings, "KEYWORD_RULES", {}) or {}
        for kw, target in sorted(kw_rules.items()):
            masker = masked_map.get(("keyword", kw))
            status_str = f"⚠ Masked by '{masker}'" if masker is not None else "Active"
            rules.append(
                {
                    "kind": "keyword",
                    "status": status_str,
                    "enabled": True,
                    "masked_by": masker,
                    "type": "keyword",
                    "action": "move",
                    "pattern": str(kw),
                    "target_folder": str(target),
                    "priority": 80,
                    "original_key": kw,
                }
            )

        dis_rules = getattr(self.settings, "DISABLED_KEYWORD_RULES", {}) or {}
        for kw, target in sorted(dis_rules.items()):
            rules.append(
                {
                    "kind": "keyword",
                    "status": "Disabled",
                    "enabled": False,
                    "masked_by": None,
                    "type": "keyword",
                    "action": "move",
                    "pattern": str(kw),
                    "target_folder": str(target),
                    "priority": 80,
                    "original_key": kw,
                }
            )

        learned_rules = getattr(self.settings, "LEARNED_RULES", {}) or {}
        for kw, target in sorted(learned_rules.items()):
            masker = masked_map.get(("learned", kw))
            status_str = f"⚠ Masked by '{masker}'" if masker is not None else "Active"
            rules.append(
                {
                    "kind": "learned",
                    "status": status_str,
                    "enabled": True,
                    "masked_by": masker,
                    "type": "learned",
                    "action": "move",
                    "pattern": str(kw),
                    "target_folder": str(target),
                    "priority": 90,
                    "original_key": kw,
                }
            )

        dis_learned_rules = getattr(self.settings, "DISABLED_LEARNED_RULES", {}) or {}
        for kw, target in sorted(dis_learned_rules.items()):
            rules.append(
                {
                    "kind": "learned",
                    "status": "Disabled",
                    "enabled": False,
                    "masked_by": None,
                    "type": "learned",
                    "action": "move",
                    "pattern": str(kw),
                    "target_folder": str(target),
                    "priority": 90,
                    "original_key": kw,
                }
            )

        policies = getattr(self.settings, "POLICIES", []) or []
        for idx, pol in enumerate(policies):
            if isinstance(pol, dict):
                is_enabled = bool(pol.get("enabled", True))
                masker = masked_map.get(("policy", idx)) if is_enabled else None
                if not is_enabled:
                    status_str = "Disabled"
                elif masker is not None:
                    status_str = f"⚠ Masked by '{masker}'"
                else:
                    status_str = "Active"
                pol_type_raw = str(pol.get("type", "policy"))
                raw_action = str(pol.get("action") or "").strip()
                display_action = raw_action or (
                    "unarchive"
                    if pol_type_raw.lower() == "unarchive"
                    else (
                        "trash"
                        if pol_type_raw.lower() == "duplicate"
                        and not str(pol.get("target_path", ""))
                        else "move"
                    )
                )
                rules.append(
                    {
                        "kind": "policy",
                        "status": status_str,
                        "enabled": is_enabled,
                        "masked_by": masker,
                        "type": _format_policy_type_badge(pol),
                        "pattern": str(pol.get("expression", "")),
                        "target_folder": str(pol.get("target_path", "")),
                        "rename_pattern": str(pol.get("rename_pattern", "") or ""),
                        "priority": pol.get("priority", 0),
                        "halting": bool(pol.get("halting", False)),
                        "action": display_action,
                        "policy_idx": idx,
                        "original": copy.deepcopy(pol),
                    }
                )
        return rules

    def _refresh_table(self, preserve_focus: bool = True) -> None:
        """Re-populate rules table from settings while preserving cursor and focus."""
        table = self.query_one("#rules-table", DataTable)
        focused = self.focused
        had_table_focus = focused is table
        prev_cursor = table.cursor_row if table.row_count > 0 else 0

        self._populate_rules_table(table, prev_cursor=prev_cursor)

        if preserve_focus:
            if had_table_focus:
                table.focus()
            elif focused and getattr(focused, "id", None):
                try:
                    self.query_one(f"#{focused.id}").focus()
                except Exception:
                    table.focus()

    def _get_selected_rule(self) -> dict | None:
        """Return the currently highlighted rule dictionary."""
        table = self.query_one("#rules-table", DataTable)
        if not self._rules_data or table.row_count == 0:
            return None
        row_idx = table.cursor_row
        if 0 <= row_idx < len(self._rules_data):
            return self._rules_data[row_idx]
        return None

    @on(DataTable.RowSelected, "#rules-table")
    def on_row_selected(self, event: DataTable.RowSelected) -> None:
        """Trigger editing when pressing Enter on a rule row."""
        self.action_edit_rule()

    @on(Button.Pressed, "#btn-toggle-rule")
    def action_toggle_rule(self) -> None:
        """Toggle active/disabled status of selected rule."""
        rule = self._get_selected_rule()
        if not rule:
            self.announce("No rule selected to toggle.")
            return

        if rule["kind"] == "keyword":
            kw = rule["original_key"]
            kw_rules = dict(getattr(self.settings, "KEYWORD_RULES", {}) or {})
            dis_rules = dict(getattr(self.settings, "DISABLED_KEYWORD_RULES", {}) or {})

            if rule.get("enabled", rule["status"] == "Active"):
                target = kw_rules.pop(kw, rule["target_folder"])
                dis_rules[kw] = target
                new_status = "Disabled"
            else:
                target = dis_rules.pop(kw, rule["target_folder"])
                kw_rules[kw] = target
                new_status = "Active"

            self.settings.KEYWORD_RULES = kw_rules
            self.settings.DISABLED_KEYWORD_RULES = dis_rules
            if hasattr(self.settings, "flush"):
                self.settings.flush()
            msg = f"Toggled keyword rule '{kw}' to {new_status}."
        elif rule["kind"] == "learned":
            kw = rule["original_key"]
            learned_rules = dict(getattr(self.settings, "LEARNED_RULES", {}) or {})
            dis_learned = dict(
                getattr(self.settings, "DISABLED_LEARNED_RULES", {}) or {}
            )
            if rule.get("enabled", rule["status"] == "Active"):
                target = learned_rules.pop(kw, rule["target_folder"])
                dis_learned[kw] = target
                new_status = "Disabled"
            else:
                target = dis_learned.pop(kw, rule["target_folder"])
                learned_rules[kw] = target
                new_status = "Active"
            self.settings.LEARNED_RULES = learned_rules
            self.settings.DISABLED_LEARNED_RULES = dis_learned
            if hasattr(self.settings, "flush"):
                self.settings.flush()
            msg = f"Toggled learned rule '{kw}' to {new_status}."
        elif rule["kind"] == "policy":
            policies = [
                copy.deepcopy(p) for p in getattr(self.settings, "POLICIES", []) or []
            ]
            idx = rule["policy_idx"]
            if 0 <= idx < len(policies):
                curr = policies[idx].get("enabled", True)
                policies[idx]["enabled"] = not curr
                new_status = "Active" if not curr else "Disabled"
                self.settings.POLICIES = policies
                if hasattr(self.settings, "flush"):
                    self.settings.flush()
                msg = f"Toggled policy '{rule['pattern']}' to {new_status}."
            else:
                return
        else:
            return

        self._mutated = True
        self._refresh_table(preserve_focus=True)
        self.announce(msg)
        if hasattr(self.app, "notify"):
            self.app.notify(msg)

    @on(Button.Pressed, "#btn-add-rule")
    def action_add_rule(self) -> None:
        """Open editor modal to add a new keyword rule or compound policy."""

        def on_rule_added(result: dict | None) -> None:
            if not result:
                return
            res_kind = result.get(
                "kind", "policy" if result.get("is_policy") else "keyword"
            )
            pattern = result["pattern"]
            target = result["target"]

            if res_kind == "policy":
                pol_payload = copy.deepcopy(
                    result.get("policy")
                    or {
                        "type": "keyword",
                        "expression": pattern,
                        "target_path": target,
                        "priority": 0,
                        "halting": False,
                        "enabled": True,
                    }
                )
                policies = [
                    copy.deepcopy(p)
                    for p in getattr(self.settings, "POLICIES", []) or []
                ]
                policies.append(pol_payload)
                self.settings.POLICIES = policies
                if hasattr(self.settings, "flush"):
                    self.settings.flush()
                msg = f"Added policy '{pattern}' (priority {pol_payload.get('priority', 0)})."
            else:
                kw_rules = dict(getattr(self.settings, "KEYWORD_RULES", {}) or {})
                kw_rules[pattern] = target
                self.settings.KEYWORD_RULES = kw_rules
                if hasattr(self.settings, "flush"):
                    self.settings.flush()
                msg = f"Added rule '{pattern}' routing to '{target}'."

            self._mutated = True
            self._refresh_table(preserve_focus=False)
            masked_now = [
                r
                for r in self._rules_data
                if r.get("masked_by") and r.get("pattern") == pattern
            ]
            if masked_now:
                msg = f"{msg} Warning: masked by higher-priority rule '{masked_now[0]['masked_by']}'."
            self.announce(msg)
            if hasattr(self.app, "notify"):
                self.app.notify(msg)

        self.app.push_screen(
            RuleEditModal(
                title="Add Rule",
                settings=self.settings,
                base_dir=getattr(self.app, "base_dir", None),
                source_dirs=getattr(self.app, "source_dirs", None),
                db=getattr(self.app, "db", None),
            ),
            on_rule_added,
        )

    @on(Button.Pressed, "#btn-edit-rule")
    def action_edit_rule(self) -> None:
        """Open editor modal to edit the selected keyword rule or policy."""
        rule = self._get_selected_rule()
        if not rule:
            self.announce("No rule selected to edit.")
            return

        def on_rule_edited(result: dict | None) -> None:
            if not result:
                return
            res_kind = result.get(
                "kind",
                "policy"
                if (result.get("is_policy") and isinstance(result.get("policy"), dict))
                else rule["kind"],
            )
            new_pattern = result["pattern"]
            new_target = result["target"]

            if rule["kind"] == "policy" and res_kind == "policy":
                policies = [
                    copy.deepcopy(p)
                    for p in getattr(self.settings, "POLICIES", []) or []
                ]
                idx = rule["policy_idx"]
                if 0 <= idx < len(policies):
                    if "policy" in result and isinstance(result["policy"], dict):
                        updated_pol = copy.deepcopy(policies[idx])
                        updated_pol.update(copy.deepcopy(result["policy"]))
                        for opt_key in (
                            "action",
                            "rename_pattern",
                            "match_mode",
                            "conditions",
                            "negate",
                            "regex",
                            "case_sensitive",
                        ):
                            if opt_key not in result["policy"]:
                                updated_pol.pop(opt_key, None)
                        policies[idx] = updated_pol
                    else:
                        policies[idx]["expression"] = new_pattern
                        policies[idx]["target_path"] = new_target
                    self.settings.POLICIES = policies
                    if hasattr(self.settings, "flush"):
                        self.settings.flush()
                    msg = f"Updated policy '{new_pattern}'."
                else:
                    return
            elif rule["kind"] in ("keyword", "learned") and res_kind == "policy":
                old_key = rule["original_key"]
                is_active = bool(rule.get("enabled", rule["status"] == "Active"))
                if rule["kind"] == "learned":
                    d_name = "LEARNED_RULES" if is_active else "DISABLED_LEARNED_RULES"
                else:
                    d_name = "KEYWORD_RULES" if is_active else "DISABLED_KEYWORD_RULES"
                r_dict = dict(getattr(self.settings, d_name, {}) or {})
                r_dict.pop(old_key, None)
                setattr(self.settings, d_name, r_dict)
                policies = [
                    copy.deepcopy(p)
                    for p in getattr(self.settings, "POLICIES", []) or []
                ]
                new_pol = copy.deepcopy(result["policy"])
                new_pol["enabled"] = is_active
                policies.append(new_pol)
                self.settings.POLICIES = policies
                if hasattr(self.settings, "flush"):
                    self.settings.flush()
                msg = f"Converted rule '{new_pattern}' into a policy."
            elif rule["kind"] == "policy" and res_kind == "keyword":
                policies = [
                    copy.deepcopy(p)
                    for p in getattr(self.settings, "POLICIES", []) or []
                ]
                idx = rule["policy_idx"]
                if 0 <= idx < len(policies):
                    was_enabled = bool(policies[idx].get("enabled", True))
                    policies.pop(idx)
                    self.settings.POLICIES = policies
                    d_name = (
                        "KEYWORD_RULES" if was_enabled else "DISABLED_KEYWORD_RULES"
                    )
                    r_dict = dict(getattr(self.settings, d_name, {}) or {})
                    r_dict[new_pattern] = new_target
                    setattr(self.settings, d_name, r_dict)
                    if hasattr(self.settings, "flush"):
                        self.settings.flush()
                    msg = f"Converted policy '{new_pattern}' into a keyword rule."
                else:
                    return
            elif rule["kind"] == "keyword":
                old_key = rule["original_key"]
                is_active = bool(rule.get("enabled", rule["status"] == "Active"))
                dict_name = "KEYWORD_RULES" if is_active else "DISABLED_KEYWORD_RULES"
                rules_dict = dict(getattr(self.settings, dict_name, {}) or {})
                if old_key in rules_dict and old_key != new_pattern:
                    del rules_dict[old_key]
                rules_dict[new_pattern] = new_target
                setattr(self.settings, dict_name, rules_dict)
                if hasattr(self.settings, "flush"):
                    self.settings.flush()
                msg = f"Updated rule '{new_pattern}' target folder to '{new_target}'."
            elif rule["kind"] == "learned":
                old_key = rule["original_key"]
                is_active = bool(rule.get("enabled", rule["status"] == "Active"))
                src_dict_name = (
                    "LEARNED_RULES" if is_active else "DISABLED_LEARNED_RULES"
                )
                learned_dict = dict(getattr(self.settings, src_dict_name, {}) or {})
                if res_kind == "keyword":
                    learned_dict.pop(old_key, None)
                    setattr(self.settings, src_dict_name, learned_dict)
                    dst_dict_name = (
                        "KEYWORD_RULES" if is_active else "DISABLED_KEYWORD_RULES"
                    )
                    kw_dict = dict(getattr(self.settings, dst_dict_name, {}) or {})
                    kw_dict[new_pattern] = new_target
                    setattr(self.settings, dst_dict_name, kw_dict)
                    msg = f"Converted learned rule '{new_pattern}' into a keyword rule."
                else:
                    if old_key in learned_dict and old_key != new_pattern:
                        del learned_dict[old_key]
                    learned_dict[new_pattern] = new_target
                    setattr(self.settings, src_dict_name, learned_dict)
                    msg = f"Updated learned rule '{new_pattern}' target folder to '{new_target}'."
                if hasattr(self.settings, "flush"):
                    self.settings.flush()
            else:
                return

            self._mutated = True
            self._refresh_table(preserve_focus=True)
            self.announce(msg)
            if hasattr(self.app, "notify"):
                self.app.notify(msg)

        orig_raw = rule.get("original")
        orig_pol: dict[str, Any] = (
            copy.deepcopy(orig_raw) if isinstance(orig_raw, dict) else {}
        )
        self.app.push_screen(
            RuleEditModal(
                title=f"Edit Rule: {rule['pattern']}",
                pattern=rule["pattern"],
                target_folder=rule["target_folder"],
                policy=orig_pol if rule["kind"] == "policy" else None,
                rule_kind=rule["kind"],
                policy_type=str(orig_pol.get("type", "keyword")),
                priority=int(orig_pol.get("priority", rule.get("priority", 0)) or 0),
                halting=bool(orig_pol.get("halting", False)),
                action=str(orig_pol.get("action") or ""),
                enabled=bool(rule.get("enabled", True)),
                settings=self.settings,
                base_dir=getattr(self.app, "base_dir", None),
                source_dirs=getattr(self.app, "source_dirs", None),
                db=getattr(self.app, "db", None),
                rename_pattern=str(
                    orig_pol.get("rename_pattern") or rule.get("rename_pattern") or ""
                ),
            ),
            on_rule_edited,
        )

    @on(Button.Pressed, "#btn-delete-rule")
    def action_delete_rule(self) -> None:
        """Delete selected rule after user confirmation."""
        rule = self._get_selected_rule()
        if not rule:
            self.announce("No rule selected to delete.")
            return

        pattern = rule["pattern"]

        def on_confirmed(confirmed: bool | None) -> None:
            if not confirmed:
                return

            if rule["kind"] == "keyword":
                key = rule["original_key"]
                is_active = rule.get("enabled", rule["status"] == "Active")
                dict_name = "KEYWORD_RULES" if is_active else "DISABLED_KEYWORD_RULES"
                rules_dict = dict(getattr(self.settings, dict_name, {}) or {})
                rules_dict.pop(key, None)
                setattr(self.settings, dict_name, rules_dict)
                if hasattr(self.settings, "flush"):
                    self.settings.flush()
                msg = f"Deleted rule '{pattern}' from settings."
            elif rule["kind"] == "learned":
                key = rule["original_key"]
                is_active = bool(rule.get("enabled", rule["status"] == "Active"))
                dict_name = "LEARNED_RULES" if is_active else "DISABLED_LEARNED_RULES"
                learned_dict = dict(getattr(self.settings, dict_name, {}) or {})
                learned_dict.pop(key, None)
                setattr(self.settings, dict_name, learned_dict)
                if hasattr(self.settings, "flush"):
                    self.settings.flush()
                msg = f"Deleted learned rule '{pattern}' from settings."
            elif rule["kind"] == "policy":
                policies = [
                    copy.deepcopy(p)
                    for p in getattr(self.settings, "POLICIES", []) or []
                ]
                idx = rule["policy_idx"]
                if 0 <= idx < len(policies):
                    policies.pop(idx)
                    self.settings.POLICIES = policies
                    if hasattr(self.settings, "flush"):
                        self.settings.flush()
                    msg = f"Deleted policy '{pattern}' from settings."
                else:
                    return
            else:
                return

            self._mutated = True
            self._refresh_table(preserve_focus=True)
            self.announce(msg)
            if hasattr(self.app, "notify"):
                self.app.notify(msg)

        self.app.push_screen(
            DeleteRuleConfirmModal(rule_pattern=pattern),
            on_confirmed,
        )

    @on(Button.Pressed, "#btn-close-rules")
    def action_close(self) -> None:
        """Close active rule manager dialog and report whether rules changed."""
        self.announce("Closed active rule manager.")
        self.dismiss(self._mutated)

    def action_close_rules(self) -> None:
        """Close active rule manager (legacy alias)."""
        self.action_close()

    @on(events.DescendantFocus)
    def on_descendant_focus(self, event: events.DescendantFocus) -> None:
        """Announce focused controls for screen reader accessibility."""
        widget_id = getattr(event.widget, "id", None)
        if not widget_id:
            return

        focus_announcements = {
            "btn-import-rules": "Import Rules button focused. Import rules from Hazel, DropIt, or TagSpaces.",
            "btn-export-rules": "Export Rules button focused. Export active rules to Sortify JSON, Hazel, or DropIt.",
            "btn-browse-templates": "Browse Templates button focused. Browse and apply starter rule templates.",
            "btn-toggle-rule": "Toggle Status button focused. Toggle active or disabled status of selected rule.",
            "btn-delete-rule": "Delete Rule button focused. Delete selected rule after confirmation.",
            "btn-edit-rule": "Edit Rule button focused. Edit pattern or destination folder of selected rule.",
            "btn-add-rule": "Add Rule button focused. Add a new keyword rule.",
            "btn-close-rules": "Close button focused. Close active rule manager.",
            "rules-table": "Rules table focused. Select a rule to edit, toggle, or delete.",
        }
        msg = focus_announcements.get(widget_id)
        if msg:
            self.announce(msg)

    @on(Button.Pressed, "#btn-import-rules")
    def action_import_rules(self) -> None:
        """Open external rule importer modal."""
        self.announce("Opening external rule importer modal.")

        def on_import_closed(result: Any | None = None) -> None:
            if result is not None:
                self._mutated = True
                self._refresh_table(preserve_focus=True)
                msg = f"Imported rules merged into settings. Active rules count: {len(self._rules_data)}."
                self.announce(msg)
                if hasattr(self.app, "notify"):
                    self.app.notify(msg)
            else:
                self.announce("Returned to active rule manager.")

        self.app.push_screen(RuleImportModal(self.settings), on_import_closed)

    @on(Button.Pressed, "#btn-export-rules")
    def action_export_rules(self) -> None:
        """Open export rules modal."""
        self.announce("Opening export rules modal.")

        def on_export_closed(result: Path | None = None) -> None:
            self.announce("Returned to active rule manager.")

        self.app.push_screen(ExportRulesModal(self.settings), on_export_closed)

    @on(Button.Pressed, "#btn-browse-templates")
    def action_browse_templates(self) -> None:
        """Open starter rule template gallery modal."""
        self.announce("Opening starter rule template gallery modal.")
        before_snapshot = (
            dict(getattr(self.settings, "KEYWORD_RULES", {}) or {}),
            dict(getattr(self.settings, "DISABLED_KEYWORD_RULES", {}) or {}),
            dict(getattr(self.settings, "LEARNED_RULES", {}) or {}),
            dict(getattr(self.settings, "DISABLED_LEARNED_RULES", {}) or {}),
            [dict(p) for p in (getattr(self.settings, "POLICIES", []) or [])],
        )

        def on_gallery_closed(result: Any = None) -> None:
            after_snapshot = (
                dict(getattr(self.settings, "KEYWORD_RULES", {}) or {}),
                dict(getattr(self.settings, "DISABLED_KEYWORD_RULES", {}) or {}),
                dict(getattr(self.settings, "LEARNED_RULES", {}) or {}),
                dict(getattr(self.settings, "DISABLED_LEARNED_RULES", {}) or {}),
                [dict(p) for p in (getattr(self.settings, "POLICIES", []) or [])],
            )
            if after_snapshot != before_snapshot:
                self._mutated = True
            self._refresh_table(preserve_focus=True)
            msg = f"Updated rules table from settings. Total rules: {len(self._rules_data)}."
            self.announce(msg)

        self.app.push_screen(
            TemplateGalleryModal(self.settings, defer_rescan=True), on_gallery_closed
        )

    action_browse_rule_templates = action_browse_templates
    action_open_templates = action_browse_templates
    action_open_export_rules = action_export_rules
    action_open_rule_import = action_import_rules

action_add_rule()

Open editor modal to add a new keyword rule or compound policy.

Source code in app/ui/modals/rules.py
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
@on(Button.Pressed, "#btn-add-rule")
def action_add_rule(self) -> None:
    """Open editor modal to add a new keyword rule or compound policy."""

    def on_rule_added(result: dict | None) -> None:
        if not result:
            return
        res_kind = result.get(
            "kind", "policy" if result.get("is_policy") else "keyword"
        )
        pattern = result["pattern"]
        target = result["target"]

        if res_kind == "policy":
            pol_payload = copy.deepcopy(
                result.get("policy")
                or {
                    "type": "keyword",
                    "expression": pattern,
                    "target_path": target,
                    "priority": 0,
                    "halting": False,
                    "enabled": True,
                }
            )
            policies = [
                copy.deepcopy(p)
                for p in getattr(self.settings, "POLICIES", []) or []
            ]
            policies.append(pol_payload)
            self.settings.POLICIES = policies
            if hasattr(self.settings, "flush"):
                self.settings.flush()
            msg = f"Added policy '{pattern}' (priority {pol_payload.get('priority', 0)})."
        else:
            kw_rules = dict(getattr(self.settings, "KEYWORD_RULES", {}) or {})
            kw_rules[pattern] = target
            self.settings.KEYWORD_RULES = kw_rules
            if hasattr(self.settings, "flush"):
                self.settings.flush()
            msg = f"Added rule '{pattern}' routing to '{target}'."

        self._mutated = True
        self._refresh_table(preserve_focus=False)
        masked_now = [
            r
            for r in self._rules_data
            if r.get("masked_by") and r.get("pattern") == pattern
        ]
        if masked_now:
            msg = f"{msg} Warning: masked by higher-priority rule '{masked_now[0]['masked_by']}'."
        self.announce(msg)
        if hasattr(self.app, "notify"):
            self.app.notify(msg)

    self.app.push_screen(
        RuleEditModal(
            title="Add Rule",
            settings=self.settings,
            base_dir=getattr(self.app, "base_dir", None),
            source_dirs=getattr(self.app, "source_dirs", None),
            db=getattr(self.app, "db", None),
        ),
        on_rule_added,
    )

action_browse_templates()

Open starter rule template gallery modal.

Source code in app/ui/modals/rules.py
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
@on(Button.Pressed, "#btn-browse-templates")
def action_browse_templates(self) -> None:
    """Open starter rule template gallery modal."""
    self.announce("Opening starter rule template gallery modal.")
    before_snapshot = (
        dict(getattr(self.settings, "KEYWORD_RULES", {}) or {}),
        dict(getattr(self.settings, "DISABLED_KEYWORD_RULES", {}) or {}),
        dict(getattr(self.settings, "LEARNED_RULES", {}) or {}),
        dict(getattr(self.settings, "DISABLED_LEARNED_RULES", {}) or {}),
        [dict(p) for p in (getattr(self.settings, "POLICIES", []) or [])],
    )

    def on_gallery_closed(result: Any = None) -> None:
        after_snapshot = (
            dict(getattr(self.settings, "KEYWORD_RULES", {}) or {}),
            dict(getattr(self.settings, "DISABLED_KEYWORD_RULES", {}) or {}),
            dict(getattr(self.settings, "LEARNED_RULES", {}) or {}),
            dict(getattr(self.settings, "DISABLED_LEARNED_RULES", {}) or {}),
            [dict(p) for p in (getattr(self.settings, "POLICIES", []) or [])],
        )
        if after_snapshot != before_snapshot:
            self._mutated = True
        self._refresh_table(preserve_focus=True)
        msg = f"Updated rules table from settings. Total rules: {len(self._rules_data)}."
        self.announce(msg)

    self.app.push_screen(
        TemplateGalleryModal(self.settings, defer_rescan=True), on_gallery_closed
    )

action_close()

Close active rule manager dialog and report whether rules changed.

Source code in app/ui/modals/rules.py
4008
4009
4010
4011
4012
@on(Button.Pressed, "#btn-close-rules")
def action_close(self) -> None:
    """Close active rule manager dialog and report whether rules changed."""
    self.announce("Closed active rule manager.")
    self.dismiss(self._mutated)

action_close_rules()

Close active rule manager (legacy alias).

Source code in app/ui/modals/rules.py
4014
4015
4016
def action_close_rules(self) -> None:
    """Close active rule manager (legacy alias)."""
    self.action_close()

action_delete_rule()

Delete selected rule after user confirmation.

Source code in app/ui/modals/rules.py
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
@on(Button.Pressed, "#btn-delete-rule")
def action_delete_rule(self) -> None:
    """Delete selected rule after user confirmation."""
    rule = self._get_selected_rule()
    if not rule:
        self.announce("No rule selected to delete.")
        return

    pattern = rule["pattern"]

    def on_confirmed(confirmed: bool | None) -> None:
        if not confirmed:
            return

        if rule["kind"] == "keyword":
            key = rule["original_key"]
            is_active = rule.get("enabled", rule["status"] == "Active")
            dict_name = "KEYWORD_RULES" if is_active else "DISABLED_KEYWORD_RULES"
            rules_dict = dict(getattr(self.settings, dict_name, {}) or {})
            rules_dict.pop(key, None)
            setattr(self.settings, dict_name, rules_dict)
            if hasattr(self.settings, "flush"):
                self.settings.flush()
            msg = f"Deleted rule '{pattern}' from settings."
        elif rule["kind"] == "learned":
            key = rule["original_key"]
            is_active = bool(rule.get("enabled", rule["status"] == "Active"))
            dict_name = "LEARNED_RULES" if is_active else "DISABLED_LEARNED_RULES"
            learned_dict = dict(getattr(self.settings, dict_name, {}) or {})
            learned_dict.pop(key, None)
            setattr(self.settings, dict_name, learned_dict)
            if hasattr(self.settings, "flush"):
                self.settings.flush()
            msg = f"Deleted learned rule '{pattern}' from settings."
        elif rule["kind"] == "policy":
            policies = [
                copy.deepcopy(p)
                for p in getattr(self.settings, "POLICIES", []) or []
            ]
            idx = rule["policy_idx"]
            if 0 <= idx < len(policies):
                policies.pop(idx)
                self.settings.POLICIES = policies
                if hasattr(self.settings, "flush"):
                    self.settings.flush()
                msg = f"Deleted policy '{pattern}' from settings."
            else:
                return
        else:
            return

        self._mutated = True
        self._refresh_table(preserve_focus=True)
        self.announce(msg)
        if hasattr(self.app, "notify"):
            self.app.notify(msg)

    self.app.push_screen(
        DeleteRuleConfirmModal(rule_pattern=pattern),
        on_confirmed,
    )

action_edit_rule()

Open editor modal to edit the selected keyword rule or policy.

Source code in app/ui/modals/rules.py
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
@on(Button.Pressed, "#btn-edit-rule")
def action_edit_rule(self) -> None:
    """Open editor modal to edit the selected keyword rule or policy."""
    rule = self._get_selected_rule()
    if not rule:
        self.announce("No rule selected to edit.")
        return

    def on_rule_edited(result: dict | None) -> None:
        if not result:
            return
        res_kind = result.get(
            "kind",
            "policy"
            if (result.get("is_policy") and isinstance(result.get("policy"), dict))
            else rule["kind"],
        )
        new_pattern = result["pattern"]
        new_target = result["target"]

        if rule["kind"] == "policy" and res_kind == "policy":
            policies = [
                copy.deepcopy(p)
                for p in getattr(self.settings, "POLICIES", []) or []
            ]
            idx = rule["policy_idx"]
            if 0 <= idx < len(policies):
                if "policy" in result and isinstance(result["policy"], dict):
                    updated_pol = copy.deepcopy(policies[idx])
                    updated_pol.update(copy.deepcopy(result["policy"]))
                    for opt_key in (
                        "action",
                        "rename_pattern",
                        "match_mode",
                        "conditions",
                        "negate",
                        "regex",
                        "case_sensitive",
                    ):
                        if opt_key not in result["policy"]:
                            updated_pol.pop(opt_key, None)
                    policies[idx] = updated_pol
                else:
                    policies[idx]["expression"] = new_pattern
                    policies[idx]["target_path"] = new_target
                self.settings.POLICIES = policies
                if hasattr(self.settings, "flush"):
                    self.settings.flush()
                msg = f"Updated policy '{new_pattern}'."
            else:
                return
        elif rule["kind"] in ("keyword", "learned") and res_kind == "policy":
            old_key = rule["original_key"]
            is_active = bool(rule.get("enabled", rule["status"] == "Active"))
            if rule["kind"] == "learned":
                d_name = "LEARNED_RULES" if is_active else "DISABLED_LEARNED_RULES"
            else:
                d_name = "KEYWORD_RULES" if is_active else "DISABLED_KEYWORD_RULES"
            r_dict = dict(getattr(self.settings, d_name, {}) or {})
            r_dict.pop(old_key, None)
            setattr(self.settings, d_name, r_dict)
            policies = [
                copy.deepcopy(p)
                for p in getattr(self.settings, "POLICIES", []) or []
            ]
            new_pol = copy.deepcopy(result["policy"])
            new_pol["enabled"] = is_active
            policies.append(new_pol)
            self.settings.POLICIES = policies
            if hasattr(self.settings, "flush"):
                self.settings.flush()
            msg = f"Converted rule '{new_pattern}' into a policy."
        elif rule["kind"] == "policy" and res_kind == "keyword":
            policies = [
                copy.deepcopy(p)
                for p in getattr(self.settings, "POLICIES", []) or []
            ]
            idx = rule["policy_idx"]
            if 0 <= idx < len(policies):
                was_enabled = bool(policies[idx].get("enabled", True))
                policies.pop(idx)
                self.settings.POLICIES = policies
                d_name = (
                    "KEYWORD_RULES" if was_enabled else "DISABLED_KEYWORD_RULES"
                )
                r_dict = dict(getattr(self.settings, d_name, {}) or {})
                r_dict[new_pattern] = new_target
                setattr(self.settings, d_name, r_dict)
                if hasattr(self.settings, "flush"):
                    self.settings.flush()
                msg = f"Converted policy '{new_pattern}' into a keyword rule."
            else:
                return
        elif rule["kind"] == "keyword":
            old_key = rule["original_key"]
            is_active = bool(rule.get("enabled", rule["status"] == "Active"))
            dict_name = "KEYWORD_RULES" if is_active else "DISABLED_KEYWORD_RULES"
            rules_dict = dict(getattr(self.settings, dict_name, {}) or {})
            if old_key in rules_dict and old_key != new_pattern:
                del rules_dict[old_key]
            rules_dict[new_pattern] = new_target
            setattr(self.settings, dict_name, rules_dict)
            if hasattr(self.settings, "flush"):
                self.settings.flush()
            msg = f"Updated rule '{new_pattern}' target folder to '{new_target}'."
        elif rule["kind"] == "learned":
            old_key = rule["original_key"]
            is_active = bool(rule.get("enabled", rule["status"] == "Active"))
            src_dict_name = (
                "LEARNED_RULES" if is_active else "DISABLED_LEARNED_RULES"
            )
            learned_dict = dict(getattr(self.settings, src_dict_name, {}) or {})
            if res_kind == "keyword":
                learned_dict.pop(old_key, None)
                setattr(self.settings, src_dict_name, learned_dict)
                dst_dict_name = (
                    "KEYWORD_RULES" if is_active else "DISABLED_KEYWORD_RULES"
                )
                kw_dict = dict(getattr(self.settings, dst_dict_name, {}) or {})
                kw_dict[new_pattern] = new_target
                setattr(self.settings, dst_dict_name, kw_dict)
                msg = f"Converted learned rule '{new_pattern}' into a keyword rule."
            else:
                if old_key in learned_dict and old_key != new_pattern:
                    del learned_dict[old_key]
                learned_dict[new_pattern] = new_target
                setattr(self.settings, src_dict_name, learned_dict)
                msg = f"Updated learned rule '{new_pattern}' target folder to '{new_target}'."
            if hasattr(self.settings, "flush"):
                self.settings.flush()
        else:
            return

        self._mutated = True
        self._refresh_table(preserve_focus=True)
        self.announce(msg)
        if hasattr(self.app, "notify"):
            self.app.notify(msg)

    orig_raw = rule.get("original")
    orig_pol: dict[str, Any] = (
        copy.deepcopy(orig_raw) if isinstance(orig_raw, dict) else {}
    )
    self.app.push_screen(
        RuleEditModal(
            title=f"Edit Rule: {rule['pattern']}",
            pattern=rule["pattern"],
            target_folder=rule["target_folder"],
            policy=orig_pol if rule["kind"] == "policy" else None,
            rule_kind=rule["kind"],
            policy_type=str(orig_pol.get("type", "keyword")),
            priority=int(orig_pol.get("priority", rule.get("priority", 0)) or 0),
            halting=bool(orig_pol.get("halting", False)),
            action=str(orig_pol.get("action") or ""),
            enabled=bool(rule.get("enabled", True)),
            settings=self.settings,
            base_dir=getattr(self.app, "base_dir", None),
            source_dirs=getattr(self.app, "source_dirs", None),
            db=getattr(self.app, "db", None),
            rename_pattern=str(
                orig_pol.get("rename_pattern") or rule.get("rename_pattern") or ""
            ),
        ),
        on_rule_edited,
    )

action_export_rules()

Open export rules modal.

Source code in app/ui/modals/rules.py
4058
4059
4060
4061
4062
4063
4064
4065
4066
@on(Button.Pressed, "#btn-export-rules")
def action_export_rules(self) -> None:
    """Open export rules modal."""
    self.announce("Opening export rules modal.")

    def on_export_closed(result: Path | None = None) -> None:
        self.announce("Returned to active rule manager.")

    self.app.push_screen(ExportRulesModal(self.settings), on_export_closed)

action_import_rules()

Open external rule importer modal.

Source code in app/ui/modals/rules.py
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
@on(Button.Pressed, "#btn-import-rules")
def action_import_rules(self) -> None:
    """Open external rule importer modal."""
    self.announce("Opening external rule importer modal.")

    def on_import_closed(result: Any | None = None) -> None:
        if result is not None:
            self._mutated = True
            self._refresh_table(preserve_focus=True)
            msg = f"Imported rules merged into settings. Active rules count: {len(self._rules_data)}."
            self.announce(msg)
            if hasattr(self.app, "notify"):
                self.app.notify(msg)
        else:
            self.announce("Returned to active rule manager.")

    self.app.push_screen(RuleImportModal(self.settings), on_import_closed)

action_toggle_rule()

Toggle active/disabled status of selected rule.

Source code in app/ui/modals/rules.py
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
@on(Button.Pressed, "#btn-toggle-rule")
def action_toggle_rule(self) -> None:
    """Toggle active/disabled status of selected rule."""
    rule = self._get_selected_rule()
    if not rule:
        self.announce("No rule selected to toggle.")
        return

    if rule["kind"] == "keyword":
        kw = rule["original_key"]
        kw_rules = dict(getattr(self.settings, "KEYWORD_RULES", {}) or {})
        dis_rules = dict(getattr(self.settings, "DISABLED_KEYWORD_RULES", {}) or {})

        if rule.get("enabled", rule["status"] == "Active"):
            target = kw_rules.pop(kw, rule["target_folder"])
            dis_rules[kw] = target
            new_status = "Disabled"
        else:
            target = dis_rules.pop(kw, rule["target_folder"])
            kw_rules[kw] = target
            new_status = "Active"

        self.settings.KEYWORD_RULES = kw_rules
        self.settings.DISABLED_KEYWORD_RULES = dis_rules
        if hasattr(self.settings, "flush"):
            self.settings.flush()
        msg = f"Toggled keyword rule '{kw}' to {new_status}."
    elif rule["kind"] == "learned":
        kw = rule["original_key"]
        learned_rules = dict(getattr(self.settings, "LEARNED_RULES", {}) or {})
        dis_learned = dict(
            getattr(self.settings, "DISABLED_LEARNED_RULES", {}) or {}
        )
        if rule.get("enabled", rule["status"] == "Active"):
            target = learned_rules.pop(kw, rule["target_folder"])
            dis_learned[kw] = target
            new_status = "Disabled"
        else:
            target = dis_learned.pop(kw, rule["target_folder"])
            learned_rules[kw] = target
            new_status = "Active"
        self.settings.LEARNED_RULES = learned_rules
        self.settings.DISABLED_LEARNED_RULES = dis_learned
        if hasattr(self.settings, "flush"):
            self.settings.flush()
        msg = f"Toggled learned rule '{kw}' to {new_status}."
    elif rule["kind"] == "policy":
        policies = [
            copy.deepcopy(p) for p in getattr(self.settings, "POLICIES", []) or []
        ]
        idx = rule["policy_idx"]
        if 0 <= idx < len(policies):
            curr = policies[idx].get("enabled", True)
            policies[idx]["enabled"] = not curr
            new_status = "Active" if not curr else "Disabled"
            self.settings.POLICIES = policies
            if hasattr(self.settings, "flush"):
                self.settings.flush()
            msg = f"Toggled policy '{rule['pattern']}' to {new_status}."
        else:
            return
    else:
        return

    self._mutated = True
    self._refresh_table(preserve_focus=True)
    self.announce(msg)
    if hasattr(self.app, "notify"):
        self.app.notify(msg)

compose()

Compose active rule manager children.

Source code in app/ui/modals/rules.py
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
def compose(self) -> ComposeResult:
    """Compose active rule manager children."""
    with ModalBox(classes="rule-manager-box modal-box"):
        yield Heading(
            "Active Rule Manager",
            level=1,
            classes="modal-title",
            id="modal-title",
        )
        with Vertical(classes="modal-body"):
            yield Label(
                "Manage keyword rules and policies. Select a rule to edit, toggle, or delete:",
                id="lbl-rules-desc",
            )
            table = DataTable(id="rules-table")
            self._populate_rules_table(table)
            yield table
        with Vertical(classes="modal-footer"):
            with Horizontal(classes="button-row"):
                btn_toggle = Button(
                    "Toggle Status", id="btn-toggle-rule", variant="default"
                )
                btn_toggle.tooltip = (
                    "Toggle active/disabled status of selected rule"
                )
                yield btn_toggle
                btn_delete = Button(
                    "Delete Rule", id="btn-delete-rule", variant="error"
                )
                btn_delete.tooltip = "Delete selected rule after confirmation"
                yield btn_delete
                btn_edit = Button(
                    "Edit Rule", id="btn-edit-rule", variant="default"
                )
                btn_edit.tooltip = (
                    "Edit pattern or destination folder of selected rule"
                )
                yield btn_edit
                btn_add = Button("Add Rule", id="btn-add-rule", variant="primary")
                btn_add.tooltip = "Add a new keyword rule or policy"
                yield btn_add

            with Horizontal(classes="button-row"):
                btn_close = Button("Close", id="btn-close-rules", variant="default")
                btn_close.tooltip = "Close active rule manager"
                yield btn_close
                btn_import = Button(
                    "Import Rules", id="btn-import-rules", variant="default"
                )
                btn_import.tooltip = "Import rules from Hazel, DropIt, or TagSpaces"
                yield btn_import
                btn_export = Button(
                    "Export Rules", id="btn-export-rules", variant="default"
                )
                btn_export.tooltip = (
                    "Export active rules to Sortify JSON, Hazel, or DropIt"
                )
                yield btn_export
                btn_browse = Button(
                    "Browse Templates",
                    id="btn-browse-templates",
                    variant="primary",
                )
                btn_browse.tooltip = "Browse and apply starter rule templates"
                yield btn_browse

on_descendant_focus(event)

Announce focused controls for screen reader accessibility.

Source code in app/ui/modals/rules.py
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
@on(events.DescendantFocus)
def on_descendant_focus(self, event: events.DescendantFocus) -> None:
    """Announce focused controls for screen reader accessibility."""
    widget_id = getattr(event.widget, "id", None)
    if not widget_id:
        return

    focus_announcements = {
        "btn-import-rules": "Import Rules button focused. Import rules from Hazel, DropIt, or TagSpaces.",
        "btn-export-rules": "Export Rules button focused. Export active rules to Sortify JSON, Hazel, or DropIt.",
        "btn-browse-templates": "Browse Templates button focused. Browse and apply starter rule templates.",
        "btn-toggle-rule": "Toggle Status button focused. Toggle active or disabled status of selected rule.",
        "btn-delete-rule": "Delete Rule button focused. Delete selected rule after confirmation.",
        "btn-edit-rule": "Edit Rule button focused. Edit pattern or destination folder of selected rule.",
        "btn-add-rule": "Add Rule button focused. Add a new keyword rule.",
        "btn-close-rules": "Close button focused. Close active rule manager.",
        "rules-table": "Rules table focused. Select a rule to edit, toggle, or delete.",
    }
    msg = focus_announcements.get(widget_id)
    if msg:
        self.announce(msg)

on_mount()

Set up columns and load rules on mount.

Source code in app/ui/modals/rules.py
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
def on_mount(self) -> None:
    """Set up columns and load rules on mount."""
    super().on_mount()
    try:
        table = self.query_one("#rules-table", DataTable)
    except NoMatches:
        return
    if not table.columns:
        self._populate_rules_table(table)
    if self.focused is None:
        table.focus()
    masked_rows = [r for r in self._rules_data if r.get("masked_by")]
    if masked_rows:
        self.announce(
            f"Opened active rule manager. Warning: {len(masked_rows)} policy rule(s) masked by higher-priority rules."
        )
    else:
        self.announce("Opened active rule manager.")

on_row_selected(event)

Trigger editing when pressing Enter on a rule row.

Source code in app/ui/modals/rules.py
3639
3640
3641
3642
@on(DataTable.RowSelected, "#rules-table")
def on_row_selected(self, event: DataTable.RowSelected) -> None:
    """Trigger editing when pressing Enter on a rule row."""
    self.action_edit_rule()

DeleteRuleConfirmModal

Bases: ResponsiveModalScreen[bool]

Confirmation modal screen for deleting a rule.

Source code in app/ui/modals/rules.py
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
class DeleteRuleConfirmModal(ResponsiveModalScreen[bool]):
    """Confirmation modal screen for deleting a rule."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel deletion", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .delete-confirm-box {
        width: 80%;
        max-width: 60;
    }
    Button:focus {
        border: heavy $accent;
        text-style: bold;
    }
    """

    def __init__(self, rule_pattern: str):
        super().__init__()
        self.rule_pattern = rule_pattern

    def compose(self) -> ComposeResult:
        """Compose confirmation dialog children."""
        with ModalBox(classes="delete-confirm-box modal-box"):
            yield Heading(
                "Confirm Delete Rule",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            with Vertical(classes="modal-body"):
                yield Label(
                    f"Are you sure you want to delete rule '{self.rule_pattern}'?\n"
                    "This action cannot be undone.",
                    id="lbl-delete-confirm-text",
                )
            with Horizontal(classes="button-row"):
                btn_cancel = Button("Cancel", id="btn-cancel-delete", variant="default")
                btn_cancel.tooltip = "Cancel and keep this rule"
                yield btn_cancel
                btn_delete = Button("Delete", id="btn-confirm-delete", variant="error")
                btn_delete.tooltip = "Permanently remove this rule"
                yield btn_delete

    def on_mount(self) -> None:
        """Focus cancel button by default to avoid accidental deletion."""
        super().on_mount()
        self.query_one("#btn-cancel-delete", Button).focus()

    @on(Button.Pressed, "#btn-confirm-delete")
    def action_confirm_delete(self) -> None:
        """Confirm deletion."""
        self.announce(f"Confirmed deletion of rule '{self.rule_pattern}'.")
        self.dismiss(True)

    @on(Button.Pressed, "#btn-cancel-delete")
    def action_cancel_button(self) -> None:
        """Cancel deletion."""
        self.announce(f"Cancelled deletion of rule '{self.rule_pattern}'.")
        self.dismiss(False)

    def action_cancel(self) -> None:
        """Cancel on Escape."""
        self.announce("Cancelled delete rule dialog.")
        self.dismiss(False)

action_cancel()

Cancel on Escape.

Source code in app/ui/modals/rules.py
3296
3297
3298
3299
def action_cancel(self) -> None:
    """Cancel on Escape."""
    self.announce("Cancelled delete rule dialog.")
    self.dismiss(False)

action_cancel_button()

Cancel deletion.

Source code in app/ui/modals/rules.py
3290
3291
3292
3293
3294
@on(Button.Pressed, "#btn-cancel-delete")
def action_cancel_button(self) -> None:
    """Cancel deletion."""
    self.announce(f"Cancelled deletion of rule '{self.rule_pattern}'.")
    self.dismiss(False)

action_confirm_delete()

Confirm deletion.

Source code in app/ui/modals/rules.py
3284
3285
3286
3287
3288
@on(Button.Pressed, "#btn-confirm-delete")
def action_confirm_delete(self) -> None:
    """Confirm deletion."""
    self.announce(f"Confirmed deletion of rule '{self.rule_pattern}'.")
    self.dismiss(True)

compose()

Compose confirmation dialog children.

Source code in app/ui/modals/rules.py
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
def compose(self) -> ComposeResult:
    """Compose confirmation dialog children."""
    with ModalBox(classes="delete-confirm-box modal-box"):
        yield Heading(
            "Confirm Delete Rule",
            level=1,
            classes="modal-title",
            id="modal-title",
        )
        with Vertical(classes="modal-body"):
            yield Label(
                f"Are you sure you want to delete rule '{self.rule_pattern}'?\n"
                "This action cannot be undone.",
                id="lbl-delete-confirm-text",
            )
        with Horizontal(classes="button-row"):
            btn_cancel = Button("Cancel", id="btn-cancel-delete", variant="default")
            btn_cancel.tooltip = "Cancel and keep this rule"
            yield btn_cancel
            btn_delete = Button("Delete", id="btn-confirm-delete", variant="error")
            btn_delete.tooltip = "Permanently remove this rule"
            yield btn_delete

on_mount()

Focus cancel button by default to avoid accidental deletion.

Source code in app/ui/modals/rules.py
3279
3280
3281
3282
def on_mount(self) -> None:
    """Focus cancel button by default to avoid accidental deletion."""
    super().on_mount()
    self.query_one("#btn-cancel-delete", Button).focus()

ExportRulesModal

Bases: _CancelToCloseMixin, ResponsiveModalScreen[Path | None]

Modal screen for exporting active keyword rules and policies to external formats.

Source code in app/ui/modals/rules.py
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
class ExportRulesModal(_CancelToCloseMixin, ResponsiveModalScreen[Path | None]):
    """Modal screen for exporting active keyword rules and policies to external formats."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-box {
        min-width: 35;
    }
    .field-label {
        margin-top: 1;
        color: $text;
        text-style: bold;
    }
    .status-text {
        color: $accent;
        margin-top: 1;
        text-style: bold;
    }
    .error-text {
        color: $error;
        margin-top: 1;
        text-style: bold;
    }
    .summary-text {
        color: $text-muted;
        margin-top: 1;
    }
    Button:focus, Input:focus, Select:focus {
        border: heavy $accent;
        text-style: bold;
    }
    ExportRulesModal {
        &.compact .modal-box, &.narrow .modal-box {
            width: 95%;
        }
        &.compact .field-label,
        &.compact .status-text,
        &.compact .error-text,
        &.compact .summary-text {
            margin-top: 0;
        }
    }
    """

    def __init__(self, settings: Any):
        super().__init__()
        self.settings = settings

    def compose(self) -> ComposeResult:
        """Compose export rules modal children."""
        kw_count = len(getattr(self.settings, "KEYWORD_RULES", {}) or {})
        pol_count = len(getattr(self.settings, "POLICIES", []) or [])

        with ModalBox(classes="modal-box"):
            yield Heading(
                "Export Active Rules",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            with Vertical(classes="modal-body"):
                yield Label(
                    f"Export {kw_count} active keyword rule(s) and {pol_count} policy rule(s) to disk:",
                    id="lbl-export-summary",
                    classes="summary-text",
                )

                yield Label("Export Format:", classes="field-label")
                yield Select(
                    [
                        ("Sortify JSON (*.json)", "sortify_json"),
                        ("Hazel Rules (*.hazelrules)", "hazel"),
                        ("DropIt Configuration (*.ini)", "dropit_ini"),
                    ],
                    value="sortify_json",
                    id="select-export-format",
                    allow_blank=False,
                )

                yield Label("Destination File Path:", classes="field-label")
                yield Input(
                    placeholder="/path/to/exported_rules.json",
                    value="exported_rules.json",
                    id="input-export-path",
                )

                yield Label(
                    "",
                    id="lbl-export-status",
                    classes="status-text",
                )

            with Horizontal(classes="button-row"):
                btn_cancel = Button("Cancel", id="btn-cancel-export", variant="default")
                btn_cancel.tooltip = "Close export dialog without saving"
                yield btn_cancel

                btn_export = Button(
                    "Export Rules",
                    id="btn-do-export",
                    variant="primary",
                )
                btn_export.tooltip = "Export active rules to destination path"
                yield btn_export

    def on_mount(self) -> None:
        """Focus initial widget on mount and emit accessibility announcement."""
        super().on_mount()
        try:
            self.query_one("#input-export-path", Input).focus()
        except Exception:
            pass
        self.announce("Opened export rules modal.")

    @on(Select.Changed, "#select-export-format")
    def on_format_changed(self, event: Select.Changed) -> None:
        """Update destination filename placeholder and value when format changes."""
        if _is_select_blank(event.value):
            return
        fmt = str(event.value)
        ext_map = {
            "sortify_json": ".json",
            "hazel": ".hazelrules",
            "dropit_ini": ".ini",
        }
        name_map = {
            "sortify_json": "Sortify JSON",
            "hazel": "Hazel (.hazelrules)",
            "dropit_ini": "DropIt (.ini)",
        }
        new_ext = ext_map.get(fmt, ".json")
        fmt_label = name_map.get(fmt, fmt)
        self.announce(f"Selected export format: {fmt_label}")

        try:
            inp = self.query_one("#input-export-path", Input)
            val = inp.value.strip()
            if val:
                p = Path(val)
                if p.suffix.lower() in (".json", ".hazelrules", ".ini"):
                    inp.value = str(p.with_suffix(new_ext))
                else:
                    inp.value = f"{val}{new_ext}"
            else:
                inp.value = f"exported_rules{new_ext}"
            inp.placeholder = f"/path/to/exported_rules{new_ext}"
        except Exception:
            pass

    @on(Button.Pressed, "#btn-do-export")
    @on(Input.Submitted, "#input-export-path")
    def action_export(self) -> None:
        """Export active rules to selected format and path."""
        from app.core.rule_templates import export_active_rules

        path_str = self.query_one("#input-export-path", Input).value.strip()
        lbl_status = self.query_one("#lbl-export-status", Label)

        if not path_str:
            err_msg = "Please provide a valid destination file path."
            lbl_status.update(err_msg)
            lbl_status.remove_class("status-text")
            lbl_status.add_class("error-text")
            self.announce(err_msg)
            if hasattr(self.app, "notify"):
                self.app.notify(err_msg, severity="error")
            return

        fmt = "sortify_json"
        try:
            sel_val = self.query_one("#select-export-format", Select).value
            if not _is_select_blank(sel_val):
                fmt = str(sel_val)
        except Exception:
            pass

        try:
            saved_path = export_active_rules(self.settings, fmt, path_str)
            success_msg = f"Successfully exported active rules to {saved_path}"
            lbl_status.update(success_msg)
            lbl_status.remove_class("error-text")
            lbl_status.add_class("status-text")
            self.announce(success_msg)
            if hasattr(self.app, "notify"):
                self.app.notify(success_msg)
            self.dismiss(saved_path)
        except Exception as exc:
            err_msg = f"Failed to export rules: {exc}"
            lbl_status.update(err_msg)
            lbl_status.remove_class("status-text")
            lbl_status.add_class("error-text")
            self.announce(err_msg)
            if hasattr(self.app, "notify"):
                self.app.notify(err_msg, severity="error")

    @on(Button.Pressed, "#btn-cancel-export")
    def action_close(self) -> None:
        """Close export modal without changes."""
        self.announce("Closed export rules modal.")
        self.dismiss(None)

action_close()

Close export modal without changes.

Source code in app/ui/modals/rules.py
896
897
898
899
900
@on(Button.Pressed, "#btn-cancel-export")
def action_close(self) -> None:
    """Close export modal without changes."""
    self.announce("Closed export rules modal.")
    self.dismiss(None)

action_export()

Export active rules to selected format and path.

Source code in app/ui/modals/rules.py
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
@on(Button.Pressed, "#btn-do-export")
@on(Input.Submitted, "#input-export-path")
def action_export(self) -> None:
    """Export active rules to selected format and path."""
    from app.core.rule_templates import export_active_rules

    path_str = self.query_one("#input-export-path", Input).value.strip()
    lbl_status = self.query_one("#lbl-export-status", Label)

    if not path_str:
        err_msg = "Please provide a valid destination file path."
        lbl_status.update(err_msg)
        lbl_status.remove_class("status-text")
        lbl_status.add_class("error-text")
        self.announce(err_msg)
        if hasattr(self.app, "notify"):
            self.app.notify(err_msg, severity="error")
        return

    fmt = "sortify_json"
    try:
        sel_val = self.query_one("#select-export-format", Select).value
        if not _is_select_blank(sel_val):
            fmt = str(sel_val)
    except Exception:
        pass

    try:
        saved_path = export_active_rules(self.settings, fmt, path_str)
        success_msg = f"Successfully exported active rules to {saved_path}"
        lbl_status.update(success_msg)
        lbl_status.remove_class("error-text")
        lbl_status.add_class("status-text")
        self.announce(success_msg)
        if hasattr(self.app, "notify"):
            self.app.notify(success_msg)
        self.dismiss(saved_path)
    except Exception as exc:
        err_msg = f"Failed to export rules: {exc}"
        lbl_status.update(err_msg)
        lbl_status.remove_class("status-text")
        lbl_status.add_class("error-text")
        self.announce(err_msg)
        if hasattr(self.app, "notify"):
            self.app.notify(err_msg, severity="error")

compose()

Compose export rules modal children.

Source code in app/ui/modals/rules.py
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
def compose(self) -> ComposeResult:
    """Compose export rules modal children."""
    kw_count = len(getattr(self.settings, "KEYWORD_RULES", {}) or {})
    pol_count = len(getattr(self.settings, "POLICIES", []) or [])

    with ModalBox(classes="modal-box"):
        yield Heading(
            "Export Active Rules",
            level=1,
            classes="modal-title",
            id="modal-title",
        )
        with Vertical(classes="modal-body"):
            yield Label(
                f"Export {kw_count} active keyword rule(s) and {pol_count} policy rule(s) to disk:",
                id="lbl-export-summary",
                classes="summary-text",
            )

            yield Label("Export Format:", classes="field-label")
            yield Select(
                [
                    ("Sortify JSON (*.json)", "sortify_json"),
                    ("Hazel Rules (*.hazelrules)", "hazel"),
                    ("DropIt Configuration (*.ini)", "dropit_ini"),
                ],
                value="sortify_json",
                id="select-export-format",
                allow_blank=False,
            )

            yield Label("Destination File Path:", classes="field-label")
            yield Input(
                placeholder="/path/to/exported_rules.json",
                value="exported_rules.json",
                id="input-export-path",
            )

            yield Label(
                "",
                id="lbl-export-status",
                classes="status-text",
            )

        with Horizontal(classes="button-row"):
            btn_cancel = Button("Cancel", id="btn-cancel-export", variant="default")
            btn_cancel.tooltip = "Close export dialog without saving"
            yield btn_cancel

            btn_export = Button(
                "Export Rules",
                id="btn-do-export",
                variant="primary",
            )
            btn_export.tooltip = "Export active rules to destination path"
            yield btn_export

on_format_changed(event)

Update destination filename placeholder and value when format changes.

Source code in app/ui/modals/rules.py
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
@on(Select.Changed, "#select-export-format")
def on_format_changed(self, event: Select.Changed) -> None:
    """Update destination filename placeholder and value when format changes."""
    if _is_select_blank(event.value):
        return
    fmt = str(event.value)
    ext_map = {
        "sortify_json": ".json",
        "hazel": ".hazelrules",
        "dropit_ini": ".ini",
    }
    name_map = {
        "sortify_json": "Sortify JSON",
        "hazel": "Hazel (.hazelrules)",
        "dropit_ini": "DropIt (.ini)",
    }
    new_ext = ext_map.get(fmt, ".json")
    fmt_label = name_map.get(fmt, fmt)
    self.announce(f"Selected export format: {fmt_label}")

    try:
        inp = self.query_one("#input-export-path", Input)
        val = inp.value.strip()
        if val:
            p = Path(val)
            if p.suffix.lower() in (".json", ".hazelrules", ".ini"):
                inp.value = str(p.with_suffix(new_ext))
            else:
                inp.value = f"{val}{new_ext}"
        else:
            inp.value = f"exported_rules{new_ext}"
        inp.placeholder = f"/path/to/exported_rules{new_ext}"
    except Exception:
        pass

on_mount()

Focus initial widget on mount and emit accessibility announcement.

Source code in app/ui/modals/rules.py
806
807
808
809
810
811
812
813
def on_mount(self) -> None:
    """Focus initial widget on mount and emit accessibility announcement."""
    super().on_mount()
    try:
        self.query_one("#input-export-path", Input).focus()
    except Exception:
        pass
    self.announce("Opened export rules modal.")

RuleEditModal

Bases: ResponsiveModalScreen[dict | None]

Modal screen for adding or editing keyword rules and compound boolean policies with live sample preview.

Source code in app/ui/modals/rules.py
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
class RuleEditModal(ResponsiveModalScreen[dict | None]):
    """Modal screen for adding or editing keyword rules and compound boolean policies with live sample preview."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MATCH_MODE_OPTIONS: list[tuple[str, str]] = [
        ("Simple Keyword / Pattern", "simple"),
        ("All conditions (AND)", "all"),
        ("Any condition (OR)", "any"),
        ("None of conditions (NOR)", "none"),
    ]

    MODAL_CSS = """
    .rule-edit-box {
        width: 86%;
        max-width: 76;
        max-height: 92%;
    }
    .hidden {
        display: none;
    }
    .field-label {
        margin-top: 1;
        color: $text;
        text-style: bold;
    }
    .rule-flags-row, .clause-flags-row {
        height: auto;
        width: 100%;
        margin-top: 0;
    }
    .rule-flags-row Checkbox, .clause-flags-row Checkbox {
        width: auto;
        margin-right: 1;
    }
    #compound-clauses-section {
        height: auto;
        width: 100%;
        margin-top: 1;
    }
    #compound-clauses-section.hidden {
        display: none;
    }
    #compound-clauses-list {
        height: auto;
        width: 100%;
    }
    .clause-row {
        height: auto;
        width: 100%;
        border: solid $primary;
        padding: 0 1;
        margin-bottom: 1;
    }
    .clause-selects-row {
        height: auto;
        width: 100%;
    }
    .clause-field-select, .clause-op-select {
        width: 1fr;
    }
    .clause-button-row {
        layout: grid;
        grid-size: 2;
        grid-columns: 1fr 1fr;
        grid-gutter: 0 1;
        height: auto;
        width: 100%;
        margin-top: 0;
    }
    .clause-button-row Button {
        width: 100%;
        min-width: 0;
        margin: 0;
    }
    .nested-groups-note {
        color: $accent;
        margin-bottom: 1;
    }
    .policy-grid {
        height: auto;
        width: 100%;
    }
    .preview-box {
        margin-top: 1;
        padding: 0 1;
        border: solid $accent;
        height: auto;
    }
    .preview-status {
        color: $text;
        margin-top: 0;
    }
    .preview-status.match {
        color: $success;
        text-style: bold;
    }
    .preview-status.no-match {
        color: $warning;
        text-style: bold;
    }
    .error-label {
        color: $error;
        text-style: bold;
        margin-top: 1;
        display: none;
    }
    .error-label.visible {
        display: block;
    }
    .button-row {
        layout: grid;
        grid-size: 2;
        grid-columns: 1fr 1fr;
        grid-gutter: 0 1;
    }
    .button-row Button {
        width: 100%;
        min-width: 0;
        margin: 0;
    }
    Button:focus, Input:focus, Select:focus, Checkbox:focus {
        border: heavy $accent;
        text-style: bold;
    }
    RuleEditModal {
        &.compact .rule-edit-box, &.narrow .rule-edit-box {
            width: 96%;
            max-height: 96%;
        }
        &.compact .modal-title {
            margin-bottom: 0;
        }
        &.compact .field-label {
            margin-top: 0;
        }
        &.compact #compound-clauses-section {
            margin-top: 0;
        }
        &.compact .clause-row {
            margin-bottom: 0;
        }
        &.compact .clause-button-row Button {
            height: 1;
            min-height: 1;
            border: none;
            padding: 0;
            margin: 0;
        }
        &.compact .preview-box {
            margin-top: 0;
        }
        &.compact .button-row {
            margin-top: 0;
        }
        &.compact .button-row Button {
            height: 1;
            min-height: 1;
            border: none;
            padding: 0;
            margin: 0;
        }
    }
    """

    RULE_TYPE_OPTIONS: list[tuple[str, str]] = [
        ("Keyword (substring)", "keyword"),
        ("Pattern (regex / glob)", "pattern"),
        ("Override", "override"),
        ("Action", "action"),
        ("File Age (e.g. > 30d)", "age"),
        ("Modified Date (e.g. < 2025-01-01)", "modified_date"),
        ("Created Date (e.g. > 2024-01-01)", "created_date"),
        ("EXIF / PDF Date (e.g. < 2023-06-01)", "exif_date"),
        ("File Size (e.g. > 10MB)", "size"),
        ("Compliance", "compliance"),
        ("Unarchive", "unarchive"),
        ("Duplicate", "duplicate"),
    ]
    MAX_WORKSPACE_PREVIEW_FILES: int = 200

    def __init__(
        self,
        title: str = "Add Keyword Rule",
        pattern: str = "",
        target_folder: str = "",
        policy: dict[str, Any] | None = None,
        rule_kind: str = "keyword",
        policy_type: str = "keyword",
        priority: int = 0,
        halting: bool = False,
        action: str = "",
        enabled: bool = True,
        settings: Any = None,
        base_dir: str | None = None,
        source_dirs: list[str] | None = None,
        db: Any = None,
        *,
        rename_pattern: str = "",
        rule_type: str | None = None,
        rule_action: str | None = None,
    ):
        super().__init__()
        self.title_text = title
        self.initial_policy = (
            copy.deepcopy(policy) if isinstance(policy, dict) else None
        )
        self.initial_pattern = (
            pattern
            if pattern
            else (
                str(self.initial_policy.get("expression", ""))
                if self.initial_policy
                else ""
            )
        )
        self.initial_target = (
            target_folder
            if target_folder
            else (
                str(self.initial_policy.get("target_path", ""))
                if self.initial_policy
                else ""
            )
        )

        norm_kind = str(rule_kind or "").strip().lower()
        if rule_type is not None:
            legacy_rt = str(rule_type).strip().lower()
            if norm_kind in ("", "keyword") and legacy_rt and legacy_rt != "keyword":
                norm_kind = "policy"
            if policy_type == "keyword" and legacy_rt:
                policy_type = legacy_rt
        eff_action = (
            action
            or rule_action
            or (self.initial_policy.get("action") if self.initial_policy else "")
            or ""
        )
        if norm_kind in ("", "keyword") and (
            self.initial_policy is not None or bool(str(eff_action).strip())
        ):
            norm_kind = "policy"
        self.initial_kind = (
            norm_kind if norm_kind in ("keyword", "policy", "learned") else "keyword"
        )

        raw_pol_type = (
            policy_type
            if policy_type != "keyword" or self.initial_policy is None
            else str(self.initial_policy.get("type", "keyword"))
        )
        self.initial_policy_type = str(raw_pol_type or "keyword").strip().lower()
        self.initial_priority = (
            int(priority)
            if (priority or self.initial_policy is None)
            else int(self.initial_policy.get("priority", 0) or 0)
        )
        self.initial_halting = bool(
            halting
            or (
                self.initial_policy.get("halting", False)
                if self.initial_policy
                else False
            )
        )
        self.initial_action = str(eff_action).strip()
        eff_rename = (
            rename_pattern
            or (
                self.initial_policy.get("rename_pattern") if self.initial_policy else ""
            )
            or ""
        )
        self.initial_rename_pattern = str(eff_rename).strip()
        self.initial_enabled = bool(
            self.initial_policy.get("enabled", enabled)
            if self.initial_policy is not None
            else enabled
        )
        self.settings = settings
        self.base_dir = base_dir
        self.source_dirs = source_dirs
        self.db = db
        self._workspace_items: list[tuple[str, str, str]] = []
        self._sample_options_seeded: bool = False
        self._text_cache: dict[str, str] = {}
        self._mounted_ready: bool = False

        raw_conditions = (
            self.initial_policy.get("conditions")
            if isinstance(self.initial_policy, dict)
            else None
        )
        raw_mode = (
            str(self.initial_policy.get("match_mode", "")).lower()
            if isinstance(self.initial_policy, dict)
            else ""
        )
        if isinstance(raw_conditions, list) and raw_conditions:
            self.initial_match_mode = (
                raw_mode if raw_mode in {"all", "any", "none"} else "all"
            )
        elif raw_mode in {"all", "any", "none"}:
            self.initial_match_mode = raw_mode
        else:
            self.initial_match_mode = "simple"

        self.initial_negate = bool(
            self.initial_policy.get("negate", False) if self.initial_policy else False
        )
        self.initial_regex = bool(
            self.initial_policy.get("regex", False) if self.initial_policy else False
        )
        self.initial_case_sensitive = bool(
            self.initial_policy.get("case_sensitive", False)
            if self.initial_policy
            else False
        )

        self._initial_leaf_clauses: list[dict[str, Any]] = []
        self._nested_groups: list[dict[str, Any]] = []
        if isinstance(raw_conditions, list):
            for item in raw_conditions:
                if isinstance(item, dict):
                    if "conditions" in item:
                        self._nested_groups.append(copy.deepcopy(item))
                    else:
                        self._initial_leaf_clauses.append(copy.deepcopy(item))

        self._next_clause_idx = 0
        self._initial_auto_summary = ""
        if self.initial_policy and isinstance(raw_conditions, list) and raw_conditions:
            from app.core.policy_engine import summarize_policy_conditions

            self._initial_auto_summary = summarize_policy_conditions(
                raw_conditions,
                match_mode=self.initial_match_mode,
                negate=self.initial_negate,
            )

    def compose(self) -> ComposeResult:
        """Compose rule editor inputs, compound clause builder, policy attributes, live sample preview, and action buttons."""
        self._workspace_items = self._discover_workspace_files()
        sample_options = [
            (rel_p, item_id) for item_id, _s, rel_p in self._workspace_items
        ]
        self._sample_options_seeded = True

        kind_options: list[tuple[str, str]] = [
            ("Keyword Rule", "keyword"),
            ("Policy Rule", "policy"),
        ]
        if self.initial_kind == "learned":
            kind_options.insert(0, ("Learned Rule", "learned"))

        policy_types: list[tuple[str, str]] = list(self.RULE_TYPE_OPTIONS)
        known_pol_vals = {val for _lbl, val in policy_types}
        if self.initial_policy_type and self.initial_policy_type not in known_pol_vals:
            policy_types.append(
                (self.initial_policy_type.title(), self.initial_policy_type)
            )

        pol_cls = (
            "policy-grid" if self.initial_kind == "policy" else "policy-grid hidden"
        )
        compound_classes = "" if self.initial_match_mode != "simple" else "hidden"

        with ModalBox(classes="rule-edit-box modal-box"):
            yield Heading(
                self.title_text, level=1, classes="modal-title", id="modal-title"
            )
            with Vertical(classes="modal-body"):
                yield Label("Rule Category:", classes="field-label")
                sel_kind = Select(
                    kind_options,
                    value=self.initial_kind,
                    allow_blank=False,
                    id="select-rule-kind",
                )
                sel_kind.tooltip = (
                    "Select whether to save a keyword rule or a prioritized policy"
                )
                self.watch(sel_kind, "value", self._on_watched_rule_kind, init=False)
                yield sel_kind

                yield Label("Match Mode:", classes="field-label")
                sel_mode = Select(
                    self.MATCH_MODE_OPTIONS,
                    value=self.initial_match_mode,
                    allow_blank=False,
                    id="sel-rule-match-mode",
                )
                sel_mode.tooltip = "Choose simple single-pattern mode or compound boolean condition mode"
                self.watch(sel_mode, "value", self._on_watched_match_mode, init=False)
                yield sel_mode

                with Horizontal(classes="rule-flags-row"):
                    chk_negate = Checkbox(
                        "Negate",
                        value=self.initial_negate,
                        id="chk-rule-negate",
                    )
                    chk_negate.tooltip = "Negate the overall rule match result"
                    self.watch(
                        chk_negate, "value", self._on_watched_draft_field, init=False
                    )
                    yield chk_negate
                    chk_regex = Checkbox(
                        "Regex",
                        value=self.initial_regex,
                        id="chk-rule-regex",
                    )
                    chk_regex.tooltip = (
                        "Evaluate expression as a bounded ReDoS-safe regular expression"
                    )
                    self.watch(
                        chk_regex, "value", self._on_watched_draft_field, init=False
                    )
                    yield chk_regex
                    chk_case = Checkbox(
                        "Case-sensitive",
                        value=self.initial_case_sensitive,
                        id="chk-rule-case",
                    )
                    chk_case.tooltip = "Match character casing exactly"
                    self.watch(
                        chk_case, "value", self._on_watched_draft_field, init=False
                    )
                    yield chk_case

                yield Label(
                    "Pattern / Expression:",
                    classes="field-label",
                    id="lbl-rule-pattern",
                )
                inp_pattern = Input(
                    value=self.initial_pattern,
                    placeholder="e.g. invoice, ^INV-\\d+, > 30d, > 10MB (auto-summarized in compound mode)",
                    id="input-rule-pattern",
                )
                inp_pattern.tooltip = "Keyword substring or policy expression (regex, glob, age, date, or size)"
                self.watch(
                    inp_pattern, "value", self._on_watched_draft_field, init=False
                )
                yield inp_pattern

                with Vertical(
                    id="compound-clauses-section",
                    classes=compound_classes,
                ):
                    yield Label("Condition Clauses:", classes="field-label")
                    if self._nested_groups:
                        yield Label(
                            f"Preserving {len(self._nested_groups)} nested condition group(s) from imported policy.",
                            classes="nested-groups-note",
                            id="lbl-nested-groups-note",
                        )
                    with Vertical(id="compound-clauses-list"):
                        initial_clauses: list[dict[str, Any] | None] = list(
                            self._initial_leaf_clauses
                        )
                        if (
                            self.initial_match_mode != "simple"
                            and not initial_clauses
                            and not self._nested_groups
                        ):
                            initial_clauses = [None]
                        for clause in initial_clauses:
                            row = _PolicyClauseRow(self._next_clause_idx, clause=clause)
                            self._next_clause_idx += 1
                            yield row
                    with Horizontal(classes="clause-button-row"):
                        btn_add_clause = Button(
                            "Add Clause", id="btn-add-clause", variant="default"
                        )
                        btn_add_clause.tooltip = "Append another condition clause"
                        yield btn_add_clause
                        btn_rem_clause = Button(
                            "Remove Clause", id="btn-remove-clause", variant="default"
                        )
                        btn_rem_clause.tooltip = "Remove the last condition clause"
                        yield btn_rem_clause

                yield Label("Target Folder:", classes="field-label")
                inp_target = Input(
                    value=self.initial_target,
                    placeholder="e.g. Finances/Invoices (optional for trash / duplicate policies)",
                    id="input-rule-target",
                )
                inp_target.tooltip = "Relative destination folder inside the active workspace (leave blank for trash or duplicate policies)"
                self.watch(
                    inp_target, "value", self._on_watched_draft_field, init=False
                )
                yield inp_target

                yield Label("Rename Template (optional):", classes="field-label")
                inp_rename = Input(
                    value=self.initial_rename_pattern,
                    placeholder="e.g. {date}_{stem}{extension}",
                    id="input-rule-rename-pattern",
                )
                inp_rename.tooltip = (
                    "Optional filename rename template (e.g. {date}_{stem}{extension})"
                )
                yield inp_rename

                with Vertical(id="policy-fields-container", classes=pol_cls):
                    yield Label("Policy Type:", classes="field-label")
                    sel_ptype = Select(
                        policy_types,
                        value=self.initial_policy_type,
                        allow_blank=False,
                        id="select-policy-type",
                    )
                    sel_ptype.tooltip = "Select policy evaluation strategy"
                    self.watch(
                        sel_ptype, "value", self._on_watched_draft_field, init=False
                    )
                    yield sel_ptype

                    yield Label("Priority (integer):", classes="field-label")
                    inp_prio = Input(
                        value=str(self.initial_priority),
                        placeholder="e.g. 10 (higher runs first)",
                        id="input-policy-priority",
                    )
                    inp_prio.tooltip = (
                        "Integer priority; higher-priority policies evaluate first"
                    )
                    self.watch(
                        inp_prio, "value", self._on_watched_draft_field, init=False
                    )
                    yield inp_prio

                    yield Label("Policy Action (optional):", classes="field-label")
                    inp_action = Input(
                        value=self.initial_action,
                        placeholder="archive, retain, quarantine, redact, unarchive, trash",
                        id="input-policy-action",
                    )
                    inp_action.tooltip = "Optional policy action (archive, retain, quarantine, redact, unarchive, trash)"
                    self.watch(
                        inp_action, "value", self._on_watched_draft_field, init=False
                    )
                    yield inp_action

                    chk_halt = Checkbox(
                        "Halting (stop evaluating lower-priority rules on match)",
                        value=self.initial_halting,
                        id="chk-policy-halting",
                    )
                    chk_halt.tooltip = (
                        "Stop evaluating lower-priority policies when this rule matches"
                    )
                    self.watch(
                        chk_halt, "value", self._on_watched_draft_field, init=False
                    )
                    yield chk_halt

                with Vertical(id="rule-preview-box", classes="preview-box"):
                    yield Label("Sample File Preview:", classes="field-label")
                    sel_sample = Select(
                        sample_options,
                        allow_blank=True,
                        prompt="Select workspace sample file...",
                        id="select-sample-file",
                    )
                    sel_sample.tooltip = "Choose a workspace file to live-test this rule without moving files"
                    self.watch(
                        sel_sample, "value", self._on_watched_draft_field, init=False
                    )
                    yield sel_sample
                    total_files = len(self._workspace_items)
                    initial_preview_msg = (
                        f"Select a sample file or enter a pattern ({total_files} workspace file(s))."
                        if total_files > 0
                        else "No active workspace folder loaded for sample preview."
                    )
                    yield Label(
                        initial_preview_msg,
                        classes="preview-status",
                        id="lbl-rule-preview",
                    )
                yield Label("", classes="error-label", id="lbl-rule-error")
            with Horizontal(classes="button-row"):
                btn_cancel = Button(
                    "Cancel", id="btn-cancel-edit-rule", variant="default"
                )
                btn_cancel.tooltip = "Cancel and discard rule changes"
                yield btn_cancel
                btn_save = Button("Save Rule", id="btn-save-rule", variant="primary")
                btn_save.tooltip = "Validate rule conditions and target path, then save"
                yield btn_save

    def _discover_workspace_files(self) -> list[tuple[str, str, str]]:
        """Discover candidate workspace files as (item_id, src_root, rel_path) tuples."""
        import os

        from app.core.scanner import (
            get_files_from_sources,
            get_files_recursively,
            parse_item_identifier,
        )

        active_app: Any = None
        with contextlib.suppress(ScreenStackError, AttributeError):
            active_app = self.app
        eff_settings = self.settings or getattr(active_app, "settings", None)
        eff_base = self.base_dir or getattr(active_app, "base_dir", None)
        eff_sources = self.source_dirs or getattr(active_app, "source_dirs", None)

        raw_items: list[str] = []
        if eff_sources and isinstance(eff_sources, list) and len(eff_sources) > 0:
            valid_sources = [s for s in eff_sources if s and os.path.isdir(str(s))]
            if valid_sources:
                raw_items = get_files_from_sources(valid_sources, settings=eff_settings)
        if not raw_items and eff_base and os.path.isdir(str(eff_base)):
            raw_items = get_files_recursively(str(eff_base), settings=eff_settings)

        discovered: list[tuple[str, str, str]] = []
        for item in raw_items[: self.MAX_WORKSPACE_PREVIEW_FILES]:
            s_root, rel_p = parse_item_identifier(
                item, default_base_dir=str(eff_base or "")
            )
            discovered.append((item, s_root, rel_p))
        return discovered

    def _get_item_text(self, src_root: str, rel_path: str) -> str:
        """Load cached or local offline text for a workspace item."""
        import os

        from app.core.extractor import _read_preview_text_offline

        abs_p = (
            os.path.abspath(os.path.join(src_root, rel_path))
            if src_root
            else os.path.abspath(rel_path)
        )
        if abs_p in self._text_cache:
            return self._text_cache[abs_p]

        active_app: Any = None
        with contextlib.suppress(ScreenStackError, AttributeError):
            active_app = self.app
        eff_settings = self.settings or getattr(active_app, "settings", None)
        eff_db = self.db if self.db is not None else getattr(active_app, "db", None)
        raw_text, _src = _read_preview_text_offline(
            abs_p,
            settings=eff_settings,
            db=eff_db,
            base_dir=src_root or self.base_dir or getattr(active_app, "base_dir", None),
        )
        self._text_cache[abs_p] = raw_text or ""
        return self._text_cache[abs_p]

    def _read_draft_state(self) -> dict[str, Any]:
        """Collect current draft input values from form widgets."""
        kind_val = self.initial_kind
        try:
            sel_k = self.query_one("#select-rule-kind", Select).value
            if not _is_select_blank(sel_k):
                kind_val = str(sel_k)
        except Exception:
            pass

        match_mode = self.initial_match_mode
        try:
            sel_m = self.query_one("#sel-rule-match-mode", Select).value
            if not _is_select_blank(sel_m):
                match_mode = str(sel_m)
        except Exception:
            pass

        negate_val = self.initial_negate
        try:
            negate_val = bool(self.query_one("#chk-rule-negate", Checkbox).value)
        except Exception:
            pass

        regex_val = self.initial_regex
        try:
            regex_val = bool(self.query_one("#chk-rule-regex", Checkbox).value)
        except Exception:
            pass

        case_val = self.initial_case_sensitive
        try:
            case_val = bool(self.query_one("#chk-rule-case", Checkbox).value)
        except Exception:
            pass

        pattern_val = self.query_one("#input-rule-pattern", Input).value.strip()
        target_val = self.query_one("#input-rule-target", Input).value.strip()

        rename_val = self.initial_rename_pattern
        try:
            rename_val = self.query_one(
                "#input-rule-rename-pattern", Input
            ).value.strip()
        except Exception:
            pass

        pol_type = self.initial_policy_type
        try:
            sel_pt = self.query_one("#select-policy-type", Select).value
            if not _is_select_blank(sel_pt):
                pol_type = str(sel_pt)
        except Exception:
            pass

        prio_raw = str(self.initial_priority)
        try:
            prio_raw = self.query_one("#input-policy-priority", Input).value.strip()
        except Exception:
            pass

        action_val = self.initial_action
        try:
            action_val = self.query_one("#input-policy-action", Input).value.strip()
        except Exception:
            pass

        halting_val = self.initial_halting
        try:
            halting_val = bool(self.query_one("#chk-policy-halting", Checkbox).value)
        except Exception:
            pass

        raw_conditions: list[dict[str, Any]] = []
        if match_mode != "simple":
            try:
                clauses_list = self.query_one("#compound-clauses-list", Vertical)
                rows = list(clauses_list.query(_PolicyClauseRow))
                raw_conditions = [
                    r.to_condition_dict()
                    for r in rows
                    if r.to_condition_dict().get("value")
                ] + copy.deepcopy(self._nested_groups)
            except Exception:
                raw_conditions = copy.deepcopy(self._nested_groups)

        return {
            "kind": kind_val,
            "match_mode": match_mode,
            "negate": negate_val,
            "regex": regex_val,
            "case_sensitive": case_val,
            "conditions": raw_conditions,
            "pattern": pattern_val,
            "target": target_val,
            "rename_pattern": rename_val,
            "policy_type": pol_type,
            "priority_raw": prio_raw,
            "action": action_val,
            "halting": halting_val,
        }

    def _matches_draft(
        self, draft: dict[str, Any], src_root: str, rel_path: str
    ) -> bool:
        """Evaluate whether a workspace file matches the current draft rule locally."""
        import os
        import re

        from app.core.network_guard import block_external_network
        from app.core.policy_engine import METADATA_POLICY_TYPES, PolicyEngine

        pattern = draft["pattern"]
        kind = draft["kind"]
        pol_type = draft["policy_type"]
        match_mode = draft["match_mode"]
        is_compound = match_mode != "simple"
        has_flags = bool(draft["negate"] or draft["regex"] or draft["case_sensitive"])
        conditions = draft["conditions"]

        eff_pattern = pattern
        if (
            not is_compound
            and not eff_pattern
            and kind == "policy"
            and pol_type == "duplicate"
        ):
            eff_pattern = "*"

        if is_compound:
            if not conditions:
                return False
        elif not eff_pattern and not (
            kind == "policy" and pol_type in ("unarchive", "duplicate")
        ):
            return False

        with block_external_network("inline rule preview"):
            abs_p = (
                os.path.abspath(os.path.join(src_root, rel_path))
                if src_root
                else os.path.abspath(rel_path)
            )
            if (
                not is_compound
                and kind == "policy"
                and pol_type in METADATA_POLICY_TYPES
            ):
                doc_text = ""
                status_tag: str | None = None
            else:
                doc_text = self._get_item_text(src_root, rel_path)
                status_re = (
                    re.match(r"^\[STATUS:(.*?)\]$", doc_text.strip())
                    if doc_text
                    else None
                )
                status_tag = status_re.group(1) if status_re else None

            wants_policy = bool(
                kind == "policy"
                or is_compound
                or has_flags
                or (
                    kind in ("keyword", "learned")
                    and (draft["rename_pattern"] or draft["action"])
                )
            )
            if wants_policy:
                try:
                    prio_int = int(draft["priority_raw"] or "0")
                except ValueError:
                    prio_int = 0
                eff_type = pol_type if kind == "policy" else "keyword"
                pol_dict: dict[str, Any] = {
                    "type": eff_type,
                    "expression": eff_pattern or "*",
                    "target_path": draft["target"],
                    "priority": prio_int,
                    "halting": draft["halting"],
                    "enabled": True,
                }
                if is_compound:
                    pol_dict["match_mode"] = match_mode
                    pol_dict["conditions"] = conditions
                if draft["negate"]:
                    pol_dict["negate"] = True
                if draft["regex"]:
                    pol_dict["regex"] = True
                if draft["case_sensitive"]:
                    pol_dict["case_sensitive"] = True
                if draft["action"]:
                    pol_dict["action"] = draft["action"]
                try:
                    return bool(
                        PolicyEngine.match_policy(
                            pol_dict,
                            rel_path,
                            doc_text,
                            status_tag,
                            abs_file_path=abs_p,
                        )
                    )
                except Exception:
                    return False

            filename_only = os.path.basename(rel_path).lower()
            doc_lower = (doc_text or "").lower()
            text_to_search = (
                filename_only if status_tag else f"{filename_only} {doc_lower}"
            )
            if kind == "learned":
                from app.core.metadata import matches_learned_rule_pattern

                return matches_learned_rule_pattern(pattern, filename_only)
            return pattern.lower() in text_to_search

    def _refresh_preview(self, announce_change: bool = False) -> None:
        """Recompute sample file match status and total workspace match count."""
        from app.core.policy_engine import (
            METADATA_POLICY_TYPES,
            validate_metadata_expression,
            validate_safe_regex,
        )

        try:
            lbl = self.query_one("#lbl-rule-preview", Label)
        except Exception:
            return

        draft = self._read_draft_state()
        pattern = draft["pattern"]
        kind = draft["kind"]
        pol_type = draft["policy_type"]
        is_compound = draft["match_mode"] != "simple"
        conditions = draft["conditions"]

        # Validate regex or metadata expression early so user gets live syntax/ReDoS feedback
        if not is_compound and draft["regex"] and pattern:
            try:
                validate_safe_regex(pattern, case_sensitive=draft["case_sensitive"])
            except ValueError as exc:
                msg = f"Invalid regex expression: {exc}"
                lbl.update(msg)
                lbl.remove_class("match")
                lbl.add_class("no-match")
                if announce_change:
                    self.announce(msg)
                return
        elif (
            not is_compound
            and kind == "policy"
            and pol_type == "pattern"
            and pattern
            and not pattern.startswith(("*", "?"))
        ):
            import re

            try:
                re.compile(pattern)
            except re.error as exc:
                msg = f"Invalid regex expression: {exc}"
                lbl.update(msg)
                lbl.remove_class("match")
                lbl.add_class("no-match")
                if announce_change:
                    self.announce(msg)
                return
        elif (
            not is_compound
            and kind == "policy"
            and pol_type in METADATA_POLICY_TYPES
            and pattern
        ):
            try:
                validate_metadata_expression(pol_type, pattern)
            except ValueError as exc:
                msg = f"Invalid {pol_type} expression: {exc}"
                lbl.update(msg)
                lbl.remove_class("match")
                lbl.add_class("no-match")
                if announce_change:
                    self.announce(msg)
                return

        selected_item: str | None = None
        try:
            sel_val = self.query_one("#select-sample-file", Select).value
            if not _is_select_blank(sel_val):
                selected_item = str(sel_val)
        except Exception:
            selected_item = None

        total_files = len(self._workspace_items)
        has_testable_input = (
            bool(conditions)
            if is_compound
            else bool(
                pattern or (kind == "policy" and pol_type in ("unarchive", "duplicate"))
            )
        )
        if not has_testable_input:
            if selected_item:
                disp = selected_item.split("::", 1)[-1]
                msg = f"Enter a pattern to test against '{disp}' ({total_files} workspace file(s))."
            elif total_files > 0:
                msg = f"Select a sample file or enter a pattern ({total_files} workspace file(s))."
            else:
                msg = "No active workspace folder loaded for sample preview."
            lbl.update(msg)
            lbl.remove_class("match")
            lbl.remove_class("no-match")
            if announce_change:
                self.announce(msg)
            return

        match_count = sum(
            1
            for _item_id, s_root, rel_p in self._workspace_items
            if self._matches_draft(draft, s_root, rel_p)
        )

        if selected_item:
            sample_tuple = next(
                (t for t in self._workspace_items if t[0] == selected_item), None
            )
            if sample_tuple is not None:
                _id, s_root, rel_p = sample_tuple
                is_hit = self._matches_draft(draft, s_root, rel_p)
                if is_hit:
                    msg = f"✓ MATCH on '{rel_p}' | Workspace matches: {match_count} of {total_files} file(s)"
                    lbl.remove_class("no-match")
                    lbl.add_class("match")
                else:
                    msg = f"✗ NO MATCH on '{rel_p}' | Workspace matches: {match_count} of {total_files} file(s)"
                    lbl.remove_class("match")
                    lbl.add_class("no-match")
            else:
                msg = f"Workspace matches: {match_count} of {total_files} file(s)"
                lbl.remove_class("match")
                lbl.remove_class("no-match")
        elif total_files > 0:
            msg = f"Workspace matches: {match_count} of {total_files} file(s)"
            lbl.remove_class("match")
            lbl.remove_class("no-match")
        else:
            msg = "No workspace files available to preview."
            lbl.remove_class("match")
            lbl.remove_class("no-match")

        lbl.update(msg)
        if announce_change:
            self.announce(msg)

    def on_mount(self) -> None:
        """Focus initial input on mount, seed compound clause if needed, and load workspace sample file options."""
        super().on_mount()
        try:
            clauses_list = self.query_one("#compound-clauses-list", Vertical)
            if (
                self.initial_match_mode != "simple"
                and not list(clauses_list.query(_PolicyClauseRow))
                and not self._nested_groups
            ):
                self.add_clause_row()
        except NoMatches:
            return

        if not self._sample_options_seeded:
            self._workspace_items = self._discover_workspace_files()
            with contextlib.suppress(NoMatches):
                sel_sample = self.query_one("#select-sample-file", Select)
                options = [
                    (rel_p, item_id) for item_id, _s, rel_p in self._workspace_items
                ]
                sel_sample.set_options(options)
                self._sample_options_seeded = True

        self._mounted_ready = True
        self._refresh_preview(announce_change=False)
        if self.focused is None:
            with contextlib.suppress(NoMatches):
                self.query_one("#input-rule-pattern", Input).focus()

    def _sync_rule_kind_visibility(self, raw_value: object) -> None:
        """Show or hide policy-specific fields based on rule category value."""
        kind_str = self.initial_kind if _is_select_blank(raw_value) else str(raw_value)
        with contextlib.suppress(NoMatches):
            pol_box = self.query_one("#policy-fields-container", Vertical)
            if kind_str == "policy":
                pol_box.remove_class("hidden")
            else:
                pol_box.add_class("hidden")

    def _sync_match_mode_visibility(self, raw_value: object) -> None:
        """Show or hide the compound clause builder based on match mode value."""
        mode = (
            self.initial_match_mode if _is_select_blank(raw_value) else str(raw_value)
        )
        try:
            section = self.query_one("#compound-clauses-section", Vertical)
            clauses_list = self.query_one("#compound-clauses-list", Vertical)
        except NoMatches:
            return
        if mode == "simple":
            section.add_class("hidden")
        else:
            section.remove_class("hidden")
            if (
                not list(clauses_list.query(_PolicyClauseRow))
                and not self._nested_groups
            ):
                seed_val = ""
                with contextlib.suppress(NoMatches):
                    seed_val = self.query_one(
                        "#input-rule-pattern", Input
                    ).value.strip()
                seed_clause = (
                    {"field": "name", "operator": "contains", "value": seed_val}
                    if seed_val
                    else None
                )
                self.add_clause_row(clause=seed_clause)

    def _on_watched_rule_kind(self, value: object) -> None:
        """Update policy field visibility and preview synchronously when rule kind mutates."""
        self._sync_rule_kind_visibility(value)
        self._refresh_preview(announce_change=False)

    def _on_watched_match_mode(self, value: object) -> None:
        """Update compound clause visibility and preview synchronously when match mode mutates."""
        self._sync_match_mode_visibility(value)
        self._refresh_preview(announce_change=False)

    def _on_watched_draft_field(self, _value: object) -> None:
        """Refresh live sample preview synchronously when a draft control value mutates."""
        self._refresh_preview(announce_change=False)

    def add_clause_row(self, clause: dict[str, Any] | None = None) -> _PolicyClauseRow:
        """Mount a new condition clause row inside the compound clauses list."""
        clauses_list = self.query_one("#compound-clauses-list", Vertical)
        row = _PolicyClauseRow(self._next_clause_idx, clause=clause)
        self._next_clause_idx += 1
        clauses_list.mount(row)
        return row

    def remove_last_clause_row(self) -> None:
        """Remove the last mounted condition clause row if more than zero exist."""
        clauses_list = self.query_one("#compound-clauses-list", Vertical)
        rows = list(clauses_list.query(_PolicyClauseRow))
        if rows:
            rows[-1].remove()

    @on(Button.Pressed, "#btn-add-clause")
    def _on_add_clause_pressed(self) -> None:
        """Handle Add Clause button press."""
        from app.core.policy_engine import MAX_CONDITION_CLAUSES

        clauses_list = self.query_one("#compound-clauses-list", Vertical)
        if len(list(clauses_list.query(_PolicyClauseRow))) >= MAX_CONDITION_CLAUSES:
            err_lbl = self.query_one("#lbl-rule-error", Label)
            msg = f"Cannot exceed {MAX_CONDITION_CLAUSES} condition clauses per rule."
            err_lbl.update(msg)
            err_lbl.add_class("visible")
            self.announce(msg, priority="assertive")
            return
        self.add_clause_row()
        self.announce("Added condition clause row.")
        if self._mounted_ready:
            self._refresh_preview(announce_change=False)

    @on(Button.Pressed, "#btn-remove-clause")
    def _on_remove_clause_pressed(self) -> None:
        """Handle Remove Clause button press."""
        clauses_list = self.query_one("#compound-clauses-list", Vertical)
        rows = list(clauses_list.query(_PolicyClauseRow))
        if len(rows) <= 1 and not self._nested_groups:
            err_lbl = self.query_one("#lbl-rule-error", Label)
            msg = "Compound rules require at least one condition clause."
            err_lbl.update(msg)
            err_lbl.add_class("visible")
            self.announce(msg, priority="assertive")
            return
        self.remove_last_clause_row()
        self.announce("Removed last condition clause row.")
        if self._mounted_ready:
            self._refresh_preview(announce_change=False)

    @on(Select.Changed, "#sel-rule-match-mode")
    def _on_match_mode_changed(self, event: Select.Changed) -> None:
        """Show or hide the compound clause builder when match mode changes."""
        self._sync_match_mode_visibility(event.value)
        self._refresh_preview(announce_change=self._mounted_ready)

    @on(Select.Changed, "#select-rule-kind")
    def _on_rule_kind_changed(self, event: Select.Changed) -> None:
        """Show or hide policy-specific fields when switching rule category."""
        self._sync_rule_kind_visibility(event.value)
        self._refresh_preview(announce_change=self._mounted_ready)

    @on(Select.Changed, "#select-policy-type")
    @on(Select.Changed, "#select-sample-file")
    @on(Select.Changed, ".clause-field-select")
    @on(Select.Changed, ".clause-op-select")
    def _on_preview_select_changed(self, event: Select.Changed) -> None:
        """Re-evaluate sample preview when policy type, clause dropdown, or sample file selection changes."""
        self._refresh_preview(announce_change=self._mounted_ready)

    @on(Input.Changed, "#input-rule-pattern")
    @on(Input.Changed, "#input-rule-target")
    @on(Input.Changed, "#input-policy-priority")
    @on(Input.Changed, "#input-policy-action")
    @on(Input.Changed, ".clause-val-input")
    def _on_preview_input_changed(self, event: Input.Changed) -> None:
        """Re-evaluate sample preview immediately as draft rule inputs change."""
        self._refresh_preview(announce_change=self._mounted_ready)

    @on(Checkbox.Changed)
    def _on_preview_checkbox_changed(self, event: Checkbox.Changed) -> None:
        """Re-evaluate preview when rule or clause checkboxes toggle."""
        self._refresh_preview(announce_change=False)

    @on(Button.Pressed, "#btn-save-rule")
    def action_save(self) -> None:
        """Validate inputs and dismiss modal with keyword rule or policy definition."""
        from app.config import Settings
        from app.core.path_utils import ILLEGAL_PATH_CHARS_SET, validate_target_path
        from app.core.pattern_formatter import PatternTokenFormatter
        from app.core.policy_engine import (
            PolicyEngine,
            summarize_policy_conditions,
            validate_policy_conditions,
            validate_safe_regex,
        )

        draft = self._read_draft_state()
        kind = draft["kind"]
        match_mode = draft["match_mode"]
        negate = draft["negate"]
        is_regex = draft["regex"]
        case_sensitive = draft["case_sensitive"]
        pattern = draft["pattern"]
        target = draft["target"]
        rename_pat = draft["rename_pattern"]
        err_lbl = self.query_one("#lbl-rule-error", Label)

        if rename_pat:
            if (
                "/" in rename_pat
                or "\\" in rename_pat
                or ".." in rename_pat
                or "\x00" in rename_pat
                or any(ch in ILLEGAL_PATH_CHARS_SET for ch in rename_pat)
            ):
                msg = (
                    "Rename template cannot contain path separators, '..', null bytes, "
                    "or illegal filename characters."
                )
                err_lbl.update(msg)
                err_lbl.add_class("visible")
                self.announce(msg, priority="assertive")
                if hasattr(self.app, "notify"):
                    self.app.notify(msg, severity="error")
                return
            preview_fn = PatternTokenFormatter.format_pattern(
                rename_pat,
                metadata={
                    "date": "2026-01-15",
                    "category": "sample",
                    "original": "document",
                    "stem": "document",
                    "extension": ".pdf",
                },
                seq=1,
                fallback_original="",
            )
            if not preview_fn or "/" in preview_fn or "\\" in preview_fn:
                msg = (
                    f"Rename template '{rename_pat}' does not produce a valid filename."
                )
                err_lbl.update(msg)
                err_lbl.add_class("visible")
                self.announce(msg, priority="assertive")
                if hasattr(self.app, "notify"):
                    self.app.notify(msg, severity="error")
                return

        is_compound = match_mode != "simple"
        has_policy_flags = bool(negate or is_regex or case_sensitive)
        wants_policy = bool(
            kind == "policy"
            or is_compound
            or has_policy_flags
            or (kind in ("keyword", "learned") and (rename_pat or draft["action"]))
        )

        if not wants_policy:
            if not pattern:
                err_lbl.update("Rule pattern/keyword cannot be empty.")
                err_lbl.add_class("visible")
                self.announce(
                    "Rule pattern/keyword cannot be empty.", priority="assertive"
                )
                return

            if not target:
                err_lbl.update("Target folder cannot be empty.")
                err_lbl.add_class("visible")
                self.announce("Target folder cannot be empty.", priority="assertive")
                return

            try:
                if "{" in target and "}" in target:
                    PatternTokenFormatter.format_target_path(
                        target,
                        metadata={
                            "date": "2026-01-15",
                            "category": "sample",
                            "original": "document",
                            "stem": "document",
                            "extension": ".pdf",
                        },
                        seq=1,
                    )
                else:
                    validate_target_path(target, keyword=pattern)
            except (ValueError, Exception) as exc:
                err_lbl.update(f"Invalid path: {exc}")
                err_lbl.add_class("visible")
                self.announce(f"Invalid target path: {exc}", priority="assertive")
                if hasattr(self.app, "notify"):
                    self.app.notify(str(exc), severity="error")
                return

            self.dismiss(
                {
                    "kind": kind,
                    "type": kind,
                    "pattern": pattern,
                    "target": target,
                    "rename_pattern": "",
                    "is_policy": False,
                }
            )
            return

        # Policy validation (explicit Policy Rule category or promoted via compound/flags/rename_pattern)
        pol_type = draft["policy_type"] if kind == "policy" else "keyword"
        action_raw = draft["action"]

        try:
            if (
                kind != "policy"
                and self.initial_policy is None
                and draft["priority_raw"] in ("", "0")
            ):
                prio_int = 75
            else:
                prio_int = int(draft["priority_raw"] or "0")
        except ValueError:
            err_lbl.update("Policy priority must be a valid integer.")
            err_lbl.add_class("visible")
            self.announce(
                "Policy priority must be a valid integer.", priority="assertive"
            )
            return

        normalized_action: str | None = None
        if action_raw:
            if not PolicyEngine.validate_policy_action(action_raw):
                supported = ", ".join(sorted(PolicyEngine.SUPPORTED_ACTIONS))
                msg = f"Unsupported policy action '{action_raw}'. Supported actions: {supported}."
                err_lbl.update(msg)
                err_lbl.add_class("visible")
                self.announce(msg, priority="assertive")
                if hasattr(self.app, "notify"):
                    self.app.notify(msg, severity="error")
                return
            normalized_action = str(action_raw).strip().lower()
        elif pol_type == "unarchive":
            normalized_action = "unarchive"
        elif pol_type == "duplicate" and not target:
            normalized_action = "trash"

        if not is_compound:
            if not pattern and pol_type == "duplicate":
                pattern = "*"

            if (
                not pattern
                and pol_type not in ("unarchive", "duplicate")
                and normalized_action not in ("trash", "unarchive")
            ):
                msg = (
                    "Policy expression cannot be empty."
                    if kind == "policy"
                    else "Rule pattern/keyword cannot be empty."
                )
                err_lbl.update(msg)
                err_lbl.add_class("visible")
                self.announce(msg, priority="assertive")
                return

            if is_regex and pattern:
                try:
                    validate_safe_regex(pattern, case_sensitive=case_sensitive)
                except ValueError as exc:
                    err_lbl.update(f"Invalid regex: {exc}")
                    err_lbl.add_class("visible")
                    self.announce(f"Invalid regex: {exc}", priority="assertive")
                    return

            if kind != "policy" and self.initial_policy is None:
                pol_type = (
                    "pattern"
                    if (
                        is_regex
                        or "*" in pattern
                        or "?" in pattern
                        or pattern.startswith(".")
                    )
                    else "keyword"
                )
            elif is_regex and pol_type == "keyword" and self.initial_policy is None:
                pol_type = "pattern"

            candidate_pol: dict[str, Any] = (
                copy.deepcopy(self.initial_policy)
                if isinstance(self.initial_policy, dict)
                else {}
            )
            candidate_pol.update(
                {
                    "type": pol_type,
                    "expression": pattern,
                    "target_path": target,
                    "priority": prio_int,
                    "halting": draft["halting"] if kind == "policy" else False,
                    "enabled": self.initial_enabled,
                }
            )
            candidate_pol.pop("match_mode", None)
            candidate_pol.pop("conditions", None)
            if normalized_action:
                candidate_pol["action"] = normalized_action
            else:
                candidate_pol.pop("action", None)
            if rename_pat:
                candidate_pol["rename_pattern"] = rename_pat
            else:
                candidate_pol.pop("rename_pattern", None)
            if negate:
                candidate_pol["negate"] = True
            else:
                candidate_pol.pop("negate", None)
            if is_regex:
                candidate_pol["regex"] = True
            else:
                candidate_pol.pop("regex", None)
            if case_sensitive:
                candidate_pol["case_sensitive"] = True
            else:
                candidate_pol.pop("case_sensitive", None)

            try:
                validated_list = Settings.validate_policies([candidate_pol])
                validated_pol = dict(validated_list[0])
            except (ValueError, Exception) as exc:
                err_lbl.update(f"Invalid policy: {exc}")
                err_lbl.add_class("visible")
                self.announce(f"Invalid policy: {exc}", priority="assertive")
                if hasattr(self.app, "notify"):
                    self.app.notify(str(exc), severity="error")
                return

            self.dismiss(
                {
                    "kind": "policy",
                    "is_policy": True,
                    "type": str(validated_pol.get("type", pol_type)),
                    "pattern": str(validated_pol.get("expression", pattern)),
                    "target": str(validated_pol.get("target_path", target)),
                    "rename_pattern": str(
                        validated_pol.get("rename_pattern", "") or ""
                    ),
                    "priority": int(validated_pol.get("priority", prio_int)),
                    "policy": validated_pol,
                }
            )
            return

        # Compound condition validation
        clauses_list = self.query_one("#compound-clauses-list", Vertical)
        rows = list(clauses_list.query(_PolicyClauseRow))
        raw_conditions: list[dict[str, Any]] = [
            row.to_condition_dict() for row in rows
        ] + copy.deepcopy(self._nested_groups)

        if not raw_conditions:
            err_lbl.update("Compound rules require at least one condition clause.")
            err_lbl.add_class("visible")
            self.announce(
                "Compound rules require at least one condition clause.",
                priority="assertive",
            )
            return

        try:
            validated_conditions = validate_policy_conditions(raw_conditions)
        except ValueError as exc:
            err_lbl.update(f"Invalid condition: {exc}")
            err_lbl.add_class("visible")
            self.announce(f"Invalid condition: {exc}", priority="assertive")
            return

        auto_summary = summarize_policy_conditions(
            validated_conditions,
            match_mode=match_mode,
            negate=negate,
        )
        effective_pattern = (
            auto_summary
            if (not pattern or pattern == self._initial_auto_summary)
            else pattern
        )

        has_pattern_clause = any(
            isinstance(c, dict)
            and (
                c.get("field") in {"extension", "path"}
                or c.get("operator") in {"glob", "regex"}
            )
            for c in validated_conditions
        )
        default_type = "pattern" if (has_pattern_clause or is_regex) else "keyword"
        eff_pol_type = (
            default_type
            if (
                kind != "policy"
                or (self.initial_policy is None and pol_type == "keyword")
            )
            else pol_type
        )

        candidate_compound: dict[str, Any] = (
            copy.deepcopy(self.initial_policy)
            if isinstance(self.initial_policy, dict)
            else {}
        )
        candidate_compound.update(
            {
                "type": eff_pol_type,
                "expression": effective_pattern,
                "target_path": target,
                "priority": prio_int,
                "halting": draft["halting"] if kind == "policy" else False,
                "enabled": self.initial_enabled,
                "match_mode": match_mode,
                "conditions": validated_conditions,
            }
        )
        if normalized_action:
            candidate_compound["action"] = normalized_action
        else:
            candidate_compound.pop("action", None)
        if rename_pat:
            candidate_compound["rename_pattern"] = rename_pat
        else:
            candidate_compound.pop("rename_pattern", None)
        if negate:
            candidate_compound["negate"] = True
        else:
            candidate_compound.pop("negate", None)
        if is_regex:
            candidate_compound["regex"] = True
        else:
            candidate_compound.pop("regex", None)
        if case_sensitive:
            candidate_compound["case_sensitive"] = True
        else:
            candidate_compound.pop("case_sensitive", None)

        try:
            validated_list = Settings.validate_policies([candidate_compound])
            validated_pol = dict(validated_list[0])
        except (ValueError, Exception) as exc:
            err_lbl.update(f"Invalid policy: {exc}")
            err_lbl.add_class("visible")
            self.announce(f"Invalid policy: {exc}", priority="assertive")
            if hasattr(self.app, "notify"):
                self.app.notify(str(exc), severity="error")
            return

        self.dismiss(
            {
                "kind": "policy",
                "is_policy": True,
                "type": str(validated_pol.get("type", eff_pol_type)),
                "pattern": str(validated_pol.get("expression", effective_pattern)),
                "target": str(validated_pol.get("target_path", target)),
                "rename_pattern": str(validated_pol.get("rename_pattern", "") or ""),
                "priority": int(validated_pol.get("priority", prio_int)),
                "policy": validated_pol,
            }
        )

    @on(Button.Pressed, "#btn-cancel-edit-rule")
    def action_cancel_button(self) -> None:
        """Cancel on Cancel button."""
        self.announce("Cancelled rule editing.")
        self.dismiss(None)

    def action_cancel(self) -> None:
        """Cancel on Escape."""
        self.announce("Cancelled rule editing dialog.")
        self.dismiss(None)

action_cancel()

Cancel on Escape.

Source code in app/ui/modals/rules.py
3226
3227
3228
3229
def action_cancel(self) -> None:
    """Cancel on Escape."""
    self.announce("Cancelled rule editing dialog.")
    self.dismiss(None)

action_cancel_button()

Cancel on Cancel button.

Source code in app/ui/modals/rules.py
3220
3221
3222
3223
3224
@on(Button.Pressed, "#btn-cancel-edit-rule")
def action_cancel_button(self) -> None:
    """Cancel on Cancel button."""
    self.announce("Cancelled rule editing.")
    self.dismiss(None)

action_save()

Validate inputs and dismiss modal with keyword rule or policy definition.

Source code in app/ui/modals/rules.py
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
@on(Button.Pressed, "#btn-save-rule")
def action_save(self) -> None:
    """Validate inputs and dismiss modal with keyword rule or policy definition."""
    from app.config import Settings
    from app.core.path_utils import ILLEGAL_PATH_CHARS_SET, validate_target_path
    from app.core.pattern_formatter import PatternTokenFormatter
    from app.core.policy_engine import (
        PolicyEngine,
        summarize_policy_conditions,
        validate_policy_conditions,
        validate_safe_regex,
    )

    draft = self._read_draft_state()
    kind = draft["kind"]
    match_mode = draft["match_mode"]
    negate = draft["negate"]
    is_regex = draft["regex"]
    case_sensitive = draft["case_sensitive"]
    pattern = draft["pattern"]
    target = draft["target"]
    rename_pat = draft["rename_pattern"]
    err_lbl = self.query_one("#lbl-rule-error", Label)

    if rename_pat:
        if (
            "/" in rename_pat
            or "\\" in rename_pat
            or ".." in rename_pat
            or "\x00" in rename_pat
            or any(ch in ILLEGAL_PATH_CHARS_SET for ch in rename_pat)
        ):
            msg = (
                "Rename template cannot contain path separators, '..', null bytes, "
                "or illegal filename characters."
            )
            err_lbl.update(msg)
            err_lbl.add_class("visible")
            self.announce(msg, priority="assertive")
            if hasattr(self.app, "notify"):
                self.app.notify(msg, severity="error")
            return
        preview_fn = PatternTokenFormatter.format_pattern(
            rename_pat,
            metadata={
                "date": "2026-01-15",
                "category": "sample",
                "original": "document",
                "stem": "document",
                "extension": ".pdf",
            },
            seq=1,
            fallback_original="",
        )
        if not preview_fn or "/" in preview_fn or "\\" in preview_fn:
            msg = (
                f"Rename template '{rename_pat}' does not produce a valid filename."
            )
            err_lbl.update(msg)
            err_lbl.add_class("visible")
            self.announce(msg, priority="assertive")
            if hasattr(self.app, "notify"):
                self.app.notify(msg, severity="error")
            return

    is_compound = match_mode != "simple"
    has_policy_flags = bool(negate or is_regex or case_sensitive)
    wants_policy = bool(
        kind == "policy"
        or is_compound
        or has_policy_flags
        or (kind in ("keyword", "learned") and (rename_pat or draft["action"]))
    )

    if not wants_policy:
        if not pattern:
            err_lbl.update("Rule pattern/keyword cannot be empty.")
            err_lbl.add_class("visible")
            self.announce(
                "Rule pattern/keyword cannot be empty.", priority="assertive"
            )
            return

        if not target:
            err_lbl.update("Target folder cannot be empty.")
            err_lbl.add_class("visible")
            self.announce("Target folder cannot be empty.", priority="assertive")
            return

        try:
            if "{" in target and "}" in target:
                PatternTokenFormatter.format_target_path(
                    target,
                    metadata={
                        "date": "2026-01-15",
                        "category": "sample",
                        "original": "document",
                        "stem": "document",
                        "extension": ".pdf",
                    },
                    seq=1,
                )
            else:
                validate_target_path(target, keyword=pattern)
        except (ValueError, Exception) as exc:
            err_lbl.update(f"Invalid path: {exc}")
            err_lbl.add_class("visible")
            self.announce(f"Invalid target path: {exc}", priority="assertive")
            if hasattr(self.app, "notify"):
                self.app.notify(str(exc), severity="error")
            return

        self.dismiss(
            {
                "kind": kind,
                "type": kind,
                "pattern": pattern,
                "target": target,
                "rename_pattern": "",
                "is_policy": False,
            }
        )
        return

    # Policy validation (explicit Policy Rule category or promoted via compound/flags/rename_pattern)
    pol_type = draft["policy_type"] if kind == "policy" else "keyword"
    action_raw = draft["action"]

    try:
        if (
            kind != "policy"
            and self.initial_policy is None
            and draft["priority_raw"] in ("", "0")
        ):
            prio_int = 75
        else:
            prio_int = int(draft["priority_raw"] or "0")
    except ValueError:
        err_lbl.update("Policy priority must be a valid integer.")
        err_lbl.add_class("visible")
        self.announce(
            "Policy priority must be a valid integer.", priority="assertive"
        )
        return

    normalized_action: str | None = None
    if action_raw:
        if not PolicyEngine.validate_policy_action(action_raw):
            supported = ", ".join(sorted(PolicyEngine.SUPPORTED_ACTIONS))
            msg = f"Unsupported policy action '{action_raw}'. Supported actions: {supported}."
            err_lbl.update(msg)
            err_lbl.add_class("visible")
            self.announce(msg, priority="assertive")
            if hasattr(self.app, "notify"):
                self.app.notify(msg, severity="error")
            return
        normalized_action = str(action_raw).strip().lower()
    elif pol_type == "unarchive":
        normalized_action = "unarchive"
    elif pol_type == "duplicate" and not target:
        normalized_action = "trash"

    if not is_compound:
        if not pattern and pol_type == "duplicate":
            pattern = "*"

        if (
            not pattern
            and pol_type not in ("unarchive", "duplicate")
            and normalized_action not in ("trash", "unarchive")
        ):
            msg = (
                "Policy expression cannot be empty."
                if kind == "policy"
                else "Rule pattern/keyword cannot be empty."
            )
            err_lbl.update(msg)
            err_lbl.add_class("visible")
            self.announce(msg, priority="assertive")
            return

        if is_regex and pattern:
            try:
                validate_safe_regex(pattern, case_sensitive=case_sensitive)
            except ValueError as exc:
                err_lbl.update(f"Invalid regex: {exc}")
                err_lbl.add_class("visible")
                self.announce(f"Invalid regex: {exc}", priority="assertive")
                return

        if kind != "policy" and self.initial_policy is None:
            pol_type = (
                "pattern"
                if (
                    is_regex
                    or "*" in pattern
                    or "?" in pattern
                    or pattern.startswith(".")
                )
                else "keyword"
            )
        elif is_regex and pol_type == "keyword" and self.initial_policy is None:
            pol_type = "pattern"

        candidate_pol: dict[str, Any] = (
            copy.deepcopy(self.initial_policy)
            if isinstance(self.initial_policy, dict)
            else {}
        )
        candidate_pol.update(
            {
                "type": pol_type,
                "expression": pattern,
                "target_path": target,
                "priority": prio_int,
                "halting": draft["halting"] if kind == "policy" else False,
                "enabled": self.initial_enabled,
            }
        )
        candidate_pol.pop("match_mode", None)
        candidate_pol.pop("conditions", None)
        if normalized_action:
            candidate_pol["action"] = normalized_action
        else:
            candidate_pol.pop("action", None)
        if rename_pat:
            candidate_pol["rename_pattern"] = rename_pat
        else:
            candidate_pol.pop("rename_pattern", None)
        if negate:
            candidate_pol["negate"] = True
        else:
            candidate_pol.pop("negate", None)
        if is_regex:
            candidate_pol["regex"] = True
        else:
            candidate_pol.pop("regex", None)
        if case_sensitive:
            candidate_pol["case_sensitive"] = True
        else:
            candidate_pol.pop("case_sensitive", None)

        try:
            validated_list = Settings.validate_policies([candidate_pol])
            validated_pol = dict(validated_list[0])
        except (ValueError, Exception) as exc:
            err_lbl.update(f"Invalid policy: {exc}")
            err_lbl.add_class("visible")
            self.announce(f"Invalid policy: {exc}", priority="assertive")
            if hasattr(self.app, "notify"):
                self.app.notify(str(exc), severity="error")
            return

        self.dismiss(
            {
                "kind": "policy",
                "is_policy": True,
                "type": str(validated_pol.get("type", pol_type)),
                "pattern": str(validated_pol.get("expression", pattern)),
                "target": str(validated_pol.get("target_path", target)),
                "rename_pattern": str(
                    validated_pol.get("rename_pattern", "") or ""
                ),
                "priority": int(validated_pol.get("priority", prio_int)),
                "policy": validated_pol,
            }
        )
        return

    # Compound condition validation
    clauses_list = self.query_one("#compound-clauses-list", Vertical)
    rows = list(clauses_list.query(_PolicyClauseRow))
    raw_conditions: list[dict[str, Any]] = [
        row.to_condition_dict() for row in rows
    ] + copy.deepcopy(self._nested_groups)

    if not raw_conditions:
        err_lbl.update("Compound rules require at least one condition clause.")
        err_lbl.add_class("visible")
        self.announce(
            "Compound rules require at least one condition clause.",
            priority="assertive",
        )
        return

    try:
        validated_conditions = validate_policy_conditions(raw_conditions)
    except ValueError as exc:
        err_lbl.update(f"Invalid condition: {exc}")
        err_lbl.add_class("visible")
        self.announce(f"Invalid condition: {exc}", priority="assertive")
        return

    auto_summary = summarize_policy_conditions(
        validated_conditions,
        match_mode=match_mode,
        negate=negate,
    )
    effective_pattern = (
        auto_summary
        if (not pattern or pattern == self._initial_auto_summary)
        else pattern
    )

    has_pattern_clause = any(
        isinstance(c, dict)
        and (
            c.get("field") in {"extension", "path"}
            or c.get("operator") in {"glob", "regex"}
        )
        for c in validated_conditions
    )
    default_type = "pattern" if (has_pattern_clause or is_regex) else "keyword"
    eff_pol_type = (
        default_type
        if (
            kind != "policy"
            or (self.initial_policy is None and pol_type == "keyword")
        )
        else pol_type
    )

    candidate_compound: dict[str, Any] = (
        copy.deepcopy(self.initial_policy)
        if isinstance(self.initial_policy, dict)
        else {}
    )
    candidate_compound.update(
        {
            "type": eff_pol_type,
            "expression": effective_pattern,
            "target_path": target,
            "priority": prio_int,
            "halting": draft["halting"] if kind == "policy" else False,
            "enabled": self.initial_enabled,
            "match_mode": match_mode,
            "conditions": validated_conditions,
        }
    )
    if normalized_action:
        candidate_compound["action"] = normalized_action
    else:
        candidate_compound.pop("action", None)
    if rename_pat:
        candidate_compound["rename_pattern"] = rename_pat
    else:
        candidate_compound.pop("rename_pattern", None)
    if negate:
        candidate_compound["negate"] = True
    else:
        candidate_compound.pop("negate", None)
    if is_regex:
        candidate_compound["regex"] = True
    else:
        candidate_compound.pop("regex", None)
    if case_sensitive:
        candidate_compound["case_sensitive"] = True
    else:
        candidate_compound.pop("case_sensitive", None)

    try:
        validated_list = Settings.validate_policies([candidate_compound])
        validated_pol = dict(validated_list[0])
    except (ValueError, Exception) as exc:
        err_lbl.update(f"Invalid policy: {exc}")
        err_lbl.add_class("visible")
        self.announce(f"Invalid policy: {exc}", priority="assertive")
        if hasattr(self.app, "notify"):
            self.app.notify(str(exc), severity="error")
        return

    self.dismiss(
        {
            "kind": "policy",
            "is_policy": True,
            "type": str(validated_pol.get("type", eff_pol_type)),
            "pattern": str(validated_pol.get("expression", effective_pattern)),
            "target": str(validated_pol.get("target_path", target)),
            "rename_pattern": str(validated_pol.get("rename_pattern", "") or ""),
            "priority": int(validated_pol.get("priority", prio_int)),
            "policy": validated_pol,
        }
    )

add_clause_row(clause=None)

Mount a new condition clause row inside the compound clauses list.

Source code in app/ui/modals/rules.py
2752
2753
2754
2755
2756
2757
2758
def add_clause_row(self, clause: dict[str, Any] | None = None) -> _PolicyClauseRow:
    """Mount a new condition clause row inside the compound clauses list."""
    clauses_list = self.query_one("#compound-clauses-list", Vertical)
    row = _PolicyClauseRow(self._next_clause_idx, clause=clause)
    self._next_clause_idx += 1
    clauses_list.mount(row)
    return row

compose()

Compose rule editor inputs, compound clause builder, policy attributes, live sample preview, and action buttons.

Source code in app/ui/modals/rules.py
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
def compose(self) -> ComposeResult:
    """Compose rule editor inputs, compound clause builder, policy attributes, live sample preview, and action buttons."""
    self._workspace_items = self._discover_workspace_files()
    sample_options = [
        (rel_p, item_id) for item_id, _s, rel_p in self._workspace_items
    ]
    self._sample_options_seeded = True

    kind_options: list[tuple[str, str]] = [
        ("Keyword Rule", "keyword"),
        ("Policy Rule", "policy"),
    ]
    if self.initial_kind == "learned":
        kind_options.insert(0, ("Learned Rule", "learned"))

    policy_types: list[tuple[str, str]] = list(self.RULE_TYPE_OPTIONS)
    known_pol_vals = {val for _lbl, val in policy_types}
    if self.initial_policy_type and self.initial_policy_type not in known_pol_vals:
        policy_types.append(
            (self.initial_policy_type.title(), self.initial_policy_type)
        )

    pol_cls = (
        "policy-grid" if self.initial_kind == "policy" else "policy-grid hidden"
    )
    compound_classes = "" if self.initial_match_mode != "simple" else "hidden"

    with ModalBox(classes="rule-edit-box modal-box"):
        yield Heading(
            self.title_text, level=1, classes="modal-title", id="modal-title"
        )
        with Vertical(classes="modal-body"):
            yield Label("Rule Category:", classes="field-label")
            sel_kind = Select(
                kind_options,
                value=self.initial_kind,
                allow_blank=False,
                id="select-rule-kind",
            )
            sel_kind.tooltip = (
                "Select whether to save a keyword rule or a prioritized policy"
            )
            self.watch(sel_kind, "value", self._on_watched_rule_kind, init=False)
            yield sel_kind

            yield Label("Match Mode:", classes="field-label")
            sel_mode = Select(
                self.MATCH_MODE_OPTIONS,
                value=self.initial_match_mode,
                allow_blank=False,
                id="sel-rule-match-mode",
            )
            sel_mode.tooltip = "Choose simple single-pattern mode or compound boolean condition mode"
            self.watch(sel_mode, "value", self._on_watched_match_mode, init=False)
            yield sel_mode

            with Horizontal(classes="rule-flags-row"):
                chk_negate = Checkbox(
                    "Negate",
                    value=self.initial_negate,
                    id="chk-rule-negate",
                )
                chk_negate.tooltip = "Negate the overall rule match result"
                self.watch(
                    chk_negate, "value", self._on_watched_draft_field, init=False
                )
                yield chk_negate
                chk_regex = Checkbox(
                    "Regex",
                    value=self.initial_regex,
                    id="chk-rule-regex",
                )
                chk_regex.tooltip = (
                    "Evaluate expression as a bounded ReDoS-safe regular expression"
                )
                self.watch(
                    chk_regex, "value", self._on_watched_draft_field, init=False
                )
                yield chk_regex
                chk_case = Checkbox(
                    "Case-sensitive",
                    value=self.initial_case_sensitive,
                    id="chk-rule-case",
                )
                chk_case.tooltip = "Match character casing exactly"
                self.watch(
                    chk_case, "value", self._on_watched_draft_field, init=False
                )
                yield chk_case

            yield Label(
                "Pattern / Expression:",
                classes="field-label",
                id="lbl-rule-pattern",
            )
            inp_pattern = Input(
                value=self.initial_pattern,
                placeholder="e.g. invoice, ^INV-\\d+, > 30d, > 10MB (auto-summarized in compound mode)",
                id="input-rule-pattern",
            )
            inp_pattern.tooltip = "Keyword substring or policy expression (regex, glob, age, date, or size)"
            self.watch(
                inp_pattern, "value", self._on_watched_draft_field, init=False
            )
            yield inp_pattern

            with Vertical(
                id="compound-clauses-section",
                classes=compound_classes,
            ):
                yield Label("Condition Clauses:", classes="field-label")
                if self._nested_groups:
                    yield Label(
                        f"Preserving {len(self._nested_groups)} nested condition group(s) from imported policy.",
                        classes="nested-groups-note",
                        id="lbl-nested-groups-note",
                    )
                with Vertical(id="compound-clauses-list"):
                    initial_clauses: list[dict[str, Any] | None] = list(
                        self._initial_leaf_clauses
                    )
                    if (
                        self.initial_match_mode != "simple"
                        and not initial_clauses
                        and not self._nested_groups
                    ):
                        initial_clauses = [None]
                    for clause in initial_clauses:
                        row = _PolicyClauseRow(self._next_clause_idx, clause=clause)
                        self._next_clause_idx += 1
                        yield row
                with Horizontal(classes="clause-button-row"):
                    btn_add_clause = Button(
                        "Add Clause", id="btn-add-clause", variant="default"
                    )
                    btn_add_clause.tooltip = "Append another condition clause"
                    yield btn_add_clause
                    btn_rem_clause = Button(
                        "Remove Clause", id="btn-remove-clause", variant="default"
                    )
                    btn_rem_clause.tooltip = "Remove the last condition clause"
                    yield btn_rem_clause

            yield Label("Target Folder:", classes="field-label")
            inp_target = Input(
                value=self.initial_target,
                placeholder="e.g. Finances/Invoices (optional for trash / duplicate policies)",
                id="input-rule-target",
            )
            inp_target.tooltip = "Relative destination folder inside the active workspace (leave blank for trash or duplicate policies)"
            self.watch(
                inp_target, "value", self._on_watched_draft_field, init=False
            )
            yield inp_target

            yield Label("Rename Template (optional):", classes="field-label")
            inp_rename = Input(
                value=self.initial_rename_pattern,
                placeholder="e.g. {date}_{stem}{extension}",
                id="input-rule-rename-pattern",
            )
            inp_rename.tooltip = (
                "Optional filename rename template (e.g. {date}_{stem}{extension})"
            )
            yield inp_rename

            with Vertical(id="policy-fields-container", classes=pol_cls):
                yield Label("Policy Type:", classes="field-label")
                sel_ptype = Select(
                    policy_types,
                    value=self.initial_policy_type,
                    allow_blank=False,
                    id="select-policy-type",
                )
                sel_ptype.tooltip = "Select policy evaluation strategy"
                self.watch(
                    sel_ptype, "value", self._on_watched_draft_field, init=False
                )
                yield sel_ptype

                yield Label("Priority (integer):", classes="field-label")
                inp_prio = Input(
                    value=str(self.initial_priority),
                    placeholder="e.g. 10 (higher runs first)",
                    id="input-policy-priority",
                )
                inp_prio.tooltip = (
                    "Integer priority; higher-priority policies evaluate first"
                )
                self.watch(
                    inp_prio, "value", self._on_watched_draft_field, init=False
                )
                yield inp_prio

                yield Label("Policy Action (optional):", classes="field-label")
                inp_action = Input(
                    value=self.initial_action,
                    placeholder="archive, retain, quarantine, redact, unarchive, trash",
                    id="input-policy-action",
                )
                inp_action.tooltip = "Optional policy action (archive, retain, quarantine, redact, unarchive, trash)"
                self.watch(
                    inp_action, "value", self._on_watched_draft_field, init=False
                )
                yield inp_action

                chk_halt = Checkbox(
                    "Halting (stop evaluating lower-priority rules on match)",
                    value=self.initial_halting,
                    id="chk-policy-halting",
                )
                chk_halt.tooltip = (
                    "Stop evaluating lower-priority policies when this rule matches"
                )
                self.watch(
                    chk_halt, "value", self._on_watched_draft_field, init=False
                )
                yield chk_halt

            with Vertical(id="rule-preview-box", classes="preview-box"):
                yield Label("Sample File Preview:", classes="field-label")
                sel_sample = Select(
                    sample_options,
                    allow_blank=True,
                    prompt="Select workspace sample file...",
                    id="select-sample-file",
                )
                sel_sample.tooltip = "Choose a workspace file to live-test this rule without moving files"
                self.watch(
                    sel_sample, "value", self._on_watched_draft_field, init=False
                )
                yield sel_sample
                total_files = len(self._workspace_items)
                initial_preview_msg = (
                    f"Select a sample file or enter a pattern ({total_files} workspace file(s))."
                    if total_files > 0
                    else "No active workspace folder loaded for sample preview."
                )
                yield Label(
                    initial_preview_msg,
                    classes="preview-status",
                    id="lbl-rule-preview",
                )
            yield Label("", classes="error-label", id="lbl-rule-error")
        with Horizontal(classes="button-row"):
            btn_cancel = Button(
                "Cancel", id="btn-cancel-edit-rule", variant="default"
            )
            btn_cancel.tooltip = "Cancel and discard rule changes"
            yield btn_cancel
            btn_save = Button("Save Rule", id="btn-save-rule", variant="primary")
            btn_save.tooltip = "Validate rule conditions and target path, then save"
            yield btn_save

on_mount()

Focus initial input on mount, seed compound clause if needed, and load workspace sample file options.

Source code in app/ui/modals/rules.py
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
def on_mount(self) -> None:
    """Focus initial input on mount, seed compound clause if needed, and load workspace sample file options."""
    super().on_mount()
    try:
        clauses_list = self.query_one("#compound-clauses-list", Vertical)
        if (
            self.initial_match_mode != "simple"
            and not list(clauses_list.query(_PolicyClauseRow))
            and not self._nested_groups
        ):
            self.add_clause_row()
    except NoMatches:
        return

    if not self._sample_options_seeded:
        self._workspace_items = self._discover_workspace_files()
        with contextlib.suppress(NoMatches):
            sel_sample = self.query_one("#select-sample-file", Select)
            options = [
                (rel_p, item_id) for item_id, _s, rel_p in self._workspace_items
            ]
            sel_sample.set_options(options)
            self._sample_options_seeded = True

    self._mounted_ready = True
    self._refresh_preview(announce_change=False)
    if self.focused is None:
        with contextlib.suppress(NoMatches):
            self.query_one("#input-rule-pattern", Input).focus()

remove_last_clause_row()

Remove the last mounted condition clause row if more than zero exist.

Source code in app/ui/modals/rules.py
2760
2761
2762
2763
2764
2765
def remove_last_clause_row(self) -> None:
    """Remove the last mounted condition clause row if more than zero exist."""
    clauses_list = self.query_one("#compound-clauses-list", Vertical)
    rows = list(clauses_list.query(_PolicyClauseRow))
    if rows:
        rows[-1].remove()

RuleImportModal

Bases: _CancelToCloseMixin, ResponsiveModalScreen[Any | None]

Modal screen for selecting, inspecting, and merging external rules (Hazel, DropIt & TagSpaces).

Source code in app/ui/modals/rules.py
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
class RuleImportModal(_CancelToCloseMixin, ResponsiveModalScreen[Any | None]):
    """Modal screen for selecting, inspecting, and merging external rules (Hazel, DropIt & TagSpaces)."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-box {
        max-width: 88;
        min-width: 35;
        max-height: 92%;
    }
    .input-row {
        width: 100%;
        margin-top: 1;
        margin-bottom: 1;
        height: auto;
        align: left middle;
    }
    #input-rule-file-path {
        width: 1fr;
        margin-right: 1;
    }
    #btn-browse-rule-file {
        width: auto;
        min-width: 11;
        margin-right: 1;
    }
    #btn-parse-rule-file {
        width: auto;
        min-width: 12;
    }
    #chk-import-disabled {
        margin-top: 0;
        margin-bottom: 0;
    }
    #select-bulk-conflict-strategy {
        width: 1fr;
    }
    .preview-card {
        margin-top: 1;
        margin-bottom: 1;
        padding: 0 1;
        border: solid $accent;
        height: auto;
    }
    #dt-imported-keywords, #dt-imported-policies, #dt-rule-conflicts {
        width: 100%;
        height: auto;
        min-height: 5;
        max-height: 10;
    }
    .warning-text {
        color: $warning;
        margin-top: 1;
    }
    .status-text {
        color: $accent;
        margin-top: 1;
        text-style: bold;
    }
    .button-row Button {
        min-width: 10;
        margin-left: 1;
    }
    Button:focus, Input:focus, Checkbox:focus {
        border: heavy $accent;
        text-style: bold;
    }
    RuleImportModal {
        &.compact .modal-title {
            margin-bottom: 0;
        }
        &.compact .input-row {
            margin-top: 0;
            margin-bottom: 0;
        }
        &.compact .preview-card {
            margin-top: 0;
            margin-bottom: 0;
        }
        &.compact .status-text, &.compact .warning-text {
            margin-top: 0;
        }
        &.compact .button-row {
            margin-top: 0;
        }
        &.narrow #btn-browse-rule-file,
        &.narrow #btn-parse-rule-file {
            min-width: 0;
            padding: 0 1;
        }
        &.narrow .button-row Button {
            min-width: 0;
            padding: 0 1;
        }
    }
    """

    def __init__(self, settings: Any):
        super().__init__()
        self.settings = settings
        self.current_result: Any | None = None
        self.conflicts: list[Any] = []
        self.conflict_resolutions: dict[str, str] = {}
        self.import_disabled: bool = True
        self._auto_setting_import_disabled: bool = False

    def compose(self) -> ComposeResult:
        """Compose rule import modal children."""
        with ModalBox(classes="modal-box"):
            yield Heading(
                "Import External Rules",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            with Vertical(classes="modal-body"):
                yield Label(
                    "Select a Hazel (.hazelrules/.plist), DropIt (.ini/.xml/.json/.dropit), TagSpaces (taggroup.json), or Sortify JSON file to import:"
                )

                with Horizontal(classes="input-row"):
                    yield Input(
                        placeholder="/path/to/rules.hazelrules, profile.ini/xml/json/dropit, or taggroup.json",
                        id="input-rule-file-path",
                    )
                    btn_browse = Button(
                        "Browse...", id="btn-browse-rule-file", variant="default"
                    )
                    btn_browse.tooltip = "Select a rule file (.hazelrules, .plist, .ini, .xml, .json, .dropit) using the native file dialog"
                    yield btn_browse
                    btn_parse = Button(
                        "Parse File", id="btn-parse-rule-file", variant="primary"
                    )
                    btn_parse.tooltip = "Parse selected rule file and display preview"
                    yield btn_parse

                chk_disabled = Checkbox(
                    "Import new rules disabled for review",
                    value=True,
                    id="chk-import-disabled",
                )
                chk_disabled.tooltip = (
                    "Stage newly imported rules disabled until reviewed and enabled"
                )
                yield chk_disabled

                yield Label(
                    "Browse or enter a file path and click 'Parse File' to preview extracted rules.",
                    id="lbl-import-status",
                    classes="status-text",
                )

                with Vertical(id="container-rule-preview", classes="preview-card"):
                    yield Label(
                        "Imported Keywords:",
                        classes="status-text",
                        id="lbl-imported-keywords",
                    )
                    yield DataTable(id="dt-imported-keywords")
                    yield Label(
                        "Imported Policies:",
                        classes="status-text",
                        id="lbl-imported-policies",
                    )
                    yield DataTable(id="dt-imported-policies")

                    with Vertical(id="container-conflicts-section"):
                        yield Label(
                            "⚠️ Detected Rule Conflicts:",
                            classes="warning-text",
                            id="lbl-conflict-header",
                        )
                        with Horizontal(classes="input-row", id="row-bulk-strategy"):
                            yield Label("Bulk Resolution Strategy: ")
                            yield Select(
                                [
                                    ("Keep Existing (Skip Conflicts)", "keep_existing"),
                                    ("Overwrite Existing Rules", "overwrite"),
                                    ("Skip Conflicting Rules", "skip_conflicting"),
                                ],
                                value="keep_existing",
                                id="select-bulk-conflict-strategy",
                                allow_blank=False,
                            )
                        yield Label(
                            "Conflict Resolution Table (Click or press Space/Enter on a row to cycle individual resolution):"
                        )
                        yield DataTable(id="dt-rule-conflicts")

                    yield Vertical(id="container-import-warnings")

            with Horizontal(classes="button-row"):
                btn_close = Button("Cancel", id="btn-close-importer", variant="default")
                btn_close.tooltip = "Close import dialog"
                yield btn_close

                btn_merge = Button(
                    "Merge Rules into Settings",
                    id="btn-merge-imported-rules",
                    variant="primary",
                    disabled=True,
                )
                btn_merge.tooltip = "Safely merge extracted rules into settings according to resolution choices"
                yield btn_merge

    def on_mount(self) -> None:
        """Focus initial input field on mount and set up preview tables."""
        super().on_mount()
        try:
            self.query_one("#input-rule-file-path", Input).focus()
            dt_kw = self.query_one("#dt-imported-keywords", DataTable)
            dt_kw.add_columns("Keyword", "Target Path")

            dt_pol = self.query_one("#dt-imported-policies", DataTable)
            dt_pol.add_columns(
                "Type", "Expression / Pattern", "Target Path", "Priority"
            )

            dt_conf = self.query_one("#dt-rule-conflicts", DataTable)
            dt_conf.add_columns(
                "Rule Type",
                "Identifier",
                "Existing Path",
                "Imported Path",
                "Resolution",
            )
        except Exception:
            pass
        self.announce("Opened external rule importer modal.")

    def _format_resolution_label(self, strategy: str) -> str:
        """Format resolution strategy code for table display."""
        if strategy == "overwrite":
            return "Overwrite"
        elif strategy == "skip_conflicting":
            return "Skip Conflicting"
        return "Keep Existing"

    def _rebuild_conflict_table(self, *, bulk_strategy: str | None = None) -> None:
        """Optionally apply a bulk strategy and rebuild the conflict resolution table."""
        if bulk_strategy is not None:
            for conflict in self.conflicts:
                conflict.resolution = bulk_strategy
                self.conflict_resolutions[conflict.identifier] = bulk_strategy

        try:
            dt_conf = self.query_one("#dt-rule-conflicts", DataTable)
            dt_conf.clear()
            for conflict in self.conflicts:
                res_strategy = self.conflict_resolutions.get(
                    conflict.identifier, conflict.resolution
                )
                dt_conf.add_row(
                    conflict.rule_type.capitalize(),
                    conflict.identifier,
                    conflict.existing_target,
                    conflict.imported_target,
                    self._format_resolution_label(res_strategy),
                    key=conflict.identifier,
                )
        except Exception:
            pass

    @on(Checkbox.Changed, "#chk-import-disabled")
    def _on_import_disabled_changed(self, event: Checkbox.Changed) -> None:
        """Toggle whether newly imported rules are staged disabled for review."""
        self.import_disabled = bool(event.value)
        if self._auto_setting_import_disabled:
            return
        mode_text = (
            "disabled for review" if self.import_disabled else "enabled immediately"
        )
        self.announce(f"New imported rules will be staged {mode_text}.")

    @on(Button.Pressed, "#btn-browse-rule-file")
    def action_browse_file(self) -> None:
        """Open native OS file picker to select an external rule package."""
        initial_dir: str | None = None
        try:
            raw_val = self.query_one("#input-rule-file-path", Input).value.strip()
            if raw_val:
                cand = Path(raw_val).expanduser()
                parent = cand if cand.is_dir() else cand.parent
                if parent.exists():
                    initial_dir = str(parent)
        except Exception:
            pass
        if not initial_dir:
            base_dir = getattr(self.app, "base_dir", None)
            if base_dir and Path(str(base_dir)).exists():
                initial_dir = str(base_dir)
        self._browse_rule_file_worker(initial_dir)

    @work(thread=True)
    def _browse_rule_file_worker(self, initial_dir: str | None) -> None:
        """Launch native file picker on a worker thread without blocking the TUI."""
        from app.core.native_dialog import (
            RULE_IMPORT_EXTENSIONS,
            NativeDialogError,
            select_native_file,
        )

        try:
            selected = select_native_file(
                initial_dir=initial_dir,
                title="Select Rule File to Import",
                extensions=RULE_IMPORT_EXTENSIONS,
            )
        except NativeDialogError as exc:
            self.app.call_from_thread(self._handle_browse_fallback, str(exc))
            return
        except Exception as exc:
            self.app.call_from_thread(self._handle_browse_fallback, str(exc))
            return

        if selected:
            self.app.call_from_thread(self._apply_selected_rule_file, selected)
        else:
            self.app.call_from_thread(self.announce, "Rule file selection cancelled.")

    def _apply_selected_rule_file(self, selected_path: str) -> None:
        """Populate selected rule file path into input and parse preview."""
        try:
            inp = self.query_one("#input-rule-file-path", Input)
            inp.value = selected_path
        except Exception:
            return
        self.announce(f"Selected rule file: {selected_path}")
        self.action_parse_file()

    def _handle_browse_fallback(self, reason: str) -> None:
        """Fall back to manual path input when native file dialog is unavailable."""
        msg = (
            f"Native file picker unavailable ({reason}). "
            "Please enter the rule file path manually."
        )
        try:
            self.query_one("#lbl-import-status", Label).update(msg)
            self.query_one("#input-rule-file-path", Input).focus()
        except Exception:
            pass
        self.announce(msg)

    @on(Button.Pressed, "#btn-parse-rule-file")
    @on(Input.Submitted, "#input-rule-file-path")
    def action_parse_file(self) -> None:
        """Parse external rule package and render preview tables."""
        path_str = self.query_one("#input-rule-file-path", Input).value.strip()
        lbl_status = self.query_one("#lbl-import-status", Label)

        if not path_str:
            lbl_status.update("Please enter a valid rule file path.")
            self.announce("Please enter a valid rule file path.")
            return

        p = Path(path_str)
        if not p.exists():
            lbl_status.update(f"File not found: '{path_str}'")
            self.announce(f"File not found: '{path_str}'")
            return

        try:
            from app.core.rule_importers import RuleConflictAnalyzer, get_rule_importer

            importer = get_rule_importer(p)
            self.current_result = importer.parse_file(p)
            self.conflicts = RuleConflictAnalyzer.analyze(
                self.current_result, self.settings
            )
            self.conflict_resolutions = {
                c.identifier: c.resolution for c in self.conflicts
            }
        except Exception as exc:
            lbl_status.update(f"Error parsing rule package: {exc}")
            self.announce(f"Error parsing rule package: {exc}")
            return

        res = self.current_result
        preserve_native = bool(getattr(res, "preserve_states", False))
        desired_chk = not preserve_native
        for chk in self.query("#chk-import-disabled").results(Checkbox):
            if chk.value != desired_chk:
                self._auto_setting_import_disabled = True
                try:
                    chk.value = desired_chk
                finally:
                    self._auto_setting_import_disabled = False
            self.import_disabled = desired_chk

        dt_kw = self.query_one("#dt-imported-keywords", DataTable)
        dt_pol = self.query_one("#dt-imported-policies", DataTable)
        btn_merge = self.query_one("#btn-merge-imported-rules", Button)

        dt_kw.clear()
        dt_pol.clear()

        for kw, target_dir in res.keyword_rules.items():
            dt_kw.add_row(kw, target_dir)
        for kw, target_dir in (
            getattr(res, "disabled_keyword_rules", {}) or {}
        ).items():
            dt_kw.add_row(f"{kw} [disabled]", target_dir)
        for kw, target_dir in (getattr(res, "learned_rules", {}) or {}).items():
            dt_kw.add_row(f"{kw} [learned]", target_dir)
        for kw, target_dir in (
            getattr(res, "disabled_learned_rules", {}) or {}
        ).items():
            dt_kw.add_row(f"{kw} [learned, disabled]", target_dir)

        for pol in res.policies:
            pol_type_label = _format_policy_type_badge(pol)
            dt_pol.add_row(
                pol_type_label,
                pol.get("expression", ""),
                pol.get("target_path", ""),
                str(pol.get("priority", 75)),
            )

        bulk_strategy = "keep_existing"
        try:
            val = self.query_one("#select-bulk-conflict-strategy", Select).value
            if not _is_select_blank(val):
                bulk_strategy = str(val)
        except Exception:
            pass

        self._rebuild_conflict_table(bulk_strategy=bulk_strategy)

        warn_container = self.query_one("#container-import-warnings", Vertical)
        warn_container.remove_children()
        for warn in res.warnings:
            warn_container.mount(Label(f"⚠️ {warn}", classes="warning-text"))

        extra_count = (
            len(getattr(res, "disabled_keyword_rules", {}) or {})
            + len(getattr(res, "learned_rules", {}) or {})
            + len(getattr(res, "disabled_learned_rules", {}) or {})
            + len(getattr(res, "extension_categories", {}) or {})
            + len(getattr(res, "folder_rule_scopes", {}) or {})
        )
        total_rules = len(res.keyword_rules) + len(res.policies) + extra_count
        lbl_status.update(
            f"Parsed {res.source_format}: {len(res.keyword_rules)} keyword rules, "
            f"{len(res.policies)} policies, {len(self.conflicts)} conflict(s), "
            f"{len(res.warnings)} warning(s)."
        )

        if total_rules > 0:
            btn_merge.disabled = False
            btn_merge.focus()
        else:
            btn_merge.disabled = True

        self.announce(
            f"Parsed {res.source_format}: {total_rules} rules extracted ({len(self.conflicts)} conflicts)."
        )

    @on(Select.Changed, "#select-bulk-conflict-strategy")
    def _on_bulk_strategy_changed(self, event: Select.Changed) -> None:
        """Apply bulk conflict resolution strategy across all detected conflicts."""
        if _is_select_blank(event.value):
            return
        new_strategy = str(event.value)
        self._rebuild_conflict_table(bulk_strategy=new_strategy)
        self.announce(
            f"Updated bulk resolution strategy to: {self._format_resolution_label(new_strategy)}"
        )

    @on(DataTable.RowSelected, "#dt-rule-conflicts")
    @on(DataTable.CellSelected, "#dt-rule-conflicts")
    def _on_conflict_selected(
        self, event: DataTable.RowSelected | DataTable.CellSelected | Any
    ) -> None:
        """Cycle resolution strategy for the selected conflict row."""
        row_key = None
        rk_attr = getattr(event, "row_key", None)
        if rk_attr is not None and getattr(rk_attr, "value", None):
            row_key = str(rk_attr.value)
        elif (coord := getattr(event, "coordinate", None)) is not None:
            try:
                dt_conf = self.query_one("#dt-rule-conflicts", DataTable)
                rk = dt_conf.coordinate_to_cell_key(coord).row_key
                if rk and rk.value:
                    row_key = str(rk.value)
            except Exception:
                pass

        if not row_key:
            return

        conflict = next((c for c in self.conflicts if c.identifier == row_key), None)
        if not conflict:
            return

        cycle_map = {
            "keep_existing": "overwrite",
            "overwrite": "skip_conflicting",
            "skip_conflicting": "keep_existing",
        }
        current_res = self.conflict_resolutions.get(
            conflict.identifier, conflict.resolution
        )
        new_res = cycle_map.get(current_res, "keep_existing")

        conflict.resolution = new_res
        self.conflict_resolutions[conflict.identifier] = new_res

        self._rebuild_conflict_table()

        self.announce(
            f"Set resolution for '{conflict.identifier}' to {self._format_resolution_label(new_res)}."
        )

    @on(Button.Pressed, "#btn-merge-imported-rules")
    def action_merge_rules(self) -> None:
        """Merge parsed rules into settings and close modal."""
        if not self.current_result:
            try:
                self.dismiss(None)
            except Exception:
                pass
            return

        bulk_strategy = "keep_existing"
        try:
            val = self.query_one("#select-bulk-conflict-strategy", Select).value
            if not _is_select_blank(val):
                bulk_strategy = str(val)
        except Exception:
            pass

        stage_disabled = self.import_disabled
        try:
            stage_disabled = bool(
                self.query_one("#chk-import-disabled", Checkbox).value
            )
            self.import_disabled = stage_disabled
        except Exception:
            pass

        preserve_native = bool(getattr(self.current_result, "preserve_states", False))
        effective_import_disabled: bool | None
        if stage_disabled:
            effective_import_disabled = True
        elif preserve_native:
            effective_import_disabled = None
        else:
            effective_import_disabled = False

        try:
            new_kw, new_pol = self.current_result.merge_into_settings(
                self.settings,
                resolutions=self.conflict_resolutions,
                default_strategy=bulk_strategy,
                import_disabled=effective_import_disabled,
            )
        except Exception as exc:
            err_msg = f"Failed to save imported rules: {exc}"
            self.announce(err_msg)
            try:
                from app.ui.notifications import notify

                notify(err_msg, type="error")
            except Exception:
                pass
            try:
                if hasattr(self.app, "notify"):
                    self.app.notify(err_msg, severity="error")
            except Exception:
                pass
            return

        dis_kw = getattr(self.settings, "DISABLED_KEYWORD_RULES", {}) or {}
        if stage_disabled:
            msg = (
                f"Merged imported rules (new rules staged disabled for review): "
                f"{len(new_kw)} active keyword(s), {len(dis_kw)} disabled keyword(s), "
                f"and {len(new_pol)} policies."
            )
        else:
            msg = (
                f"Merged imported rules: {len(new_kw)} keyword rules and "
                f"{len(new_pol)} policies."
            )
        self.announce(msg)
        try:
            if hasattr(self.app, "notify"):
                self.app.notify(msg)
        except Exception:
            pass

        try:
            self.dismiss(self.current_result)
        except Exception:
            pass

    @on(Button.Pressed, "#btn-close-importer")
    def action_close(self) -> None:
        """Close import dialog."""
        self.announce("Closed external rule importer modal.")
        self.dismiss(None)

action_browse_file()

Open native OS file picker to select an external rule package.

Source code in app/ui/modals/rules.py
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
@on(Button.Pressed, "#btn-browse-rule-file")
def action_browse_file(self) -> None:
    """Open native OS file picker to select an external rule package."""
    initial_dir: str | None = None
    try:
        raw_val = self.query_one("#input-rule-file-path", Input).value.strip()
        if raw_val:
            cand = Path(raw_val).expanduser()
            parent = cand if cand.is_dir() else cand.parent
            if parent.exists():
                initial_dir = str(parent)
    except Exception:
        pass
    if not initial_dir:
        base_dir = getattr(self.app, "base_dir", None)
        if base_dir and Path(str(base_dir)).exists():
            initial_dir = str(base_dir)
    self._browse_rule_file_worker(initial_dir)

action_close()

Close import dialog.

Source code in app/ui/modals/rules.py
1504
1505
1506
1507
1508
@on(Button.Pressed, "#btn-close-importer")
def action_close(self) -> None:
    """Close import dialog."""
    self.announce("Closed external rule importer modal.")
    self.dismiss(None)

action_merge_rules()

Merge parsed rules into settings and close modal.

Source code in app/ui/modals/rules.py
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
@on(Button.Pressed, "#btn-merge-imported-rules")
def action_merge_rules(self) -> None:
    """Merge parsed rules into settings and close modal."""
    if not self.current_result:
        try:
            self.dismiss(None)
        except Exception:
            pass
        return

    bulk_strategy = "keep_existing"
    try:
        val = self.query_one("#select-bulk-conflict-strategy", Select).value
        if not _is_select_blank(val):
            bulk_strategy = str(val)
    except Exception:
        pass

    stage_disabled = self.import_disabled
    try:
        stage_disabled = bool(
            self.query_one("#chk-import-disabled", Checkbox).value
        )
        self.import_disabled = stage_disabled
    except Exception:
        pass

    preserve_native = bool(getattr(self.current_result, "preserve_states", False))
    effective_import_disabled: bool | None
    if stage_disabled:
        effective_import_disabled = True
    elif preserve_native:
        effective_import_disabled = None
    else:
        effective_import_disabled = False

    try:
        new_kw, new_pol = self.current_result.merge_into_settings(
            self.settings,
            resolutions=self.conflict_resolutions,
            default_strategy=bulk_strategy,
            import_disabled=effective_import_disabled,
        )
    except Exception as exc:
        err_msg = f"Failed to save imported rules: {exc}"
        self.announce(err_msg)
        try:
            from app.ui.notifications import notify

            notify(err_msg, type="error")
        except Exception:
            pass
        try:
            if hasattr(self.app, "notify"):
                self.app.notify(err_msg, severity="error")
        except Exception:
            pass
        return

    dis_kw = getattr(self.settings, "DISABLED_KEYWORD_RULES", {}) or {}
    if stage_disabled:
        msg = (
            f"Merged imported rules (new rules staged disabled for review): "
            f"{len(new_kw)} active keyword(s), {len(dis_kw)} disabled keyword(s), "
            f"and {len(new_pol)} policies."
        )
    else:
        msg = (
            f"Merged imported rules: {len(new_kw)} keyword rules and "
            f"{len(new_pol)} policies."
        )
    self.announce(msg)
    try:
        if hasattr(self.app, "notify"):
            self.app.notify(msg)
    except Exception:
        pass

    try:
        self.dismiss(self.current_result)
    except Exception:
        pass

action_parse_file()

Parse external rule package and render preview tables.

Source code in app/ui/modals/rules.py
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
@on(Button.Pressed, "#btn-parse-rule-file")
@on(Input.Submitted, "#input-rule-file-path")
def action_parse_file(self) -> None:
    """Parse external rule package and render preview tables."""
    path_str = self.query_one("#input-rule-file-path", Input).value.strip()
    lbl_status = self.query_one("#lbl-import-status", Label)

    if not path_str:
        lbl_status.update("Please enter a valid rule file path.")
        self.announce("Please enter a valid rule file path.")
        return

    p = Path(path_str)
    if not p.exists():
        lbl_status.update(f"File not found: '{path_str}'")
        self.announce(f"File not found: '{path_str}'")
        return

    try:
        from app.core.rule_importers import RuleConflictAnalyzer, get_rule_importer

        importer = get_rule_importer(p)
        self.current_result = importer.parse_file(p)
        self.conflicts = RuleConflictAnalyzer.analyze(
            self.current_result, self.settings
        )
        self.conflict_resolutions = {
            c.identifier: c.resolution for c in self.conflicts
        }
    except Exception as exc:
        lbl_status.update(f"Error parsing rule package: {exc}")
        self.announce(f"Error parsing rule package: {exc}")
        return

    res = self.current_result
    preserve_native = bool(getattr(res, "preserve_states", False))
    desired_chk = not preserve_native
    for chk in self.query("#chk-import-disabled").results(Checkbox):
        if chk.value != desired_chk:
            self._auto_setting_import_disabled = True
            try:
                chk.value = desired_chk
            finally:
                self._auto_setting_import_disabled = False
        self.import_disabled = desired_chk

    dt_kw = self.query_one("#dt-imported-keywords", DataTable)
    dt_pol = self.query_one("#dt-imported-policies", DataTable)
    btn_merge = self.query_one("#btn-merge-imported-rules", Button)

    dt_kw.clear()
    dt_pol.clear()

    for kw, target_dir in res.keyword_rules.items():
        dt_kw.add_row(kw, target_dir)
    for kw, target_dir in (
        getattr(res, "disabled_keyword_rules", {}) or {}
    ).items():
        dt_kw.add_row(f"{kw} [disabled]", target_dir)
    for kw, target_dir in (getattr(res, "learned_rules", {}) or {}).items():
        dt_kw.add_row(f"{kw} [learned]", target_dir)
    for kw, target_dir in (
        getattr(res, "disabled_learned_rules", {}) or {}
    ).items():
        dt_kw.add_row(f"{kw} [learned, disabled]", target_dir)

    for pol in res.policies:
        pol_type_label = _format_policy_type_badge(pol)
        dt_pol.add_row(
            pol_type_label,
            pol.get("expression", ""),
            pol.get("target_path", ""),
            str(pol.get("priority", 75)),
        )

    bulk_strategy = "keep_existing"
    try:
        val = self.query_one("#select-bulk-conflict-strategy", Select).value
        if not _is_select_blank(val):
            bulk_strategy = str(val)
    except Exception:
        pass

    self._rebuild_conflict_table(bulk_strategy=bulk_strategy)

    warn_container = self.query_one("#container-import-warnings", Vertical)
    warn_container.remove_children()
    for warn in res.warnings:
        warn_container.mount(Label(f"⚠️ {warn}", classes="warning-text"))

    extra_count = (
        len(getattr(res, "disabled_keyword_rules", {}) or {})
        + len(getattr(res, "learned_rules", {}) or {})
        + len(getattr(res, "disabled_learned_rules", {}) or {})
        + len(getattr(res, "extension_categories", {}) or {})
        + len(getattr(res, "folder_rule_scopes", {}) or {})
    )
    total_rules = len(res.keyword_rules) + len(res.policies) + extra_count
    lbl_status.update(
        f"Parsed {res.source_format}: {len(res.keyword_rules)} keyword rules, "
        f"{len(res.policies)} policies, {len(self.conflicts)} conflict(s), "
        f"{len(res.warnings)} warning(s)."
    )

    if total_rules > 0:
        btn_merge.disabled = False
        btn_merge.focus()
    else:
        btn_merge.disabled = True

    self.announce(
        f"Parsed {res.source_format}: {total_rules} rules extracted ({len(self.conflicts)} conflicts)."
    )

compose()

Compose rule import modal children.

Source code in app/ui/modals/rules.py
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
def compose(self) -> ComposeResult:
    """Compose rule import modal children."""
    with ModalBox(classes="modal-box"):
        yield Heading(
            "Import External Rules",
            level=1,
            classes="modal-title",
            id="modal-title",
        )
        with Vertical(classes="modal-body"):
            yield Label(
                "Select a Hazel (.hazelrules/.plist), DropIt (.ini/.xml/.json/.dropit), TagSpaces (taggroup.json), or Sortify JSON file to import:"
            )

            with Horizontal(classes="input-row"):
                yield Input(
                    placeholder="/path/to/rules.hazelrules, profile.ini/xml/json/dropit, or taggroup.json",
                    id="input-rule-file-path",
                )
                btn_browse = Button(
                    "Browse...", id="btn-browse-rule-file", variant="default"
                )
                btn_browse.tooltip = "Select a rule file (.hazelrules, .plist, .ini, .xml, .json, .dropit) using the native file dialog"
                yield btn_browse
                btn_parse = Button(
                    "Parse File", id="btn-parse-rule-file", variant="primary"
                )
                btn_parse.tooltip = "Parse selected rule file and display preview"
                yield btn_parse

            chk_disabled = Checkbox(
                "Import new rules disabled for review",
                value=True,
                id="chk-import-disabled",
            )
            chk_disabled.tooltip = (
                "Stage newly imported rules disabled until reviewed and enabled"
            )
            yield chk_disabled

            yield Label(
                "Browse or enter a file path and click 'Parse File' to preview extracted rules.",
                id="lbl-import-status",
                classes="status-text",
            )

            with Vertical(id="container-rule-preview", classes="preview-card"):
                yield Label(
                    "Imported Keywords:",
                    classes="status-text",
                    id="lbl-imported-keywords",
                )
                yield DataTable(id="dt-imported-keywords")
                yield Label(
                    "Imported Policies:",
                    classes="status-text",
                    id="lbl-imported-policies",
                )
                yield DataTable(id="dt-imported-policies")

                with Vertical(id="container-conflicts-section"):
                    yield Label(
                        "⚠️ Detected Rule Conflicts:",
                        classes="warning-text",
                        id="lbl-conflict-header",
                    )
                    with Horizontal(classes="input-row", id="row-bulk-strategy"):
                        yield Label("Bulk Resolution Strategy: ")
                        yield Select(
                            [
                                ("Keep Existing (Skip Conflicts)", "keep_existing"),
                                ("Overwrite Existing Rules", "overwrite"),
                                ("Skip Conflicting Rules", "skip_conflicting"),
                            ],
                            value="keep_existing",
                            id="select-bulk-conflict-strategy",
                            allow_blank=False,
                        )
                    yield Label(
                        "Conflict Resolution Table (Click or press Space/Enter on a row to cycle individual resolution):"
                    )
                    yield DataTable(id="dt-rule-conflicts")

                yield Vertical(id="container-import-warnings")

        with Horizontal(classes="button-row"):
            btn_close = Button("Cancel", id="btn-close-importer", variant="default")
            btn_close.tooltip = "Close import dialog"
            yield btn_close

            btn_merge = Button(
                "Merge Rules into Settings",
                id="btn-merge-imported-rules",
                variant="primary",
                disabled=True,
            )
            btn_merge.tooltip = "Safely merge extracted rules into settings according to resolution choices"
            yield btn_merge

on_mount()

Focus initial input field on mount and set up preview tables.

Source code in app/ui/modals/rules.py
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
def on_mount(self) -> None:
    """Focus initial input field on mount and set up preview tables."""
    super().on_mount()
    try:
        self.query_one("#input-rule-file-path", Input).focus()
        dt_kw = self.query_one("#dt-imported-keywords", DataTable)
        dt_kw.add_columns("Keyword", "Target Path")

        dt_pol = self.query_one("#dt-imported-policies", DataTable)
        dt_pol.add_columns(
            "Type", "Expression / Pattern", "Target Path", "Priority"
        )

        dt_conf = self.query_one("#dt-rule-conflicts", DataTable)
        dt_conf.add_columns(
            "Rule Type",
            "Identifier",
            "Existing Path",
            "Imported Path",
            "Resolution",
        )
    except Exception:
        pass
    self.announce("Opened external rule importer modal.")

TemplateGalleryModal

Bases: _CancelToCloseMixin, ResponsiveModalScreen[None]

Split-pane modal screen for inspecting, staging, and applying starter rule template packs.

Source code in app/ui/modals/rules.py
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
class TemplateGalleryModal(_CancelToCloseMixin, ResponsiveModalScreen[None]):
    """Split-pane modal screen for inspecting, staging, and applying starter rule template packs."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-box {
        width: 96%;
        max-width: 124;
        max-height: 92%;
    }
    .gallery-header-row {
        width: 100%;
        height: auto;
        margin-bottom: 0;
    }
    .gallery-scope-badge {
        width: 1fr;
        color: $accent;
        text-style: bold;
    }
    .gallery-staging-badge {
        width: auto;
        color: $success;
        text-style: bold;
    }
    #chk-gallery-stage-disabled {
        height: auto;
        border: none;
        padding: 0;
        margin-top: 0;
        margin-bottom: 0;
    }
    #chk-gallery-stage-disabled:focus {
        border: none;
        background: $boost;
        color: $accent;
        text-style: bold;
    }
    .gallery-split-panes {
        width: 100%;
        height: auto;
        margin-top: 1;
    }
    .gallery-packs-pane {
        width: 35%;
        height: auto;
        max-height: 16;
        overflow-y: auto;
        padding-right: 1;
        border-right: solid $primary;
    }
    .gallery-preview-pane {
        width: 65%;
        height: auto;
        padding-left: 1;
    }
    .pane-header {
        color: $accent;
        text-style: bold;
        margin-bottom: 0;
    }
    .template-card {
        margin-top: 0;
        margin-bottom: 0;
        padding: 0;
        height: auto;
    }
    .template-card-top {
        width: 100%;
        height: auto;
    }
    .template-card-top Checkbox {
        width: 1fr;
        height: auto;
        border: none;
        padding: 0;
        margin: 0;
    }
    .template-card-top Checkbox:focus {
        border: none;
        background: $boost;
        color: $accent;
        text-style: bold;
    }
    .pack-badge {
        width: auto;
        margin-left: 1;
        text-style: bold;
    }
    .badge-active {
        color: $success;
    }
    .badge-staged {
        color: $warning;
    }
    .badge-partial {
        color: $accent;
    }
    .badge-none {
        color: $text-muted;
    }
    .template-desc {
        display: none;
    }
    .gallery-summary {
        color: $text-muted;
        margin-top: 1;
    }
    #dt-template-preview {
        width: 100%;
        height: 12;
        min-height: 6;
        border: solid $accent;
    }
    .gallery-conflict-bar {
        color: $text-muted;
        margin-top: 0;
    }
    .gallery-conflict-warning {
        color: $warning;
        text-style: bold;
    }
    .button-row {
        layout: grid;
        grid-size: 2;
        grid-columns: 1fr 1fr;
        grid-gutter: 0 1;
    }
    .button-row Button {
        width: 100%;
        min-width: 0;
        margin: 0;
    }
    Button:focus, Checkbox:focus, DataTable:focus {
        border: heavy $accent;
        text-style: bold;
    }
    TemplateGalleryModal {
        &.compact .modal-title {
            margin-bottom: 0;
        }
        &.compact .gallery-header-row {
            margin-bottom: 0;
        }
        &.compact .gallery-split-panes {
            margin-top: 0;
        }
        &.compact .gallery-packs-pane {
            max-height: 9;
        }
        &.compact .template-card {
            margin-top: 0;
            margin-bottom: 0;
            border: none;
            padding: 0;
        }
        &.compact .template-desc {
            display: none;
        }
        &.compact #dt-template-preview {
            height: 7;
            min-height: 6;
        }
        &.compact .button-row {
            margin-top: 0;
        }
        &.compact .button-row Button {
            height: 1;
            min-height: 1;
            border: none;
            margin-bottom: 0;
        }
        &.narrow .gallery-header-row {
            layout: vertical;
        }
        &.narrow .gallery-split-panes {
            layout: vertical;
        }
        &.narrow .gallery-packs-pane {
            width: 100%;
            max-height: 6;
            padding-right: 0;
            border-right: none;
        }
        &.narrow .gallery-preview-pane {
            width: 100%;
            padding-left: 0;
        }
        &.narrow .button-row Button {
            padding: 0;
        }
    }
    """

    def __init__(self, settings: Any, defer_rescan: bool = False):
        super().__init__()
        self.settings = settings
        self.defer_rescan = defer_rescan
        self._focused_pack_id: str | None = None
        self._last_badge_state: dict[str, tuple[str, str]] = {}
        self._last_preview_rows_sig: tuple[tuple[str, ...], ...] | None = None

    def _resolve_target_scope(self) -> tuple[Any, str]:
        """Resolve folder-scoped settings view (anchored to ``self.app.base_dir``) and display label."""
        from app.core.rule_scopes import ScopedSettingsView, resolve_scoped_settings

        if isinstance(self.settings, ScopedSettingsView):
            scope_dir = str(self.settings.folder_path or "").strip()
            return self.settings, (
                f"{scope_dir} (Folder Scope)" if scope_dir else "Folder Scope"
            )

        if self.defer_rescan:
            return self.settings, "Global Scope"

        base_dir = ""
        with contextlib.suppress(ScreenStackError, AttributeError):
            raw_base = getattr(self.app, "base_dir", None)
            if raw_base:
                base_dir = str(raw_base).strip()

        if base_dir:
            scoped = resolve_scoped_settings(
                self.settings, base_dir, fallback_to_global=True
            )
            return scoped, f"{base_dir} (Folder Scope)"

        return self.settings, "Global Scope"

    @staticmethod
    def _format_pack_badge(status: str, selected: bool) -> str:
        """Render concise status badge text without hiding installed state."""
        status_map = {
            "active": "Active",
            "staged": "Staged",
            "partial": "Partial",
            "none": "Ready",
        }
        base = status_map.get(status, "Ready")
        if selected and status == "none":
            return "[Selected]"
        if selected:
            return f"[{base} · Selected]"
        return f"[{base}]"

    def _is_stage_disabled(self) -> bool:
        """Return True when new starter rules should be staged disabled for review."""
        try:
            return bool(self.query_one("#chk-gallery-stage-disabled", Checkbox).value)
        except NoMatches:
            return True

    def _get_checked_pack_ids(self) -> list[str]:
        """Return starter template pack IDs currently checked in the gallery."""
        from app.core.rule_templates import get_starter_templates

        checked: list[str] = []
        for pack in get_starter_templates():
            with contextlib.suppress(NoMatches):
                if self.query_one(f"#chk-gallery-{pack.id}", Checkbox).value:
                    checked.append(pack.id)
        return checked

    def _get_preview_pack_ids(self) -> tuple[list[str], bool]:
        """Return ``(pack_ids_to_preview, from_checked_selection)``."""
        from app.core.rule_templates import get_starter_templates

        checked = self._get_checked_pack_ids()
        if checked:
            return checked, True

        templates = get_starter_templates()
        if self._focused_pack_id and any(
            p.id == self._focused_pack_id for p in templates
        ):
            return [self._focused_pack_id], False
        if templates:
            return [templates[0].id], False
        return [], False

    def compose(self) -> ComposeResult:
        """Compose split-pane starter template gallery children."""
        from app.core.rule_templates import (
            get_starter_template_status,
            get_starter_templates,
        )

        templates = get_starter_templates()
        target_settings, scope_label = self._resolve_target_scope()
        if templates and self._focused_pack_id is None:
            self._focused_pack_id = templates[0].id

        with ModalBox(classes="modal-box"):
            yield Heading(
                "Starter Rule Template Gallery",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            with Vertical(classes="modal-body"):
                with Horizontal(classes="gallery-header-row"):
                    yield Label(
                        f"Target Scope: {scope_label}",
                        id="lbl-gallery-scope",
                        classes="gallery-scope-badge",
                        markup=False,
                    )
                    yield Label(
                        "[SAFE STAGING MODE ACTIVE]",
                        id="lbl-gallery-staging-badge",
                        classes="gallery-staging-badge",
                        markup=False,
                    )

                chk_stage = Checkbox(
                    "Stage new rules disabled for review",
                    value=True,
                    id="chk-gallery-stage-disabled",
                )
                chk_stage.tooltip = "Stage newly applied template rules disabled until reviewed and enabled"
                self._watch_toggle_control(chk_stage, self.on_checkbox_changed)
                yield chk_stage

                with Horizontal(classes="gallery-split-panes"):
                    with Vertical(classes="gallery-packs-pane"):
                        yield Label(
                            f"STARTER PACKS [{len(templates)}]",
                            id="lbl-gallery-packs-header",
                            classes="pane-header",
                            markup=False,
                        )
                        for pack in templates:
                            status = get_starter_template_status(pack, target_settings)
                            with Vertical(classes="template-card"):
                                with Horizontal(classes="template-card-top"):
                                    chk = Checkbox(
                                        f"{pack.icon} {pack.title}",
                                        value=False,
                                        id=f"chk-gallery-{pack.id}",
                                    )
                                    chk.tooltip = pack.description
                                    self._watch_toggle_control(
                                        chk, self.on_checkbox_changed
                                    )
                                    yield chk
                                    badge_text = self._format_pack_badge(status, False)
                                    self._last_badge_state[pack.id] = (
                                        badge_text,
                                        status,
                                    )
                                    yield Label(
                                        badge_text,
                                        id=f"lbl-gallery-status-{pack.id}",
                                        classes=f"pack-badge badge-{status}",
                                        markup=False,
                                    )
                                yield Label(
                                    pack.description,
                                    classes="template-desc",
                                    markup=False,
                                )
                        yield Label(
                            "",
                            id="lbl-gallery-pack-summary",
                            classes="gallery-summary",
                            markup=False,
                        )

                    with Vertical(classes="gallery-preview-pane"):
                        yield Label(
                            "RULE & CONFLICT PREVIEW",
                            id="lbl-gallery-inspector-title",
                            classes="pane-header",
                            markup=False,
                        )
                        dt_preview = DataTable(id="dt-template-preview")
                        dt_preview.tooltip = "Preview starter pack patterns, rule kinds, target folders, notes, and conflicts"
                        yield dt_preview
                        yield Label(
                            "✔ 0 conflicts across previewed rules.",
                            id="lbl-gallery-conflicts",
                            classes="gallery-conflict-bar",
                            markup=False,
                        )

            with Horizontal(classes="button-row"):
                btn_close = Button("Close", id="btn-close-gallery", variant="default")
                btn_close.tooltip = "Close template gallery"
                yield btn_close
                btn_import = Button(
                    "Import External Rules",
                    id="btn-import-rules",
                    variant="primary",
                )
                btn_import.tooltip = "Import Hazel (.hazelrules/.plist), DropIt (.ini/.xml/.json/.dropit), or TagSpaces (taggroup.json) rule files"
                yield btn_import
                btn_export = Button(
                    "Export Rules",
                    id="btn-export-rules",
                    variant="primary",
                )
                btn_export.tooltip = "Export active rules to Sortify JSON, Hazel (.hazelrules), or DropIt (.ini)"
                yield btn_export
                btn_apply = Button(
                    "Apply Selected Templates",
                    id="btn-apply-templates",
                    variant="primary",
                )
                btn_apply.tooltip = "Merge selected template packs into target scope"
                yield btn_apply

    def _refresh_gallery_state(self) -> None:
        """Refresh scope badge, pack status badges, rule preview table, and conflict summary."""
        from app.core.rule_templates import (
            analyze_starter_template_conflicts,
            build_starter_template_preview_rows,
            get_starter_template_by_id,
            get_starter_template_status,
            get_starter_templates,
        )

        target_settings, scope_label = self._resolve_target_scope()
        stage_disabled = self._is_stage_disabled()
        checked_set = set(self._get_checked_pack_ids())

        with contextlib.suppress(NoMatches):
            self.query_one("#lbl-gallery-scope", Label).update(
                f"Target Scope: {scope_label}"
            )

        with contextlib.suppress(NoMatches):
            staging_lbl = self.query_one("#lbl-gallery-staging-badge", Label)
            staging_lbl.update(
                "[SAFE STAGING MODE ACTIVE]"
                if stage_disabled
                else "[IMMEDIATE ACTIVATION]"
            )

        for pack in get_starter_templates():
            status = get_starter_template_status(pack, target_settings)
            badge_text = self._format_pack_badge(status, pack.id in checked_set)
            prev_badge = self._last_badge_state.get(pack.id)
            if prev_badge == (badge_text, status):
                continue
            with contextlib.suppress(NoMatches):
                badge = self.query_one(f"#lbl-gallery-status-{pack.id}", Label)
                if prev_badge is None or prev_badge[0] != badge_text:
                    badge.update(badge_text)
                if prev_badge is None or prev_badge[1] != status:
                    for cls_name in (
                        "badge-active",
                        "badge-staged",
                        "badge-partial",
                        "badge-none",
                    ):
                        badge.remove_class(cls_name)
                    badge.add_class(f"badge-{status}")
                self._last_badge_state[pack.id] = (badge_text, status)

        preview_ids, from_checked = self._get_preview_pack_ids()
        rows = build_starter_template_preview_rows(
            preview_ids,
            target_settings,
            stage_disabled=stage_disabled,
        )
        conflicts = analyze_starter_template_conflicts(target_settings, preview_ids)

        with contextlib.suppress(NoMatches):
            title_lbl = self.query_one("#lbl-gallery-inspector-title", Label)
            if from_checked:
                pack_word = "PACK" if len(preview_ids) == 1 else "PACKS"
                title_lbl.update(
                    f"RULE & CONFLICT PREVIEW — {len(preview_ids)} {pack_word} ({len(rows)} RULES)"
                )
            elif preview_ids:
                focused_pack = get_starter_template_by_id(preview_ids[0])
                p_name = focused_pack.title if focused_pack else preview_ids[0]
                title_lbl.update(
                    f"RULE & CONFLICT PREVIEW — {p_name} ({len(rows)} RULES)"
                )
            else:
                title_lbl.update("RULE & CONFLICT PREVIEW")

        rows_sig = tuple(
            (
                row["pack_id"],
                row["pattern"],
                row["kind"],
                row["target_folder"],
                row["note"],
                row["status"],
            )
            for row in rows
        )
        with contextlib.suppress(NoMatches):
            dt = self.query_one("#dt-template-preview", DataTable)
            if dt.columns and rows_sig != self._last_preview_rows_sig:
                dt.clear()
                for idx, row in enumerate(rows):
                    dt.add_row(
                        row["pattern"],
                        row["kind"],
                        row["target_folder"],
                        row["note"],
                        f"[{row['status']}]",
                        key=f"{row['pack_id']}:{idx}",
                    )
                self._last_preview_rows_sig = rows_sig

        with contextlib.suppress(NoMatches):
            summary_lbl = self.query_one("#lbl-gallery-pack-summary", Label)
            summary_lbl.update(
                f"Presets: {len(checked_set)} | Rules: {len(rows)} | Conf: {len(conflicts)}"
            )

        with contextlib.suppress(NoMatches):
            conf_lbl = self.query_one("#lbl-gallery-conflicts", Label)
            if conflicts:
                sample_idents = ", ".join(c.identifier for c in conflicts[:3])
                conf_lbl.update(
                    f"⚠ {len(conflicts)} conflict(s) ({sample_idents}) — existing custom rules preserved (keep_existing)."
                )
                conf_lbl.add_class("gallery-conflict-warning")
            else:
                conf_lbl.update("✔ 0 conflicts across previewed rules.")
                conf_lbl.remove_class("gallery-conflict-warning")

    def on_mount(self) -> None:
        """Set up preview table columns, populate inspector, and focus initial pack checkbox."""
        super().on_mount()
        from app.core.rule_templates import get_starter_templates

        with contextlib.suppress(NoMatches):
            dt = self.query_one("#dt-template-preview", DataTable)
            dt.cursor_type = "row"
            dt.zebra_stripes = True
            dt.add_column("Pattern", width=12)
            dt.add_column("Kind", width=12)
            dt.add_column("Target Folder", width=14)
            dt.add_column("Note", width=15)
            dt.add_column("Status", width=13)

        templates = get_starter_templates()
        if templates:
            first_id = templates[0].id
            self._focused_pack_id = first_id
            with contextlib.suppress(NoMatches):
                self.query_one(f"#chk-gallery-{first_id}", Checkbox).focus()

        self._refresh_gallery_state()
        self.announce("Opened starter rule template gallery.")

    @on(events.DescendantFocus)
    def on_descendant_focus(self, event: events.DescendantFocus) -> None:
        """Update right-pane rule preview when focus moves across starter pack checkboxes."""
        widget_id = getattr(event.widget, "id", None) or ""
        if (
            widget_id.startswith("chk-gallery-")
            and widget_id != "chk-gallery-stage-disabled"
        ):
            pack_id = widget_id[len("chk-gallery-") :]
            if pack_id != self._focused_pack_id:
                self._focused_pack_id = pack_id
                self._refresh_gallery_state()

    @on(Checkbox.Changed)
    def on_checkbox_changed(self, event: Checkbox.Changed) -> None:
        """Refresh rule preview and announce starter template gallery checkbox changes."""
        if self._should_skip_bubbled_toggle_event(event):
            return
        chk_id = (
            getattr(event.checkbox, "id", None)
            or getattr(event.control, "id", None)
            or ""
        )
        value = bool(event.value)
        if chk_id == "chk-gallery-stage-disabled":
            self._refresh_gallery_state()
            mode = "disabled for review" if value else "enabled immediately"
            self.announce(f"Starter rule staging mode set to {mode}.")
            return

        prefix = ""
        if chk_id.startswith("chk-gallery-"):
            prefix = "chk-gallery-"
        elif chk_id.startswith("chk-template-"):
            prefix = "chk-template-"
        else:
            return

        pack_id = chk_id[len(prefix) :]
        self._focused_pack_id = pack_id
        self._refresh_gallery_state()

        from app.core.rule_templates import get_starter_templates

        for pack in get_starter_templates():
            if pack.id == pack_id:
                state = "selected" if value else "deselected"
                self.announce(f"{pack.title} template pack {state}.")
                break

    @on(Button.Pressed, "#btn-apply-templates")
    def action_apply_templates(self) -> None:
        """Apply or stage selected starter template packs into target scope."""
        from app.core.rule_templates import apply_starter_templates

        selected_pack_ids = self._get_checked_pack_ids()
        stage_disabled = self._is_stage_disabled()
        target_settings, _ = self._resolve_target_scope()

        if selected_pack_ids:
            try:
                apply_starter_templates(
                    target_settings,
                    selected_pack_ids,
                    stage_disabled=stage_disabled,
                )
                verb = "Staged" if stage_disabled else "Applied"
                suffix = " (disabled for review)" if stage_disabled else " to settings"
                msg = f"{verb} {len(selected_pack_ids)} starter rule template pack(s){suffix}."
                self.announce(msg)
                if hasattr(self.app, "notify"):
                    self.app.notify(msg)
                if not self.defer_rescan:
                    scan_fn = getattr(self.app, "action_scan_directory", None)
                    if callable(scan_fn):
                        scan_fn()
            except Exception as exc:
                err_msg = f"Failed to apply starter rule template pack(s): {exc}"
                self.announce(err_msg)
                if hasattr(self.app, "notify"):
                    self.app.notify(err_msg, severity="error")
        else:
            self.announce("No starter template packs were selected.")

        self.dismiss(None)

    @on(Button.Pressed, "#btn-import-rules")
    def action_import_rules(self) -> None:
        """Open external rule importer modal scoped to the active target settings."""
        target_settings, _ = self._resolve_target_scope()
        self.app.push_screen(RuleImportModal(target_settings))

    @on(Button.Pressed, "#btn-export-rules")
    def action_export_rules(self) -> None:
        """Open export rules modal scoped to the active target settings."""
        target_settings, _ = self._resolve_target_scope()
        self.app.push_screen(ExportRulesModal(target_settings))

    @on(Button.Pressed, "#btn-close-gallery")
    def action_close(self) -> None:
        """Close template gallery dialog."""
        self.announce("Closed starter rule template gallery.")
        self.dismiss(None)

action_apply_templates()

Apply or stage selected starter template packs into target scope.

Source code in app/ui/modals/rules.py
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@on(Button.Pressed, "#btn-apply-templates")
def action_apply_templates(self) -> None:
    """Apply or stage selected starter template packs into target scope."""
    from app.core.rule_templates import apply_starter_templates

    selected_pack_ids = self._get_checked_pack_ids()
    stage_disabled = self._is_stage_disabled()
    target_settings, _ = self._resolve_target_scope()

    if selected_pack_ids:
        try:
            apply_starter_templates(
                target_settings,
                selected_pack_ids,
                stage_disabled=stage_disabled,
            )
            verb = "Staged" if stage_disabled else "Applied"
            suffix = " (disabled for review)" if stage_disabled else " to settings"
            msg = f"{verb} {len(selected_pack_ids)} starter rule template pack(s){suffix}."
            self.announce(msg)
            if hasattr(self.app, "notify"):
                self.app.notify(msg)
            if not self.defer_rescan:
                scan_fn = getattr(self.app, "action_scan_directory", None)
                if callable(scan_fn):
                    scan_fn()
        except Exception as exc:
            err_msg = f"Failed to apply starter rule template pack(s): {exc}"
            self.announce(err_msg)
            if hasattr(self.app, "notify"):
                self.app.notify(err_msg, severity="error")
    else:
        self.announce("No starter template packs were selected.")

    self.dismiss(None)

action_close()

Close template gallery dialog.

Source code in app/ui/modals/rules.py
689
690
691
692
693
@on(Button.Pressed, "#btn-close-gallery")
def action_close(self) -> None:
    """Close template gallery dialog."""
    self.announce("Closed starter rule template gallery.")
    self.dismiss(None)

action_export_rules()

Open export rules modal scoped to the active target settings.

Source code in app/ui/modals/rules.py
683
684
685
686
687
@on(Button.Pressed, "#btn-export-rules")
def action_export_rules(self) -> None:
    """Open export rules modal scoped to the active target settings."""
    target_settings, _ = self._resolve_target_scope()
    self.app.push_screen(ExportRulesModal(target_settings))

action_import_rules()

Open external rule importer modal scoped to the active target settings.

Source code in app/ui/modals/rules.py
677
678
679
680
681
@on(Button.Pressed, "#btn-import-rules")
def action_import_rules(self) -> None:
    """Open external rule importer modal scoped to the active target settings."""
    target_settings, _ = self._resolve_target_scope()
    self.app.push_screen(RuleImportModal(target_settings))

compose()

Compose split-pane starter template gallery children.

Source code in app/ui/modals/rules.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
def compose(self) -> ComposeResult:
    """Compose split-pane starter template gallery children."""
    from app.core.rule_templates import (
        get_starter_template_status,
        get_starter_templates,
    )

    templates = get_starter_templates()
    target_settings, scope_label = self._resolve_target_scope()
    if templates and self._focused_pack_id is None:
        self._focused_pack_id = templates[0].id

    with ModalBox(classes="modal-box"):
        yield Heading(
            "Starter Rule Template Gallery",
            level=1,
            classes="modal-title",
            id="modal-title",
        )
        with Vertical(classes="modal-body"):
            with Horizontal(classes="gallery-header-row"):
                yield Label(
                    f"Target Scope: {scope_label}",
                    id="lbl-gallery-scope",
                    classes="gallery-scope-badge",
                    markup=False,
                )
                yield Label(
                    "[SAFE STAGING MODE ACTIVE]",
                    id="lbl-gallery-staging-badge",
                    classes="gallery-staging-badge",
                    markup=False,
                )

            chk_stage = Checkbox(
                "Stage new rules disabled for review",
                value=True,
                id="chk-gallery-stage-disabled",
            )
            chk_stage.tooltip = "Stage newly applied template rules disabled until reviewed and enabled"
            self._watch_toggle_control(chk_stage, self.on_checkbox_changed)
            yield chk_stage

            with Horizontal(classes="gallery-split-panes"):
                with Vertical(classes="gallery-packs-pane"):
                    yield Label(
                        f"STARTER PACKS [{len(templates)}]",
                        id="lbl-gallery-packs-header",
                        classes="pane-header",
                        markup=False,
                    )
                    for pack in templates:
                        status = get_starter_template_status(pack, target_settings)
                        with Vertical(classes="template-card"):
                            with Horizontal(classes="template-card-top"):
                                chk = Checkbox(
                                    f"{pack.icon} {pack.title}",
                                    value=False,
                                    id=f"chk-gallery-{pack.id}",
                                )
                                chk.tooltip = pack.description
                                self._watch_toggle_control(
                                    chk, self.on_checkbox_changed
                                )
                                yield chk
                                badge_text = self._format_pack_badge(status, False)
                                self._last_badge_state[pack.id] = (
                                    badge_text,
                                    status,
                                )
                                yield Label(
                                    badge_text,
                                    id=f"lbl-gallery-status-{pack.id}",
                                    classes=f"pack-badge badge-{status}",
                                    markup=False,
                                )
                            yield Label(
                                pack.description,
                                classes="template-desc",
                                markup=False,
                            )
                    yield Label(
                        "",
                        id="lbl-gallery-pack-summary",
                        classes="gallery-summary",
                        markup=False,
                    )

                with Vertical(classes="gallery-preview-pane"):
                    yield Label(
                        "RULE & CONFLICT PREVIEW",
                        id="lbl-gallery-inspector-title",
                        classes="pane-header",
                        markup=False,
                    )
                    dt_preview = DataTable(id="dt-template-preview")
                    dt_preview.tooltip = "Preview starter pack patterns, rule kinds, target folders, notes, and conflicts"
                    yield dt_preview
                    yield Label(
                        "✔ 0 conflicts across previewed rules.",
                        id="lbl-gallery-conflicts",
                        classes="gallery-conflict-bar",
                        markup=False,
                    )

        with Horizontal(classes="button-row"):
            btn_close = Button("Close", id="btn-close-gallery", variant="default")
            btn_close.tooltip = "Close template gallery"
            yield btn_close
            btn_import = Button(
                "Import External Rules",
                id="btn-import-rules",
                variant="primary",
            )
            btn_import.tooltip = "Import Hazel (.hazelrules/.plist), DropIt (.ini/.xml/.json/.dropit), or TagSpaces (taggroup.json) rule files"
            yield btn_import
            btn_export = Button(
                "Export Rules",
                id="btn-export-rules",
                variant="primary",
            )
            btn_export.tooltip = "Export active rules to Sortify JSON, Hazel (.hazelrules), or DropIt (.ini)"
            yield btn_export
            btn_apply = Button(
                "Apply Selected Templates",
                id="btn-apply-templates",
                variant="primary",
            )
            btn_apply.tooltip = "Merge selected template packs into target scope"
            yield btn_apply

on_checkbox_changed(event)

Refresh rule preview and announce starter template gallery checkbox changes.

Source code in app/ui/modals/rules.py
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
@on(Checkbox.Changed)
def on_checkbox_changed(self, event: Checkbox.Changed) -> None:
    """Refresh rule preview and announce starter template gallery checkbox changes."""
    if self._should_skip_bubbled_toggle_event(event):
        return
    chk_id = (
        getattr(event.checkbox, "id", None)
        or getattr(event.control, "id", None)
        or ""
    )
    value = bool(event.value)
    if chk_id == "chk-gallery-stage-disabled":
        self._refresh_gallery_state()
        mode = "disabled for review" if value else "enabled immediately"
        self.announce(f"Starter rule staging mode set to {mode}.")
        return

    prefix = ""
    if chk_id.startswith("chk-gallery-"):
        prefix = "chk-gallery-"
    elif chk_id.startswith("chk-template-"):
        prefix = "chk-template-"
    else:
        return

    pack_id = chk_id[len(prefix) :]
    self._focused_pack_id = pack_id
    self._refresh_gallery_state()

    from app.core.rule_templates import get_starter_templates

    for pack in get_starter_templates():
        if pack.id == pack_id:
            state = "selected" if value else "deselected"
            self.announce(f"{pack.title} template pack {state}.")
            break

on_descendant_focus(event)

Update right-pane rule preview when focus moves across starter pack checkboxes.

Source code in app/ui/modals/rules.py
591
592
593
594
595
596
597
598
599
600
601
602
@on(events.DescendantFocus)
def on_descendant_focus(self, event: events.DescendantFocus) -> None:
    """Update right-pane rule preview when focus moves across starter pack checkboxes."""
    widget_id = getattr(event.widget, "id", None) or ""
    if (
        widget_id.startswith("chk-gallery-")
        and widget_id != "chk-gallery-stage-disabled"
    ):
        pack_id = widget_id[len("chk-gallery-") :]
        if pack_id != self._focused_pack_id:
            self._focused_pack_id = pack_id
            self._refresh_gallery_state()

on_mount()

Set up preview table columns, populate inspector, and focus initial pack checkbox.

Source code in app/ui/modals/rules.py
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
def on_mount(self) -> None:
    """Set up preview table columns, populate inspector, and focus initial pack checkbox."""
    super().on_mount()
    from app.core.rule_templates import get_starter_templates

    with contextlib.suppress(NoMatches):
        dt = self.query_one("#dt-template-preview", DataTable)
        dt.cursor_type = "row"
        dt.zebra_stripes = True
        dt.add_column("Pattern", width=12)
        dt.add_column("Kind", width=12)
        dt.add_column("Target Folder", width=14)
        dt.add_column("Note", width=15)
        dt.add_column("Status", width=13)

    templates = get_starter_templates()
    if templates:
        first_id = templates[0].id
        self._focused_pack_id = first_id
        with contextlib.suppress(NoMatches):
            self.query_one(f"#chk-gallery-{first_id}", Checkbox).focus()

    self._refresh_gallery_state()
    self.announce("Opened starter rule template gallery.")

app.ui.modals.sample_playground

app.ui.modals.sample_playground

Interactive Onboarding Sample Playground Modal with Live Rule Matrix.

SamplePlaygroundModal

Bases: ResponsiveModalScreen[None]

Modal screen for interactive onboarding sample playground with live rule simulation.

Source code in app/ui/modals/sample_playground.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
class SamplePlaygroundModal(ResponsiveModalScreen[None]):
    """Modal screen for interactive onboarding sample playground with live rule simulation."""

    BINDINGS = [
        Binding("escape", "cancel", "Close playground", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-box {
        width: 92%;
        max-width: 100;
        min-width: 40;
        max-height: 92%;
    }
    .field-label {
        margin-top: 1;
        color: $text;
        text-style: bold;
    }
    .playground-panes {
        width: 100%;
        height: auto;
        min-height: 12;
        margin-top: 1;
        margin-bottom: 1;
    }
    .left-pane {
        width: 45%;
        height: auto;
        padding-right: 1;
    }
    .right-pane {
        width: 55%;
        height: auto;
        padding-left: 1;
    }
    #playground-doc-list {
        height: 8;
        min-height: 5;
        border: solid $accent;
        margin-bottom: 1;
    }
    #playground-doc-preview {
        height: 6;
        min-height: 4;
        border: solid $primary;
        padding: 0 1;
        background: $surface;
        overflow-y: auto;
    }
    #playground-prediction-matrix {
        height: 10;
        min-height: 7;
        border: solid $accent;
        margin-top: 1;
        margin-bottom: 1;
    }
    .button-row {
        min-height: 3;
    }
    .button-row Button {
        margin-left: 1;
    }
    Button:focus, Checkbox:focus, OptionList:focus, DataTable:focus {
        border: heavy $accent;
        text-style: bold;
    }
    SamplePlaygroundModal {
        &.compact .field-label {
            margin-top: 0;
        }
        &.compact .playground-panes {
            margin-top: 0;
            margin-bottom: 0;
            min-height: 0;
        }
        &.narrow .playground-panes {
            layout: vertical;
        }
        &.narrow .left-pane, &.narrow .right-pane {
            width: 100%;
            padding: 0;
        }
        &.compact #playground-doc-list {
            height: 6;
            margin-bottom: 0;
        }
        &.compact #playground-doc-preview {
            height: 4;
            min-height: 3;
        }
        &.compact #playground-prediction-matrix {
            height: 6;
            min-height: 6;
            margin-top: 0;
            margin-bottom: 0;
        }
        &.narrow .button-row Button {
            margin-left: 0;
            min-width: 0;
            padding: 0 1;
        }
    }
    """

    def __init__(
        self,
        settings: Any,
        target_dir: str | None = None,
        initial_selected_packs: list[str] | None = None,
        on_sync: Callable[[dict[str, Any]], None] | None = None,
    ):
        super().__init__()
        self.settings = settings
        self.target_dir = target_dir or getattr(self.app, "base_dir", "") or os.getcwd()
        self.sample_items = get_sample_corpus_items()
        self.selected_file: str = "demo_finance.txt"
        self._predictions: dict[str, dict[str, Any]] = {}
        self._initial_selected_packs = (
            list(initial_selected_packs)
            if initial_selected_packs is not None
            else ["financial_tax", "personal_admin"]
        )
        self._on_sync = on_sync
        self._last_simulated_packs: tuple[str, ...] | None = None

    @staticmethod
    def _ensure_matrix_columns(matrix: DataTable) -> None:
        """Configure prediction matrix columns idempotently."""
        matrix.cursor_type = "row"
        if not matrix.columns:
            matrix.add_column("Document", key="doc")
            matrix.add_column("Category", key="cat")
            matrix.add_column("Target Path", key="target")
            matrix.add_column("Confidence", key="conf")
            matrix.add_column("Matched Rule", key="rule")

    def _populate_matrix_for_packs(
        self,
        matrix: DataTable,
        selected_packs: list[str],
        *,
        force: bool = False,
    ) -> None:
        """Compute simulation predictions for selected_packs and populate matrix rows."""
        from app.config import resolve_scoped_settings

        state = tuple(selected_packs)
        self._ensure_matrix_columns(matrix)
        if not force and self._last_simulated_packs == state and matrix.row_count > 0:
            return
        scoped_settings = resolve_scoped_settings(
            self.settings, self.target_dir, fallback_to_global=True
        )
        self._predictions = simulate_corpus_classification(
            selected_packs=selected_packs,
            settings=scoped_settings,
        )
        matrix.clear()
        for fn, pred in self._predictions.items():
            conf_str = f"{int(pred.get('confidence', 0) * 100)}%"
            matrix.add_row(
                pred.get("filename", fn),
                pred.get("category", "Uncategorized"),
                pred.get("target_path", ""),
                conf_str,
                pred.get("matched_rule", "None"),
                key=fn,
            )
        self._last_simulated_packs = state

    def compose(self) -> ComposeResult:
        """Compose playground modal dialog UI widgets."""
        with ModalBox(classes="modal-box"):
            with Vertical(classes="modal-body"):
                yield Heading(
                    "Interactive Sample Playground",
                    level=1,
                    classes="modal-title",
                    id="modal-title",
                )
                yield Label(
                    "Select a sample document and toggle starter rule packs to preview live classification prediction matrix without altering disk files."
                )

                with Horizontal(classes="playground-panes"):
                    # Left Pane: Sample Document Selection & Content Preview
                    with Vertical(classes="left-pane"):
                        yield Label("Sample Corpus Documents:", classes="field-label")
                        opts = [Option(fn, id=fn) for fn in self.sample_items.keys()]
                        doc_list = OptionList(*opts, id="playground-doc-list")
                        doc_list.tooltip = (
                            "Select a sample document to inspect its text content"
                        )
                        yield doc_list

                        yield Label("Document Text Preview:", classes="field-label")
                        initial_content = self.sample_items.get(self.selected_file, "")
                        initial_preview = (
                            initial_content
                            if initial_content
                            else "[italic gray](Empty document)[/italic gray]"
                        )
                        yield Static(initial_preview, id="playground-doc-preview")

                    # Right Pane: Starter Template Packs & Live Prediction Matrix
                    with Vertical(classes="right-pane"):
                        yield Label(
                            "Starter Rule Template Packs:", classes="field-label"
                        )
                        chk_stage_pg = Checkbox(
                            "Stage committed starter rules disabled for review",
                            value=True,
                            id="chk-playground-stage-disabled",
                        )
                        chk_stage_pg.tooltip = "Stage committed starter template rules disabled until reviewed in Active Rule Manager"
                        self._watch_toggle_control(
                            chk_stage_pg, self.on_pack_checkbox_changed
                        )
                        yield chk_stage_pg
                        initial_set = set(self._initial_selected_packs)
                        ordered_initial_packs: list[str] = []
                        for pack in get_starter_templates():
                            is_default = pack.id in initial_set
                            if is_default:
                                ordered_initial_packs.append(pack.id)
                            chk = Checkbox(
                                f"{pack.icon} {pack.title}",
                                value=is_default,
                                id=f"chk-playground-pack-{pack.id}",
                            )
                            chk.tooltip = pack.description
                            self._watch_toggle_control(
                                chk, self.on_pack_checkbox_changed
                            )
                            yield chk

                        yield Label(
                            "Live Classification Prediction Matrix:",
                            classes="field-label",
                        )
                        matrix = DataTable(id="playground-prediction-matrix")
                        matrix.tooltip = "Live classification results for each sample document across selected starter packs"
                        self._populate_matrix_for_packs(
                            matrix, ordered_initial_packs, force=True
                        )
                        yield matrix

            with Horizontal(classes="button-row"):
                btn_commit = Button(
                    "Commit Sandbox to Workspace",
                    id="btn-commit-playground",
                    variant="primary",
                )
                btn_commit.tooltip = "Save selected starter packs and write sample documents into the target workspace"
                yield btn_commit
                btn_close = Button(
                    "Close Playground",
                    id="btn-close-playground",
                    variant="default",
                )
                btn_close.tooltip = (
                    "Close sample playground without writing sample files to disk"
                )
                yield btn_close

    def on_mount(self) -> None:
        """Set up prediction matrix columns, focus doc list, and evaluate predictions."""
        super().on_mount()

        with contextlib.suppress(NoMatches):
            self._refresh_simulation()
            self._update_doc_preview(self.selected_file)

        try:
            self.query_one("#playground-doc-list", OptionList).focus()
        except Exception:
            pass

        self.announce("Opened interactive sample playground modal.")

    def _get_selected_pack_ids(self) -> list[str]:
        """Return list of pack IDs currently checked in the playground."""
        selected_packs = []
        for pack in get_starter_templates():
            try:
                chk = self.query_one(f"#chk-playground-pack-{pack.id}", Checkbox)
                if chk.value:
                    selected_packs.append(pack.id)
            except Exception:
                pass
        return selected_packs

    def _refresh_simulation(self, *, force: bool = False) -> None:
        """Re-evaluate rule simulation and update prediction matrix table."""
        selected_packs = self._get_selected_pack_ids()
        matrix = self.query_one("#playground-prediction-matrix", DataTable)
        self._populate_matrix_for_packs(matrix, selected_packs, force=force)

    def _update_doc_preview(self, filename: str) -> None:
        """Update text preview box for selected sample document."""
        self.selected_file = filename
        preview = self.query_one("#playground-doc-preview", Static)
        content = self.sample_items.get(filename, "")
        if not content:
            preview.update("[italic gray](Empty document)[/italic gray]")
        else:
            preview.update(content)

    @on(OptionList.OptionHighlighted, "#playground-doc-list")
    @on(OptionList.OptionSelected, "#playground-doc-list")
    def on_doc_option_event(
        self, event: OptionList.OptionHighlighted | OptionList.OptionSelected
    ) -> None:
        """Update document preview on OptionList highlight or selection."""
        if event.option and event.option.id:
            fn = str(event.option.id)
            self._update_doc_preview(fn)
            self.announce(f"Selected sample document {fn}.")

    def _is_stage_disabled(self) -> bool:
        """Return True when committed starter pack rules should be staged disabled."""
        from textual.css.query import NoMatches

        try:
            return bool(
                self.query_one("#chk-playground-stage-disabled", Checkbox).value
            )
        except NoMatches:
            return True

    def _notify_sync(self, *, committed: bool) -> None:
        """Invoke optional synchronization callback with current playground state."""
        if callable(self._on_sync):
            try:
                self._on_sync(
                    {
                        "selected_packs": self._get_selected_pack_ids(),
                        "stage_disabled": self._is_stage_disabled(),
                        "committed": committed,
                        "target_dir": self.target_dir,
                    }
                )
            except Exception as exc:
                logger.debug(f"SamplePlaygroundModal sync callback error: {exc}")

    @on(Checkbox.Changed)
    def on_pack_checkbox_changed(self, event: Checkbox.Changed) -> None:
        """Refresh predictions live when starter rule template pack checkbox is toggled."""
        if self._should_skip_bubbled_toggle_event(event):
            return
        chk_id = (
            getattr(event.checkbox, "id", None)
            or getattr(event.control, "id", None)
            or ""
        )
        value = bool(event.value)
        if chk_id == "chk-playground-stage-disabled":
            self._notify_sync(committed=False)
            mode = "disabled for review" if value else "enabled immediately"
            self.announce(f"Starter rule staging mode set to {mode}.")
            return
        if chk_id.startswith("chk-playground-pack-"):
            pack_id = chk_id[len("chk-playground-pack-") :]
            with contextlib.suppress(NoMatches):
                self._refresh_simulation()
            self._notify_sync(committed=False)
            state = "enabled" if value else "disabled"
            self.announce(f"Starter template pack {pack_id} {state}.")

    @on(Button.Pressed, "#btn-commit-playground")
    def action_commit(self) -> None:
        """Apply chosen starter template packs and commit sample documents to workspace disk."""
        from app.config import resolve_scoped_settings

        selected_packs = self._get_selected_pack_ids()
        stage_disabled = self._is_stage_disabled()
        if selected_packs:
            try:
                scoped_settings = resolve_scoped_settings(
                    self.settings, self.target_dir, fallback_to_global=True
                )
                apply_starter_templates(
                    scoped_settings,
                    selected_packs,
                    stage_disabled=stage_disabled,
                )
                if hasattr(self.settings, "_save"):
                    self.settings._save()
            except Exception as exc:
                logger.error(f"Failed to apply starter templates on commit: {exc}")

        try:
            try:
                generate_sample_corpus(self.target_dir, overwrite=False)
                self.announce(
                    f"Committed sample documents to workspace '{self.target_dir}'."
                )
            except FileExistsError:
                self.announce(
                    f"Using the existing sample dataset in {self.target_dir}."
                )
            if hasattr(self.app, "base_dir"):
                setattr(self.app, "base_dir", self.target_dir)
            if hasattr(self.app, "source_dirs"):
                setattr(self.app, "source_dirs", [self.target_dir])
            update_cta = getattr(self.app, "_update_onboarding_cta_visibility", None)
            if callable(update_cta):
                try:
                    update_cta()
                except Exception:
                    pass
            try:
                ws_state = self.app.query_one("#onboarding-workspace-state", Static)
                ws_state.update(f"Active Workspace: {self.target_dir}")
            except Exception:
                pass
            self._notify_sync(committed=True)
            if hasattr(self.app, "notify"):
                self.app.notify(
                    "Sample corpus committed to workspace.", severity="information"
                )
        except Exception as exc:
            logger.error(f"Failed to commit sample corpus: {exc}")
            self.announce(f"Failed to commit sample documents: {exc}")

        app_ref = self.app
        was_wizard_underneath = len(app_ref.screen_stack) > 2
        self.dismiss(None)
        scan_fn = getattr(app_ref, "action_scan_directory", None)
        if not was_wizard_underneath and callable(scan_fn):
            scan_fn()

    @on(Button.Pressed, "#btn-close-playground")
    def action_cancel(self) -> None:
        """Close interactive playground without modifying disk files."""
        self.announce("Closed interactive sample playground modal.")
        self.dismiss(None)

action_cancel()

Close interactive playground without modifying disk files.

Source code in app/ui/modals/sample_playground.py
464
465
466
467
468
@on(Button.Pressed, "#btn-close-playground")
def action_cancel(self) -> None:
    """Close interactive playground without modifying disk files."""
    self.announce("Closed interactive sample playground modal.")
    self.dismiss(None)

action_commit()

Apply chosen starter template packs and commit sample documents to workspace disk.

Source code in app/ui/modals/sample_playground.py
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
@on(Button.Pressed, "#btn-commit-playground")
def action_commit(self) -> None:
    """Apply chosen starter template packs and commit sample documents to workspace disk."""
    from app.config import resolve_scoped_settings

    selected_packs = self._get_selected_pack_ids()
    stage_disabled = self._is_stage_disabled()
    if selected_packs:
        try:
            scoped_settings = resolve_scoped_settings(
                self.settings, self.target_dir, fallback_to_global=True
            )
            apply_starter_templates(
                scoped_settings,
                selected_packs,
                stage_disabled=stage_disabled,
            )
            if hasattr(self.settings, "_save"):
                self.settings._save()
        except Exception as exc:
            logger.error(f"Failed to apply starter templates on commit: {exc}")

    try:
        try:
            generate_sample_corpus(self.target_dir, overwrite=False)
            self.announce(
                f"Committed sample documents to workspace '{self.target_dir}'."
            )
        except FileExistsError:
            self.announce(
                f"Using the existing sample dataset in {self.target_dir}."
            )
        if hasattr(self.app, "base_dir"):
            setattr(self.app, "base_dir", self.target_dir)
        if hasattr(self.app, "source_dirs"):
            setattr(self.app, "source_dirs", [self.target_dir])
        update_cta = getattr(self.app, "_update_onboarding_cta_visibility", None)
        if callable(update_cta):
            try:
                update_cta()
            except Exception:
                pass
        try:
            ws_state = self.app.query_one("#onboarding-workspace-state", Static)
            ws_state.update(f"Active Workspace: {self.target_dir}")
        except Exception:
            pass
        self._notify_sync(committed=True)
        if hasattr(self.app, "notify"):
            self.app.notify(
                "Sample corpus committed to workspace.", severity="information"
            )
    except Exception as exc:
        logger.error(f"Failed to commit sample corpus: {exc}")
        self.announce(f"Failed to commit sample documents: {exc}")

    app_ref = self.app
    was_wizard_underneath = len(app_ref.screen_stack) > 2
    self.dismiss(None)
    scan_fn = getattr(app_ref, "action_scan_directory", None)
    if not was_wizard_underneath and callable(scan_fn):
        scan_fn()

compose()

Compose playground modal dialog UI widgets.

Source code in app/ui/modals/sample_playground.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def compose(self) -> ComposeResult:
    """Compose playground modal dialog UI widgets."""
    with ModalBox(classes="modal-box"):
        with Vertical(classes="modal-body"):
            yield Heading(
                "Interactive Sample Playground",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            yield Label(
                "Select a sample document and toggle starter rule packs to preview live classification prediction matrix without altering disk files."
            )

            with Horizontal(classes="playground-panes"):
                # Left Pane: Sample Document Selection & Content Preview
                with Vertical(classes="left-pane"):
                    yield Label("Sample Corpus Documents:", classes="field-label")
                    opts = [Option(fn, id=fn) for fn in self.sample_items.keys()]
                    doc_list = OptionList(*opts, id="playground-doc-list")
                    doc_list.tooltip = (
                        "Select a sample document to inspect its text content"
                    )
                    yield doc_list

                    yield Label("Document Text Preview:", classes="field-label")
                    initial_content = self.sample_items.get(self.selected_file, "")
                    initial_preview = (
                        initial_content
                        if initial_content
                        else "[italic gray](Empty document)[/italic gray]"
                    )
                    yield Static(initial_preview, id="playground-doc-preview")

                # Right Pane: Starter Template Packs & Live Prediction Matrix
                with Vertical(classes="right-pane"):
                    yield Label(
                        "Starter Rule Template Packs:", classes="field-label"
                    )
                    chk_stage_pg = Checkbox(
                        "Stage committed starter rules disabled for review",
                        value=True,
                        id="chk-playground-stage-disabled",
                    )
                    chk_stage_pg.tooltip = "Stage committed starter template rules disabled until reviewed in Active Rule Manager"
                    self._watch_toggle_control(
                        chk_stage_pg, self.on_pack_checkbox_changed
                    )
                    yield chk_stage_pg
                    initial_set = set(self._initial_selected_packs)
                    ordered_initial_packs: list[str] = []
                    for pack in get_starter_templates():
                        is_default = pack.id in initial_set
                        if is_default:
                            ordered_initial_packs.append(pack.id)
                        chk = Checkbox(
                            f"{pack.icon} {pack.title}",
                            value=is_default,
                            id=f"chk-playground-pack-{pack.id}",
                        )
                        chk.tooltip = pack.description
                        self._watch_toggle_control(
                            chk, self.on_pack_checkbox_changed
                        )
                        yield chk

                    yield Label(
                        "Live Classification Prediction Matrix:",
                        classes="field-label",
                    )
                    matrix = DataTable(id="playground-prediction-matrix")
                    matrix.tooltip = "Live classification results for each sample document across selected starter packs"
                    self._populate_matrix_for_packs(
                        matrix, ordered_initial_packs, force=True
                    )
                    yield matrix

        with Horizontal(classes="button-row"):
            btn_commit = Button(
                "Commit Sandbox to Workspace",
                id="btn-commit-playground",
                variant="primary",
            )
            btn_commit.tooltip = "Save selected starter packs and write sample documents into the target workspace"
            yield btn_commit
            btn_close = Button(
                "Close Playground",
                id="btn-close-playground",
                variant="default",
            )
            btn_close.tooltip = (
                "Close sample playground without writing sample files to disk"
            )
            yield btn_close

on_doc_option_event(event)

Update document preview on OptionList highlight or selection.

Source code in app/ui/modals/sample_playground.py
340
341
342
343
344
345
346
347
348
349
@on(OptionList.OptionHighlighted, "#playground-doc-list")
@on(OptionList.OptionSelected, "#playground-doc-list")
def on_doc_option_event(
    self, event: OptionList.OptionHighlighted | OptionList.OptionSelected
) -> None:
    """Update document preview on OptionList highlight or selection."""
    if event.option and event.option.id:
        fn = str(event.option.id)
        self._update_doc_preview(fn)
        self.announce(f"Selected sample document {fn}.")

on_mount()

Set up prediction matrix columns, focus doc list, and evaluate predictions.

Source code in app/ui/modals/sample_playground.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def on_mount(self) -> None:
    """Set up prediction matrix columns, focus doc list, and evaluate predictions."""
    super().on_mount()

    with contextlib.suppress(NoMatches):
        self._refresh_simulation()
        self._update_doc_preview(self.selected_file)

    try:
        self.query_one("#playground-doc-list", OptionList).focus()
    except Exception:
        pass

    self.announce("Opened interactive sample playground modal.")

on_pack_checkbox_changed(event)

Refresh predictions live when starter rule template pack checkbox is toggled.

Source code in app/ui/modals/sample_playground.py
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
@on(Checkbox.Changed)
def on_pack_checkbox_changed(self, event: Checkbox.Changed) -> None:
    """Refresh predictions live when starter rule template pack checkbox is toggled."""
    if self._should_skip_bubbled_toggle_event(event):
        return
    chk_id = (
        getattr(event.checkbox, "id", None)
        or getattr(event.control, "id", None)
        or ""
    )
    value = bool(event.value)
    if chk_id == "chk-playground-stage-disabled":
        self._notify_sync(committed=False)
        mode = "disabled for review" if value else "enabled immediately"
        self.announce(f"Starter rule staging mode set to {mode}.")
        return
    if chk_id.startswith("chk-playground-pack-"):
        pack_id = chk_id[len("chk-playground-pack-") :]
        with contextlib.suppress(NoMatches):
            self._refresh_simulation()
        self._notify_sync(committed=False)
        state = "enabled" if value else "disabled"
        self.announce(f"Starter template pack {pack_id} {state}.")

app.ui.modals.session

app.ui.modals.session

Session history, rollback confirmation and interrupted-session recovery dialogs.

HistoryModal

Bases: ResponsiveModalScreen[dict[str, Any] | None]

Modal dialog for viewing session history records, exporting audit logs, and rolling back sessions.

Source code in app/ui/modals/session.py
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
class HistoryModal(ResponsiveModalScreen[dict[str, Any] | None]):
    """Modal dialog for viewing session history records, exporting audit logs, and rolling back sessions."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-box {
        max-width: 90;
        min-width: 40;
        max-height: 92%;
    }
    .modal-subtitle {
        color: $text-muted;
        margin-bottom: 1;
    }
    .details-box {
        margin-top: 1;
        margin-bottom: 1;
        padding: 0 1;
        background: $boost;
        border: solid $accent;
        color: $text;
    }
    .button-row {
        layout: grid;
        grid-size: 3;
        grid-columns: 1fr 1fr 1fr;
        grid-gutter: 0 1;
    }
    .button-row Button {
        width: 100%;
        min-width: 0;
        margin: 0;
    }
    Button:focus, Input:focus, Select:focus {
        border: heavy $accent;
        text-style: bold;
    }
    HistoryModal {
        &.compact .modal-title {
            margin-bottom: 0;
        }
        &.compact .modal-subtitle {
            margin-bottom: 0;
        }
        &.compact .details-box {
            margin-top: 0;
            margin-bottom: 0;
        }
        &.narrow .button-row {
            grid-size: 2;
            grid-columns: 1fr 1fr;
        }
        &.compact .button-row Button {
            height: 1;
            min-height: 1;
            border: none;
        }
    }
    """

    def __init__(
        self,
        sessions: list[dict[str, Any]] | None = None,
        base_dir: str = "",
    ):
        super().__init__()
        if sessions is None:
            from app.core.session_catalog import list_sessions

            sessions = list_sessions()
        self.sessions = [
            s
            for s in (sessions or [])
            if str(s.get("status") or "").strip().lower() != "undo_snapshot"
        ]
        self.base_dir = base_dir
        self._default_export_dir = Path(get_app_dir()) / "exports"
        self._rollback_in_progress = False
        self._rollback_pipeline: Any = None

    def _build_session_select_options(self) -> list[tuple[str, str]]:
        """Build Select widget options for available historical sessions."""
        if not self.sessions:
            return [("No historical sessions found", "none")]
        options = [("All Sessions (Aggregate Audit Log)", "all")]
        for s in self.sessions:
            sid = s.get("session_id", "unknown")
            b_dir = s.get("base_dir") or "N/A"
            status = s.get("status") or "completed"
            step_cnt = s.get("step_count") or s.get("file_count") or 0
            options.append(
                (
                    f"{sid[:8]}... | {status.upper()} | {step_cnt} file(s) | {b_dir}",
                    sid,
                )
            )
        return options

    def compose(self) -> ComposeResult:
        """Compose history view, export, and undo modal widgets."""
        default_csv_path = str(self._default_export_dir / "audit_log.csv")
        with ModalBox(classes="modal-box"):
            yield Heading(
                "Session History & Undo Controls [Ctrl+Y]",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            with Vertical(classes="modal-body"):
                yield Label(
                    "Select a session row to export an audit record or undo a sort:",
                    classes="modal-subtitle",
                )

                options = self._build_session_select_options()

                select_sess = Select(
                    options,
                    value=options[0][1] if options else "none",
                    id="select-history-session",
                    allow_blank=False,
                )
                select_sess.tooltip = (
                    "Select historical session row for audit export or session undo"
                )
                yield select_sess

                yield Label("Session Details:", classes="modal-subtitle")
                yield Label(
                    "Select a session above to view details.",
                    id="lbl-session-details",
                    classes="details-box",
                )

                yield Label("Output File Path (Audit Log Export):")
                inp_path = Input(
                    value=default_csv_path,
                    placeholder=f"Enter export path (e.g. {default_csv_path})...",
                    id="input-history-path",
                )
                inp_path.tooltip = (
                    "Enter external output path for exported session audit file"
                )
                yield inp_path

                yield Label("Export Format:")
                fmt_select = Select(
                    [("CSV Format (*.csv)", "csv"), ("JSON Format (*.json)", "json")],
                    value="csv",
                    id="select-history-format",
                    allow_blank=False,
                )
                fmt_select.tooltip = "Select audit log output format"
                yield fmt_select

                yield Label("", id="lbl-rollback-status")

            with Horizontal(classes="button-row"):
                btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
                btn_cancel.tooltip = "Cancel history dialog"
                yield btn_cancel

                btn_rollback = Button(
                    "Undo Session",
                    id="btn-rollback-session",
                    variant="warning",
                    disabled=True,
                )
                btn_rollback.tooltip = "Undo file moves for selected session"
                yield btn_rollback

                btn_export = Button(
                    "Export Audit Log", id="btn-export", variant="primary"
                )
                btn_export.tooltip = (
                    "Export audit log file for selected session history row"
                )
                yield btn_export

    def on_mount(self) -> None:
        """Focus session select widget on mount and emit accessibility announcement."""
        super().on_mount()
        select_widget = self.query_one("#select-history-session", Select)
        select_widget.focus()
        self._update_selected_session_view(select_widget.value)
        self.announce("Opened session history export and undo modal dialog.")

    @on(Select.Changed, "#select-history-format")
    def on_format_changed(self, event: Select.Changed) -> None:
        """Sync default export filename suffix when switching between CSV and JSON."""
        fmt_val = str(event.value or "").strip().lower()
        if fmt_val not in ("csv", "json"):
            return
        for inp_path in self.query("#input-history-path").results(Input):
            curr = inp_path.value.strip()
            default_stem = str(self._default_export_dir / "audit_log")
            if curr in (f"{default_stem}.csv", f"{default_stem}.json"):
                inp_path.value = f"{default_stem}.{fmt_val}"

    @on(Select.Changed, "#select-history-session")
    def on_session_changed(self, event: Select.Changed) -> None:
        """Update session details label and button state when session selection changes."""
        self._update_selected_session_view(event.value)

    def _update_selected_session_view(self, session_val: Any) -> None:
        """Update session details label and enable/disable rollback button based on selected session."""
        try:
            lbl_details = self.query_one("#lbl-session-details", Label)
            btn_rollback = self.query_one("#btn-rollback-session", Button)
        except Exception:
            return

        if not session_val or session_val in ("none", "all"):
            lbl_details.update(
                "Aggregate log across all historical sessions selected."
                if session_val == "all"
                else "No session selected."
            )
            btn_rollback.disabled = True
            btn_rollback.tooltip = "Select an individual session to enable undo"
            return

        target = None
        for s in self.sessions:
            if s.get("session_id") == session_val:
                target = s
                break

        if not target:
            lbl_details.update("Session information unavailable.")
            btn_rollback.disabled = True
            return

        sid = target.get("session_id", "N/A")
        status = target.get("status") or "completed"
        b_dir = target.get("base_dir") or "N/A"
        step_cnt = int(target.get("step_count") or 0)
        trashed_cnt = int(target.get("trashed_count") or 0)
        ts = target.get("timestamp")
        ts_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts)) if ts else "N/A"
        trashed_info = (
            f" | Trashed (OS Trash): {trashed_cnt}" if trashed_cnt > 0 else ""
        )

        details_str = (
            f"Session ID: {sid}\n"
            f"Status: {status.upper()} | Reversible Steps: {step_cnt}{trashed_info}\n"
            f"Timestamp: {ts_str}\n"
            f"Base Directory: {b_dir}"
        )
        lbl_details.update(details_str)

        from app.core.session_catalog import can_undo_session

        status_lower = status.lower()
        if not can_undo_session(target):
            btn_rollback.disabled = True
            if status_lower == "rolled_back":
                btn_rollback.tooltip = "Session has already been undone"
            elif status_lower in ("abandoned", "undo_snapshot"):
                btn_rollback.tooltip = "Session cannot be undone"
            else:
                btn_rollback.tooltip = "Session has no reversible file moves to undo"
        else:
            btn_rollback.disabled = False
            btn_rollback.tooltip = "Undo file moves for selected session"

    @on(Button.Pressed, "#btn-export")
    def action_export_audit(self) -> None:
        """Confirm session audit log export and dismiss modal screen."""
        session_val = self.query_one("#select-history-session", Select).value
        if not session_val or session_val == "none":
            self.announce("No session selected for audit log export.")
            return

        path_val = self.query_one("#input-history-path", Input).value.strip()
        if not path_val:
            self.announce("Output file path cannot be empty.")
            return

        format_val = self.query_one("#select-history-format", Select).value or "csv"

        self.dismiss(
            {
                "session_id": str(session_val),
                "output_path": path_val,
                "format": str(format_val),
            }
        )

    @on(Button.Pressed, "#btn-rollback-session")
    def action_rollback_session(self) -> None:
        """Prompt confirmation and initiate asynchronous session undo."""
        from app.core.session_catalog import can_undo_session

        session_val = self.query_one("#select-history-session", Select).value
        if not session_val or session_val in ("none", "all"):
            self.announce("Please select a specific session to undo.")
            return

        target_sess = None
        for s in self.sessions:
            if s.get("session_id") == session_val:
                target_sess = s
                break

        if not target_sess or not can_undo_session(target_sess):
            status_lower = (
                str(target_sess.get("status") or "").strip().lower()
                if target_sess
                else ""
            )
            if status_lower == "rolled_back":
                err_msg = "Selected session has already been undone."
            elif target_sess and int(target_sess.get("step_count") or 0) <= 0:
                err_msg = "Selected session has no reversible file moves to undo."
            else:
                err_msg = "Selected session cannot be undone."
            for status_lbl in self.query("#lbl-rollback-status").results(Label):
                status_lbl.update(f"⚠️ {err_msg}")
            self.announce(err_msg)
            return

        if (
            int(target_sess.get("step_count") or 0) <= 0
            and int(target_sess.get("trashed_count") or 0) > 0
        ):
            sid = str(target_sess["session_id"])
            self.query_one("#btn-rollback-session", Button).disabled = True
            self.query_one("#btn-export", Button).disabled = True
            self.query_one("#btn-cancel", Button).disabled = True
            self._rollback_in_progress = True
            self.run_rollback_worker(sid)
            return

        def handle_confirm_result(result: dict[str, Any] | None) -> None:
            if not result or not result.get("confirmed"):
                return

            sid = result["session_id"]
            selected_step_ids = result.get("selected_step_ids")

            self.query_one("#btn-rollback-session", Button).disabled = True
            self.query_one("#btn-export", Button).disabled = True
            self.query_one("#btn-cancel", Button).disabled = True
            self._rollback_in_progress = True

            lbl_status = self.query_one("#lbl-rollback-status", Label)
            allow_missing = bool(
                result.get("allow_missing") or result.get("ignore_missing")
            )
            lbl_status.update(f"⏳ Undoing session {sid[:8]}... Please wait.")
            self.announce(f"Executing undo for session {sid[:8]}...")

            self.run_rollback_worker(
                sid,
                ignore_missing=allow_missing,
                allow_missing=allow_missing,
                selected_step_ids=selected_step_ids,
            )

        self.app.push_screen(
            RollbackConfirmModal(session_info=target_sess),
            handle_confirm_result,
        )

    @work(thread=True)
    def run_rollback_worker(
        self,
        session_id: str,
        ignore_missing: bool = False,
        selected_step_ids: list[Any] | None = None,
        *,
        allow_missing: bool = False,
    ) -> None:
        """Execute session rollback asynchronously in background worker thread."""
        app_obj = getattr(self, "app", None)
        try:
            from app.core.pipeline import SortPipeline

            effective_allow_missing = bool(allow_missing or ignore_missing)
            app_session = getattr(app_obj, "app_session", None)
            settings = getattr(app_obj, "settings", None)
            pipeline = getattr(app_obj, "pipeline", None)
            if pipeline is None or pipeline.state.is_active:
                pipeline = SortPipeline(app_session, settings=settings)
                if app_obj is not None and getattr(app_obj, "pipeline", None) is None:
                    app_obj.pipeline = pipeline
                    state_hook = getattr(
                        app_obj, "_handle_pipeline_state_transition", None
                    )
                    tel_hook = getattr(app_obj, "_handle_pipeline_telemetry", None)
                    if callable(state_hook):
                        pipeline.add_state_change_hook(state_hook)
                    if callable(tel_hook):
                        pipeline.add_telemetry_hook(tel_hook)
            self._rollback_pipeline = pipeline

            undo_result = pipeline.undo(
                session_id,
                ignore_missing=effective_allow_missing,
                allow_missing=effective_allow_missing,
                selected_step_ids=selected_step_ids,
            )
            if "error" in undo_result.summary:
                raise RuntimeError(str(undo_result.summary["error"]))
            restored_count = int(
                undo_result.summary.get("restored", len(undo_result.moved))
            )
            trashed_remaining = int(
                undo_result.summary.get("trashed_unrestorable")
                or len(undo_result.trashed)
                or 0
            )
            missing_count = (
                0
                if undo_result.rollback_completed
                else int(undo_result.summary.get("missing_count") or 0)
            )

            if app_obj and hasattr(app_obj, "call_from_thread"):
                app_obj.call_from_thread(
                    self._on_rollback_success,
                    session_id,
                    restored_count,
                    trashed_remaining,
                    missing_count,
                )
            else:
                self._on_rollback_success(
                    session_id, restored_count, trashed_remaining, missing_count
                )
        except Exception as err:
            if app_obj and hasattr(app_obj, "call_from_thread"):
                app_obj.call_from_thread(self._on_rollback_failure, session_id, err)
            else:
                self._on_rollback_failure(session_id, err)
        finally:
            self._rollback_pipeline = None

    def _on_rollback_success(
        self,
        session_id: str,
        restored_count: int,
        trashed_remaining: int = 0,
        missing_count: int = 0,
    ) -> None:
        """Handle successful session rollback completion on main thread."""
        self._rollback_in_progress = False
        from app.core.plan_format import format_session_rollback_outcome
        from app.core.session_catalog import list_sessions

        self.sessions = list_sessions()
        self._refresh_session_options(selected_sid=session_id)

        msg, notif_type = format_session_rollback_outcome(
            session_id,
            restored_count,
            trashed_remaining,
            missing_count=missing_count,
        )
        lbl_status = self.query_one("#lbl-rollback-status", Label)
        if missing_count > 0:
            lbl_status.update(
                f"⚠️ Session partially undone ({restored_count} restored; {missing_count} missing target(s) kept in Partially Rolled Back)."
            )
        elif restored_count == 0 and trashed_remaining > 0:
            noun = "copy" if trashed_remaining == 1 else "copies"
            verb_rem = "remains" if trashed_remaining == 1 else "remain"
            lbl_status.update(
                f"⚠️ No reversible moves; {trashed_remaining} duplicate {noun} {verb_rem} in OS Trash."
            )
        elif trashed_remaining > 0:
            lbl_status.update(
                f"✅ Session undone ({restored_count} restored; {trashed_remaining} in OS Trash)."
            )
        else:
            lbl_status.update(
                f"✅ Session successfully undone. ({restored_count} operations restored)"
            )

        self.announce(msg)
        try:
            from app.ui.notifications import notify

            notify(msg, type=notif_type)
        except Exception:
            pass

        self.query_one("#btn-cancel", Button).disabled = False
        self.query_one("#btn-export", Button).disabled = False

    def _on_rollback_failure(self, session_id: str, err: Exception) -> None:
        """Handle session undo failure on main thread."""
        self._rollback_in_progress = False
        lbl_status = self.query_one("#lbl-rollback-status", Label)
        lbl_status.update(f"❌ Undo failed: {err}")

        msg = f"Undo failed for session {session_id[:8]}...: {err}"
        self.announce(msg)
        try:
            from app.ui.notifications import notify

            notify(msg, type="error")
        except Exception:
            pass

        self.query_one("#btn-cancel", Button).disabled = False
        self.query_one("#btn-export", Button).disabled = False
        self.query_one("#btn-rollback-session", Button).disabled = False

        self.app.push_screen(
            RollbackErrorModal(
                title="Undo Failed",
                error_message=str(err),
                settings=getattr(self.app, "settings", None),
            )
        )

    def _refresh_session_options(self, selected_sid: str | None = None) -> None:
        """Re-populate session select dropdown widget options after state update."""
        select_sess = self.query_one("#select-history-session", Select)
        options = self._build_session_select_options()

        select_sess.set_options(options)
        if selected_sid:
            select_sess.value = selected_sid
        self._update_selected_session_view(select_sess.value)

    @on(Button.Pressed, "#btn-cancel")
    def action_cancel(self) -> None:
        """Cancel history export modal, unless an undo is still running."""
        from app.core.pipeline import PipelineLifecycleState

        rb_pipe = getattr(self, "_rollback_pipeline", None)
        if self._rollback_in_progress or (
            rb_pipe is not None and rb_pipe.state == PipelineLifecycleState.ROLLING_BACK
        ):
            self.announce("Undo in progress. Please wait for it to finish.")
            return
        self.dismiss(None)

action_cancel()

Cancel history export modal, unless an undo is still running.

Source code in app/ui/modals/session.py
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
@on(Button.Pressed, "#btn-cancel")
def action_cancel(self) -> None:
    """Cancel history export modal, unless an undo is still running."""
    from app.core.pipeline import PipelineLifecycleState

    rb_pipe = getattr(self, "_rollback_pipeline", None)
    if self._rollback_in_progress or (
        rb_pipe is not None and rb_pipe.state == PipelineLifecycleState.ROLLING_BACK
    ):
        self.announce("Undo in progress. Please wait for it to finish.")
        return
    self.dismiss(None)

action_export_audit()

Confirm session audit log export and dismiss modal screen.

Source code in app/ui/modals/session.py
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
@on(Button.Pressed, "#btn-export")
def action_export_audit(self) -> None:
    """Confirm session audit log export and dismiss modal screen."""
    session_val = self.query_one("#select-history-session", Select).value
    if not session_val or session_val == "none":
        self.announce("No session selected for audit log export.")
        return

    path_val = self.query_one("#input-history-path", Input).value.strip()
    if not path_val:
        self.announce("Output file path cannot be empty.")
        return

    format_val = self.query_one("#select-history-format", Select).value or "csv"

    self.dismiss(
        {
            "session_id": str(session_val),
            "output_path": path_val,
            "format": str(format_val),
        }
    )

action_rollback_session()

Prompt confirmation and initiate asynchronous session undo.

Source code in app/ui/modals/session.py
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
@on(Button.Pressed, "#btn-rollback-session")
def action_rollback_session(self) -> None:
    """Prompt confirmation and initiate asynchronous session undo."""
    from app.core.session_catalog import can_undo_session

    session_val = self.query_one("#select-history-session", Select).value
    if not session_val or session_val in ("none", "all"):
        self.announce("Please select a specific session to undo.")
        return

    target_sess = None
    for s in self.sessions:
        if s.get("session_id") == session_val:
            target_sess = s
            break

    if not target_sess or not can_undo_session(target_sess):
        status_lower = (
            str(target_sess.get("status") or "").strip().lower()
            if target_sess
            else ""
        )
        if status_lower == "rolled_back":
            err_msg = "Selected session has already been undone."
        elif target_sess and int(target_sess.get("step_count") or 0) <= 0:
            err_msg = "Selected session has no reversible file moves to undo."
        else:
            err_msg = "Selected session cannot be undone."
        for status_lbl in self.query("#lbl-rollback-status").results(Label):
            status_lbl.update(f"⚠️ {err_msg}")
        self.announce(err_msg)
        return

    if (
        int(target_sess.get("step_count") or 0) <= 0
        and int(target_sess.get("trashed_count") or 0) > 0
    ):
        sid = str(target_sess["session_id"])
        self.query_one("#btn-rollback-session", Button).disabled = True
        self.query_one("#btn-export", Button).disabled = True
        self.query_one("#btn-cancel", Button).disabled = True
        self._rollback_in_progress = True
        self.run_rollback_worker(sid)
        return

    def handle_confirm_result(result: dict[str, Any] | None) -> None:
        if not result or not result.get("confirmed"):
            return

        sid = result["session_id"]
        selected_step_ids = result.get("selected_step_ids")

        self.query_one("#btn-rollback-session", Button).disabled = True
        self.query_one("#btn-export", Button).disabled = True
        self.query_one("#btn-cancel", Button).disabled = True
        self._rollback_in_progress = True

        lbl_status = self.query_one("#lbl-rollback-status", Label)
        allow_missing = bool(
            result.get("allow_missing") or result.get("ignore_missing")
        )
        lbl_status.update(f"⏳ Undoing session {sid[:8]}... Please wait.")
        self.announce(f"Executing undo for session {sid[:8]}...")

        self.run_rollback_worker(
            sid,
            ignore_missing=allow_missing,
            allow_missing=allow_missing,
            selected_step_ids=selected_step_ids,
        )

    self.app.push_screen(
        RollbackConfirmModal(session_info=target_sess),
        handle_confirm_result,
    )

compose()

Compose history view, export, and undo modal widgets.

Source code in app/ui/modals/session.py
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
def compose(self) -> ComposeResult:
    """Compose history view, export, and undo modal widgets."""
    default_csv_path = str(self._default_export_dir / "audit_log.csv")
    with ModalBox(classes="modal-box"):
        yield Heading(
            "Session History & Undo Controls [Ctrl+Y]",
            level=1,
            classes="modal-title",
            id="modal-title",
        )
        with Vertical(classes="modal-body"):
            yield Label(
                "Select a session row to export an audit record or undo a sort:",
                classes="modal-subtitle",
            )

            options = self._build_session_select_options()

            select_sess = Select(
                options,
                value=options[0][1] if options else "none",
                id="select-history-session",
                allow_blank=False,
            )
            select_sess.tooltip = (
                "Select historical session row for audit export or session undo"
            )
            yield select_sess

            yield Label("Session Details:", classes="modal-subtitle")
            yield Label(
                "Select a session above to view details.",
                id="lbl-session-details",
                classes="details-box",
            )

            yield Label("Output File Path (Audit Log Export):")
            inp_path = Input(
                value=default_csv_path,
                placeholder=f"Enter export path (e.g. {default_csv_path})...",
                id="input-history-path",
            )
            inp_path.tooltip = (
                "Enter external output path for exported session audit file"
            )
            yield inp_path

            yield Label("Export Format:")
            fmt_select = Select(
                [("CSV Format (*.csv)", "csv"), ("JSON Format (*.json)", "json")],
                value="csv",
                id="select-history-format",
                allow_blank=False,
            )
            fmt_select.tooltip = "Select audit log output format"
            yield fmt_select

            yield Label("", id="lbl-rollback-status")

        with Horizontal(classes="button-row"):
            btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
            btn_cancel.tooltip = "Cancel history dialog"
            yield btn_cancel

            btn_rollback = Button(
                "Undo Session",
                id="btn-rollback-session",
                variant="warning",
                disabled=True,
            )
            btn_rollback.tooltip = "Undo file moves for selected session"
            yield btn_rollback

            btn_export = Button(
                "Export Audit Log", id="btn-export", variant="primary"
            )
            btn_export.tooltip = (
                "Export audit log file for selected session history row"
            )
            yield btn_export

on_format_changed(event)

Sync default export filename suffix when switching between CSV and JSON.

Source code in app/ui/modals/session.py
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
@on(Select.Changed, "#select-history-format")
def on_format_changed(self, event: Select.Changed) -> None:
    """Sync default export filename suffix when switching between CSV and JSON."""
    fmt_val = str(event.value or "").strip().lower()
    if fmt_val not in ("csv", "json"):
        return
    for inp_path in self.query("#input-history-path").results(Input):
        curr = inp_path.value.strip()
        default_stem = str(self._default_export_dir / "audit_log")
        if curr in (f"{default_stem}.csv", f"{default_stem}.json"):
            inp_path.value = f"{default_stem}.{fmt_val}"

on_mount()

Focus session select widget on mount and emit accessibility announcement.

Source code in app/ui/modals/session.py
1783
1784
1785
1786
1787
1788
1789
def on_mount(self) -> None:
    """Focus session select widget on mount and emit accessibility announcement."""
    super().on_mount()
    select_widget = self.query_one("#select-history-session", Select)
    select_widget.focus()
    self._update_selected_session_view(select_widget.value)
    self.announce("Opened session history export and undo modal dialog.")

on_session_changed(event)

Update session details label and button state when session selection changes.

Source code in app/ui/modals/session.py
1803
1804
1805
1806
@on(Select.Changed, "#select-history-session")
def on_session_changed(self, event: Select.Changed) -> None:
    """Update session details label and button state when session selection changes."""
    self._update_selected_session_view(event.value)

run_rollback_worker(session_id, ignore_missing=False, selected_step_ids=None, *, allow_missing=False)

Execute session rollback asynchronously in background worker thread.

Source code in app/ui/modals/session.py
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
@work(thread=True)
def run_rollback_worker(
    self,
    session_id: str,
    ignore_missing: bool = False,
    selected_step_ids: list[Any] | None = None,
    *,
    allow_missing: bool = False,
) -> None:
    """Execute session rollback asynchronously in background worker thread."""
    app_obj = getattr(self, "app", None)
    try:
        from app.core.pipeline import SortPipeline

        effective_allow_missing = bool(allow_missing or ignore_missing)
        app_session = getattr(app_obj, "app_session", None)
        settings = getattr(app_obj, "settings", None)
        pipeline = getattr(app_obj, "pipeline", None)
        if pipeline is None or pipeline.state.is_active:
            pipeline = SortPipeline(app_session, settings=settings)
            if app_obj is not None and getattr(app_obj, "pipeline", None) is None:
                app_obj.pipeline = pipeline
                state_hook = getattr(
                    app_obj, "_handle_pipeline_state_transition", None
                )
                tel_hook = getattr(app_obj, "_handle_pipeline_telemetry", None)
                if callable(state_hook):
                    pipeline.add_state_change_hook(state_hook)
                if callable(tel_hook):
                    pipeline.add_telemetry_hook(tel_hook)
        self._rollback_pipeline = pipeline

        undo_result = pipeline.undo(
            session_id,
            ignore_missing=effective_allow_missing,
            allow_missing=effective_allow_missing,
            selected_step_ids=selected_step_ids,
        )
        if "error" in undo_result.summary:
            raise RuntimeError(str(undo_result.summary["error"]))
        restored_count = int(
            undo_result.summary.get("restored", len(undo_result.moved))
        )
        trashed_remaining = int(
            undo_result.summary.get("trashed_unrestorable")
            or len(undo_result.trashed)
            or 0
        )
        missing_count = (
            0
            if undo_result.rollback_completed
            else int(undo_result.summary.get("missing_count") or 0)
        )

        if app_obj and hasattr(app_obj, "call_from_thread"):
            app_obj.call_from_thread(
                self._on_rollback_success,
                session_id,
                restored_count,
                trashed_remaining,
                missing_count,
            )
        else:
            self._on_rollback_success(
                session_id, restored_count, trashed_remaining, missing_count
            )
    except Exception as err:
        if app_obj and hasattr(app_obj, "call_from_thread"):
            app_obj.call_from_thread(self._on_rollback_failure, session_id, err)
        else:
            self._on_rollback_failure(session_id, err)
    finally:
        self._rollback_pipeline = None

MultiSessionRecoveryModal

Bases: ResponsiveModalScreen[Any | None]

Modal dialog for recovering multiple interrupted file sorting sessions.

Source code in app/ui/modals/session.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
class MultiSessionRecoveryModal(ResponsiveModalScreen[Any | None]):
    """Modal dialog for recovering multiple interrupted file sorting sessions."""

    HELP_URL = f"{TROUBLESHOOTING_URL}#multi-session-recovery"

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-title {
        color: $error;
        margin-bottom: 0;
    }
    .modal-subtitle {
        color: $text-muted;
        margin-bottom: 1;
    }
    #sessions-table {
        height: auto;
        min-height: 6;
        max-height: 10;
        border: solid $primary;
        margin-bottom: 1;
    }
    #lbl-selected-session {
        text-style: bold;
        color: $accent;
        margin-bottom: 1;
    }
    .actions-heading {
        margin-top: 1;
        margin-bottom: 0;
    }
    .batch-button-row {
        layout: grid;
        grid-size: 2;
        grid-columns: 1fr 1fr;
        grid-gutter: 0 1;
    }
    .item-button-row {
        layout: grid;
        grid-size: 3;
        grid-columns: 1fr 1fr 1fr;
        grid-gutter: 0 1;
    }
    .button-row Button {
        width: 100%;
        min-width: 0;
        margin: 0;
    }
    Button:focus, DataTable:focus {
        border: heavy $accent;
        text-style: bold;
    }
    MultiSessionRecoveryModal {
        &.compact .modal-subtitle {
            margin-bottom: 0;
        }
        &.compact #sessions-table {
            margin-bottom: 0;
        }
        &.compact #lbl-selected-session {
            margin-bottom: 0;
        }
        &.compact .actions-heading {
            margin-top: 0;
        }
        &.compact .button-row {
            margin-top: 0;
        }
        &.compact .button-row Button {
            height: 1;
            min-height: 1;
            border: none;
        }
        &.narrow .item-button-row {
            grid-size: 2;
            grid-columns: 1fr 1fr;
        }
    }
    """

    def __init__(
        self,
        sessions: list[dict[str, Any]] | None = None,
        settings: Any | None = None,
    ):
        super().__init__()
        if sessions is None:
            sessions = []
        elif isinstance(sessions, dict):
            sessions = [sessions]
        self.sessions: list[dict[str, Any]] = list(sessions)
        self.settings = settings
        self.selected_index: int = 0

    def compose(self) -> ComposeResult:
        """Compose multi-session recovery modal widgets."""
        with ModalBox(classes="modal-box"):
            yield Heading(
                "Multiple Interrupted Sessions Detected",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            with Vertical(classes="modal-body"):
                yield Label(
                    "Sortify detected multiple interrupted sessions. Review or perform batch recovery:",
                    classes="modal-subtitle",
                    id="modal-subtitle",
                )

                yield DataTable(id="sessions-table")

                yield Label(
                    "Selected: None",
                    id="lbl-selected-session",
                )

            with Vertical(classes="modal-footer"):
                yield Heading("Batch Actions:", level=2, classes="actions-heading")
                with Horizontal(classes="button-row batch-button-row"):
                    btn_rollback_all = Button(
                        "Rollback All", id="btn-rollback-all", variant="warning"
                    )
                    btn_rollback_all.tooltip = (
                        "Rollback uncommitted operations across all abandoned sessions"
                    )
                    yield btn_rollback_all

                    btn_clean_all = Button(
                        "Clean All", id="btn-clean-all", variant="error"
                    )
                    btn_clean_all.tooltip = (
                        "Discard all abandoned sessions and clean records"
                    )
                    yield btn_clean_all

                yield Heading(
                    "Item Actions (Selected Session):",
                    level=2,
                    classes="actions-heading",
                )
                with Horizontal(classes="button-row item-button-row"):
                    btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
                    btn_cancel.tooltip = "Cancel recovery dialog"
                    yield btn_cancel

                    btn_help = Button("Help", id="btn-help", variant="default")
                    btn_help.tooltip = "Open session recovery troubleshooting guide"
                    yield btn_help

                    btn_clean = Button("Clean", id="btn-clean", variant="error")
                    btn_clean.tooltip = (
                        "Discard selected session files and clean record"
                    )
                    yield btn_clean

                    btn_rollback = Button(
                        "Rollback", id="btn-rollback", variant="warning"
                    )
                    btn_rollback.tooltip = (
                        "Rollback partial file moves for selected session"
                    )
                    yield btn_rollback

                    btn_resume = Button("Resume", id="btn-resume", variant="primary")
                    btn_resume.tooltip = (
                        "Resume pending file moves for selected session"
                    )
                    yield btn_resume

    def on_mount(self) -> None:
        """Initialize table columns, populate rows, and announce session count."""
        super().on_mount()
        table = self.query_one("#sessions-table", DataTable)
        table.cursor_type = "row"
        table.add_columns("Session ID", "Target Directory", "Step Count", "Status")
        self._refresh_table()
        count = len(self.sessions)
        selected = self.get_selected_session()
        conflict_note = (
            f" {selected['conflict_summary']}"
            if selected and selected.get("conflict_summary")
            else ""
        )
        self.announce(
            f"Opened multi-session recovery dialog. Detected {count} abandoned sessions.{conflict_note}"
        )
        with contextlib.suppress(QueryError, AppError, ScreenError):
            btn_resume = self.query_one("#btn-resume", Button)
            if btn_resume.display and not btn_resume.disabled:
                btn_resume.focus()
            else:
                self.query_one("#btn-rollback", Button).focus()

    def _refresh_table(self) -> None:
        """Refresh DataTable rows from self.sessions."""
        try:
            table = self.query_one("#sessions-table", DataTable)
        except (QueryError, AppError, ScreenError):
            return
        table.clear()
        for idx, sess in enumerate(self.sessions):
            sid = str(sess.get("session_id", "Unknown"))
            b_dir = scrub_user_home_paths(str(sess.get("base_dir") or "Unknown"))
            steps = str(sess.get("step_count", 0))
            status = str(sess.get("status", "Unknown"))
            if sess.get("recovery_kind") == "incomplete_undo":
                status = f"{status} (incomplete undo)"
            table.add_row(sid, b_dir, steps, status, key=str(idx))
        if self.sessions:
            if self.selected_index >= len(self.sessions):
                self.selected_index = max(0, len(self.sessions) - 1)
            with contextlib.suppress(
                QueryError, AppError, ScreenError, LookupError, ValueError
            ):
                table.move_cursor(row=self.selected_index)
        self._update_selected_session_display()

    def get_selected_session(self) -> dict[str, Any] | None:
        """Return the currently selected session dictionary."""
        if not self.sessions:
            return None
        with contextlib.suppress(QueryError, AppError, ScreenError):
            table = self.query_one("#sessions-table", DataTable)
            row_idx = table.cursor_row
            if row_idx is not None and 0 <= row_idx < len(self.sessions):
                self.selected_index = row_idx
        if 0 <= self.selected_index < len(self.sessions):
            return self.sessions[self.selected_index]
        return self.sessions[0]

    @staticmethod
    def _session_can_resume(sess: dict[str, Any] | None) -> bool:
        if not sess:
            return False
        if sess.get("can_resume") is False:
            return False
        if sess.get("recovery_kind") == "incomplete_undo":
            return False
        return True

    def _update_selected_session_display(self) -> None:
        """Update selected session details label and action button states."""
        try:
            lbl = self.query_one("#lbl-selected-session", Label)
        except (QueryError, AppError, ScreenError):
            return
        sess = self.get_selected_session()
        if not sess:
            lbl.update("Selected: No sessions remaining.")
            return
        sid = sess.get("session_id", "Unknown")
        b_dir = scrub_user_home_paths(str(sess.get("base_dir") or "Unknown"))
        steps = sess.get("step_count", 0)
        status = sess.get("status", "Unknown")
        conflict = sess.get("conflict_summary")
        text = f"Selected: {sid} | Target: {b_dir} | Steps: {steps} | Status: {status}"
        if conflict:
            text = f"{text} | Cause: {conflict}"
        lbl.update(text)

        can_resume = self._session_can_resume(sess)
        with contextlib.suppress(QueryError, AppError, ScreenError):
            btn_resume = self.query_one("#btn-resume", Button)
            btn_rollback = self.query_one("#btn-rollback", Button)
            btn_resume.disabled = not can_resume
            btn_resume.display = can_resume
            btn_rollback.variant = "primary" if not can_resume else "warning"

    @on(DataTable.RowHighlighted, "#sessions-table")
    def _on_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
        """Handle row cursor movement in sessions table."""
        if 0 <= event.cursor_row < len(self.sessions):
            self.selected_index = event.cursor_row
            self._update_selected_session_display()
            sess = self.sessions[self.selected_index]
            sid = sess.get("session_id", "Unknown")
            conflict = sess.get("conflict_summary")
            if conflict:
                self.announce(f"Selected session '{sid}'. {conflict}")
            else:
                self.announce(f"Selected session '{sid}'.")

    @on(DataTable.RowSelected, "#sessions-table")
    def _on_row_selected(self, event: DataTable.RowSelected) -> None:
        """Handle row selection in sessions table."""
        if 0 <= event.cursor_row < len(self.sessions):
            self.selected_index = event.cursor_row
            self._update_selected_session_display()

    @on(Button.Pressed, "#btn-clean-all")
    def action_clean_all(self) -> None:
        """Confirm clean all action."""
        self.announce("Confirmed cleanup of all abandoned sessions.")
        self.dismiss(RecoveryResult("clean_all", sessions=list(self.sessions)))

    @on(Button.Pressed, "#btn-rollback-all")
    def action_rollback_all(self) -> None:
        """Confirm rollback all action."""
        self.announce("Confirmed rollback of all abandoned sessions.")
        self.dismiss(RecoveryResult("rollback_all", sessions=list(self.sessions)))

    @on(Button.Pressed, "#btn-resume")
    def action_resume(self) -> None:
        """Confirm resume action for the selected session."""
        selected = self.get_selected_session()
        if not selected:
            return
        if not self._session_can_resume(selected):
            self.announce(
                "Cannot resume an incomplete undo session. Choose Rollback or Clean."
            )
            return
        sid = selected.get("session_id", "Unknown")
        self.announce(f"Confirmed resume for session '{sid}'.")
        self.dismiss(
            RecoveryResult("resume", session=selected, sessions=list(self.sessions))
        )

    @on(Button.Pressed, "#btn-clean")
    def action_clean(self) -> None:
        """Clean currently selected session."""
        selected = self.get_selected_session()
        if not selected:
            return
        sid = selected.get("session_id", "Unknown")
        app_clean = getattr(self.app, "_do_recovery_clean", None)
        if callable(app_clean):
            try:
                app_clean(selected)
            except Exception as e:
                logger.error(f"Error cleaning session {sid}: {e}")
        else:
            from app.core.session_catalog import forget_abandoned_session

            try:
                forget_abandoned_session(selected)
            except Exception as e:
                logger.error(f"Error cleaning session {sid}: {e}")

        self.announce(f"Cleaned session files for '{sid}'.")
        self.sessions = [s for s in self.sessions if s.get("session_id") != sid]
        self._refresh_table()
        if not self.sessions:
            self.dismiss(RecoveryResult("clean", session=selected, sessions=[]))

    @on(Button.Pressed, "#btn-rollback")
    def action_rollback(self) -> None:
        """Rollback currently selected session."""
        selected = self.get_selected_session()
        if not selected:
            return
        sid = selected.get("session_id", "Unknown")
        app_rollback = getattr(self.app, "_do_recovery_rollback", None)
        if callable(app_rollback):
            outcome = app_rollback(selected)
            succeeded = outcome is not False
        else:
            from app.core.session_catalog import roll_back_abandoned_session

            settings = getattr(self, "settings", None) or getattr(
                self.app, "settings", None
            )
            succeeded = (
                bool(roll_back_abandoned_session(settings, selected))
                if settings
                else False
            )
            action_scan = getattr(self.app, "action_scan_directory", None)
            if callable(action_scan):
                try:
                    action_scan()
                except Exception:
                    pass

        if not succeeded:
            self.announce(
                f"Session recovery failed for '{sid}': write/permission error. Session files and safety storage preserved."
            )
            return

        self.announce(f"Rolled back session '{sid}'.")
        self.sessions = [s for s in self.sessions if s.get("session_id") != sid]
        self._refresh_table()
        if not self.sessions:
            self.dismiss(RecoveryResult("rollback", session=selected, sessions=[]))

    @on(Button.Pressed, "#btn-cancel")
    def action_cancel(self) -> None:
        """Cancel recovery dialog."""
        self.announce("Cancelled multi-session recovery dialog.")
        self.dismiss(None)

action_cancel()

Cancel recovery dialog.

Source code in app/ui/modals/session.py
630
631
632
633
634
@on(Button.Pressed, "#btn-cancel")
def action_cancel(self) -> None:
    """Cancel recovery dialog."""
    self.announce("Cancelled multi-session recovery dialog.")
    self.dismiss(None)

action_clean()

Clean currently selected session.

Source code in app/ui/modals/session.py
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
@on(Button.Pressed, "#btn-clean")
def action_clean(self) -> None:
    """Clean currently selected session."""
    selected = self.get_selected_session()
    if not selected:
        return
    sid = selected.get("session_id", "Unknown")
    app_clean = getattr(self.app, "_do_recovery_clean", None)
    if callable(app_clean):
        try:
            app_clean(selected)
        except Exception as e:
            logger.error(f"Error cleaning session {sid}: {e}")
    else:
        from app.core.session_catalog import forget_abandoned_session

        try:
            forget_abandoned_session(selected)
        except Exception as e:
            logger.error(f"Error cleaning session {sid}: {e}")

    self.announce(f"Cleaned session files for '{sid}'.")
    self.sessions = [s for s in self.sessions if s.get("session_id") != sid]
    self._refresh_table()
    if not self.sessions:
        self.dismiss(RecoveryResult("clean", session=selected, sessions=[]))

action_clean_all()

Confirm clean all action.

Source code in app/ui/modals/session.py
533
534
535
536
537
@on(Button.Pressed, "#btn-clean-all")
def action_clean_all(self) -> None:
    """Confirm clean all action."""
    self.announce("Confirmed cleanup of all abandoned sessions.")
    self.dismiss(RecoveryResult("clean_all", sessions=list(self.sessions)))

action_resume()

Confirm resume action for the selected session.

Source code in app/ui/modals/session.py
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
@on(Button.Pressed, "#btn-resume")
def action_resume(self) -> None:
    """Confirm resume action for the selected session."""
    selected = self.get_selected_session()
    if not selected:
        return
    if not self._session_can_resume(selected):
        self.announce(
            "Cannot resume an incomplete undo session. Choose Rollback or Clean."
        )
        return
    sid = selected.get("session_id", "Unknown")
    self.announce(f"Confirmed resume for session '{sid}'.")
    self.dismiss(
        RecoveryResult("resume", session=selected, sessions=list(self.sessions))
    )

action_rollback()

Rollback currently selected session.

Source code in app/ui/modals/session.py
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
@on(Button.Pressed, "#btn-rollback")
def action_rollback(self) -> None:
    """Rollback currently selected session."""
    selected = self.get_selected_session()
    if not selected:
        return
    sid = selected.get("session_id", "Unknown")
    app_rollback = getattr(self.app, "_do_recovery_rollback", None)
    if callable(app_rollback):
        outcome = app_rollback(selected)
        succeeded = outcome is not False
    else:
        from app.core.session_catalog import roll_back_abandoned_session

        settings = getattr(self, "settings", None) or getattr(
            self.app, "settings", None
        )
        succeeded = (
            bool(roll_back_abandoned_session(settings, selected))
            if settings
            else False
        )
        action_scan = getattr(self.app, "action_scan_directory", None)
        if callable(action_scan):
            try:
                action_scan()
            except Exception:
                pass

    if not succeeded:
        self.announce(
            f"Session recovery failed for '{sid}': write/permission error. Session files and safety storage preserved."
        )
        return

    self.announce(f"Rolled back session '{sid}'.")
    self.sessions = [s for s in self.sessions if s.get("session_id") != sid]
    self._refresh_table()
    if not self.sessions:
        self.dismiss(RecoveryResult("rollback", session=selected, sessions=[]))

action_rollback_all()

Confirm rollback all action.

Source code in app/ui/modals/session.py
539
540
541
542
543
@on(Button.Pressed, "#btn-rollback-all")
def action_rollback_all(self) -> None:
    """Confirm rollback all action."""
    self.announce("Confirmed rollback of all abandoned sessions.")
    self.dismiss(RecoveryResult("rollback_all", sessions=list(self.sessions)))

compose()

Compose multi-session recovery modal widgets.

Source code in app/ui/modals/session.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
def compose(self) -> ComposeResult:
    """Compose multi-session recovery modal widgets."""
    with ModalBox(classes="modal-box"):
        yield Heading(
            "Multiple Interrupted Sessions Detected",
            level=1,
            classes="modal-title",
            id="modal-title",
        )
        with Vertical(classes="modal-body"):
            yield Label(
                "Sortify detected multiple interrupted sessions. Review or perform batch recovery:",
                classes="modal-subtitle",
                id="modal-subtitle",
            )

            yield DataTable(id="sessions-table")

            yield Label(
                "Selected: None",
                id="lbl-selected-session",
            )

        with Vertical(classes="modal-footer"):
            yield Heading("Batch Actions:", level=2, classes="actions-heading")
            with Horizontal(classes="button-row batch-button-row"):
                btn_rollback_all = Button(
                    "Rollback All", id="btn-rollback-all", variant="warning"
                )
                btn_rollback_all.tooltip = (
                    "Rollback uncommitted operations across all abandoned sessions"
                )
                yield btn_rollback_all

                btn_clean_all = Button(
                    "Clean All", id="btn-clean-all", variant="error"
                )
                btn_clean_all.tooltip = (
                    "Discard all abandoned sessions and clean records"
                )
                yield btn_clean_all

            yield Heading(
                "Item Actions (Selected Session):",
                level=2,
                classes="actions-heading",
            )
            with Horizontal(classes="button-row item-button-row"):
                btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
                btn_cancel.tooltip = "Cancel recovery dialog"
                yield btn_cancel

                btn_help = Button("Help", id="btn-help", variant="default")
                btn_help.tooltip = "Open session recovery troubleshooting guide"
                yield btn_help

                btn_clean = Button("Clean", id="btn-clean", variant="error")
                btn_clean.tooltip = (
                    "Discard selected session files and clean record"
                )
                yield btn_clean

                btn_rollback = Button(
                    "Rollback", id="btn-rollback", variant="warning"
                )
                btn_rollback.tooltip = (
                    "Rollback partial file moves for selected session"
                )
                yield btn_rollback

                btn_resume = Button("Resume", id="btn-resume", variant="primary")
                btn_resume.tooltip = (
                    "Resume pending file moves for selected session"
                )
                yield btn_resume

get_selected_session()

Return the currently selected session dictionary.

Source code in app/ui/modals/session.py
461
462
463
464
465
466
467
468
469
470
471
472
def get_selected_session(self) -> dict[str, Any] | None:
    """Return the currently selected session dictionary."""
    if not self.sessions:
        return None
    with contextlib.suppress(QueryError, AppError, ScreenError):
        table = self.query_one("#sessions-table", DataTable)
        row_idx = table.cursor_row
        if row_idx is not None and 0 <= row_idx < len(self.sessions):
            self.selected_index = row_idx
    if 0 <= self.selected_index < len(self.sessions):
        return self.sessions[self.selected_index]
    return self.sessions[0]

on_mount()

Initialize table columns, populate rows, and announce session count.

Source code in app/ui/modals/session.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
def on_mount(self) -> None:
    """Initialize table columns, populate rows, and announce session count."""
    super().on_mount()
    table = self.query_one("#sessions-table", DataTable)
    table.cursor_type = "row"
    table.add_columns("Session ID", "Target Directory", "Step Count", "Status")
    self._refresh_table()
    count = len(self.sessions)
    selected = self.get_selected_session()
    conflict_note = (
        f" {selected['conflict_summary']}"
        if selected and selected.get("conflict_summary")
        else ""
    )
    self.announce(
        f"Opened multi-session recovery dialog. Detected {count} abandoned sessions.{conflict_note}"
    )
    with contextlib.suppress(QueryError, AppError, ScreenError):
        btn_resume = self.query_one("#btn-resume", Button)
        if btn_resume.display and not btn_resume.disabled:
            btn_resume.focus()
        else:
            self.query_one("#btn-rollback", Button).focus()

RecoveryResult

Bases: str

Result returned when session recovery modal dismisses with an action.

Source code in app/ui/modals/session.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
class RecoveryResult(str):
    """Result returned when session recovery modal dismisses with an action."""

    action: str
    session: dict[str, Any] | None
    sessions: list[dict[str, Any]]

    def __new__(
        cls,
        action: str,
        session: dict[str, Any] | None = None,
        sessions: list[dict[str, Any]] | None = None,
    ):
        """Instantiate recovery result string with action and session context."""
        obj = super().__new__(cls, action)
        obj.action = action
        obj.session = session
        obj.sessions = sessions or []
        return obj

__new__(action, session=None, sessions=None)

Instantiate recovery result string with action and session context.

Source code in app/ui/modals/session.py
224
225
226
227
228
229
230
231
232
233
234
235
def __new__(
    cls,
    action: str,
    session: dict[str, Any] | None = None,
    sessions: list[dict[str, Any]] | None = None,
):
    """Instantiate recovery result string with action and session context."""
    obj = super().__new__(cls, action)
    obj.action = action
    obj.session = session
    obj.sessions = sessions or []
    return obj

RollbackConfirmModal

Bases: ResponsiveModalScreen[dict[str, Any] | None]

Consolidated pre-flight review and confirmation dialog before executing session undo.

Source code in app/ui/modals/session.py
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
class RollbackConfirmModal(ResponsiveModalScreen[dict[str, Any] | None]):
    """Consolidated pre-flight review and confirmation dialog before executing session undo."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel rollback dialog", show=True),
        Binding("space", "toggle_current_row", "Toggle selection", show=False),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .confirm-box {
        border: thick $warning;
        width: 94%;
        max-width: 108;
        height: 92%;
        max-height: 94%;
    }
    .modal-body {
        height: 1fr;
        overflow-y: auto;
    }
    .modal-title {
        color: $warning;
        margin-bottom: 0;
    }
    .error-banner {
        color: $error;
        background: $boost;
        border: solid $error;
        padding: 0 1;
        margin-top: 0;
        margin-bottom: 0;
        text-style: bold;
        display: none;
    }
    .controls-row {
        width: 100%;
        height: auto;
        margin-top: 0;
        margin-bottom: 1;
        layout: horizontal;
    }
    #rollback-search-input {
        width: 1fr;
        margin-right: 1;
    }
    .bulk-actions-row {
        width: auto;
        height: auto;
        layout: horizontal;
    }
    .bulk-btn {
        min-width: 10;
        margin-right: 1;
    }
    .summary-bar {
        width: 100%;
        height: auto;
        margin-top: 0;
        margin-bottom: 0;
        background: $surface;
        border: solid $accent;
        padding: 0 1;
        layout: grid;
        grid-size: 3;
        grid-columns: 1fr 1fr 1fr;
        grid-gutter: 0 2;
    }
    .summary-stat {
        width: auto;
        text-style: bold;
    }
    #lbl-selection-count {
        color: $accent;
    }
    .summary-stat.clean {
        color: $success;
    }
    .summary-stat.collision {
        color: $error;
    }
    .summary-stat.mismatch {
        color: $error;
    }
    .summary-stat.missing {
        color: $warning;
    }
    #rollback-items-table {
        width: 100%;
        height: 1fr;
        min-height: 6;
        border: solid $primary;
        margin-bottom: 0;
    }
    .warning-box {
        width: 100%;
        margin-top: 0;
        margin-bottom: 0;
        padding: 0 1;
        background: $boost;
        border: dashed $warning;
        color: $text;
        height: auto;
    }
    .warning-box Label {
        width: 100%;
    }
    #chk-ignore-missing {
        margin-top: 0;
        margin-bottom: 0;
    }
    .button-row {
        layout: grid;
        grid-size: 2;
        grid-columns: 1fr 1fr;
        grid-gutter: 0 1;
        margin-top: 0;
    }
    .button-row Button {
        width: 100%;
        min-width: 0;
        margin: 0;
    }
    Button:focus, Input:focus, DataTable:focus, Checkbox:focus {
        border: heavy $accent;
        text-style: bold;
    }
    RollbackConfirmModal {
        background: rgba(0, 0, 0, 0.7);
        &.compact .confirm-box, &.narrow .confirm-box {
            padding: 0 1;
            width: 98%;
            height: 96%;
            max-height: 98%;
        }
        &.compact .controls-row, &.narrow .controls-row {
            layout: vertical;
            margin-top: 0;
            margin-bottom: 0;
        }
        &.compact #rollback-search-input {
            width: 100%;
            margin-right: 0;
            height: 1;
            min-height: 1;
            border: none;
            padding: 0 1;
        }
        &.narrow #rollback-search-input {
            width: 100%;
            margin-right: 0;
        }
        &.compact .bulk-actions-row {
            width: 100%;
            layout: grid;
            grid-size: 4;
            grid-columns: 1fr 1fr 1fr 1fr;
            grid-gutter: 0 1;
        }
        &.narrow .bulk-actions-row {
            width: 100%;
            layout: grid;
            grid-size: 2;
            grid-columns: 1fr 1fr;
            grid-gutter: 0 1;
        }
        &.compact .bulk-btn, &.narrow .bulk-btn {
            width: 100%;
            min-width: 0;
            margin-right: 0;
            height: 1;
            min-height: 1;
            border: none;
        }
        &.compact .summary-bar {
            margin-top: 0;
            margin-bottom: 0;
            border: none;
            padding: 0;
            layout: grid;
            grid-size: 3;
            grid-columns: 1fr 1fr 1fr;
            grid-gutter: 0 1;
        }
        &.narrow .summary-bar {
            margin-top: 0;
            margin-bottom: 0;
            border: none;
            padding: 0;
            layout: grid;
            grid-size: 2;
            grid-columns: 1fr 1fr;
            grid-gutter: 0 1;
        }
        &.compact #rollback-items-table {
            margin-bottom: 0;
            min-height: 5;
        }
        &.compact .warning-box {
            margin-top: 0;
            margin-bottom: 0;
            border: none;
            padding: 0;
        }
        &.compact #chk-ignore-missing {
            height: 1;
            min-height: 1;
            border: none;
            padding: 0;
        }
        &.compact .button-row {
            margin-top: 0;
        }
        &.compact .button-row Button {
            height: 1;
            min-height: 1;
            border: none;
        }
    }
    """

    def __init__(self, session_info: dict[str, Any]):
        super().__init__()
        self.session_info = session_info
        self.all_items: list[dict[str, Any]] = list(session_info.get("items") or [])
        self.selected_step_ids: set[Any] = set()
        self.filtered_items: list[dict[str, Any]] = []
        self.history_error: str | None = None
        self.preview_data: dict[str, Any] | None = None
        self._step_preview_by_id: dict[str, dict[str, Any]] = {}

    def _is_trash_only_session(self) -> bool:
        step_cnt = int(self.session_info.get("step_count") or 0)
        trashed_cnt = int(self.session_info.get("trashed_count") or 0)
        return step_cnt == 0 and trashed_cnt > 0 and not self.all_items

    def compose(self) -> ComposeResult:
        """Compose unified pre-flight undo and recovery review widgets."""
        sid = self.session_info.get("session_id", "unknown")
        b_dir = self.session_info.get("base_dir") or "N/A"
        ts = self.session_info.get("timestamp")
        ts_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts)) if ts else "N/A"

        with ModalBox(classes="confirm-box modal-box"):
            yield Heading(
                "Pre-Flight Undo & Recovery Review",
                level=1,
                classes="modal-title",
                id="confirm-title",
            )
            yield Label(
                f"Session ID: {sid} | Base Dir: {b_dir} | Date: {ts_str}",
                id="lbl-confirm-sid",
            )
            yield Static("", id="rollback-error-banner", classes="error-banner")

            with Vertical(classes="modal-body"):
                with Horizontal(classes="controls-row"):
                    inp = Input(
                        placeholder="Filter steps by path or pre-flight status...",
                        id="rollback-search-input",
                    )
                    inp.tooltip = "Filter undo steps by source/target path or status"
                    yield inp
                    with Horizontal(classes="bulk-actions-row"):
                        btn_all = Button(
                            "Select All",
                            id="btn-select-all",
                            classes="bulk-btn",
                            variant="primary",
                        )
                        btn_all.tooltip = "Select all visible undo steps"
                        yield btn_all

                        btn_none = Button(
                            "Deselect All",
                            id="btn-deselect-all",
                            classes="bulk-btn",
                            variant="default",
                        )
                        btn_none.tooltip = "Deselect all visible undo steps"
                        yield btn_none

                        btn_inv = Button(
                            "Invert Selection",
                            id="btn-invert-selection",
                            classes="bulk-btn",
                            variant="default",
                        )
                        btn_inv.tooltip = "Invert selection across visible undo steps"
                        yield btn_inv

                        btn_clean = Button(
                            "Select Clean Only",
                            id="btn-select-clean",
                            classes="bulk-btn",
                            variant="success",
                        )
                        btn_clean.tooltip = "Select only clean unmodified steps (skip hash mismatches and missing targets)"
                        yield btn_clean

                with Horizontal(classes="summary-bar", id="preflight-summary-bar"):
                    yield Label(
                        "Selected for Undo: 0 items",
                        id="lbl-selection-count",
                        classes="summary-stat",
                    )
                    yield Label(
                        "Total: 0",
                        id="lbl-summary-total",
                        classes="summary-stat",
                    )
                    yield Label(
                        "Clean: 0",
                        id="lbl-summary-clean",
                        classes="summary-stat clean",
                    )
                    yield Label(
                        "Hash Mismatches: 0",
                        id="lbl-summary-hash-mismatches",
                        classes="summary-stat mismatch",
                    )
                    yield Label(
                        "Collisions: 0",
                        id="lbl-summary-collisions",
                        classes="summary-stat collision",
                    )
                    yield Label(
                        "Missing: 0",
                        id="lbl-summary-missing",
                        classes="summary-stat missing",
                    )

                table = DataTable(id="rollback-items-table")
                table.tooltip = (
                    "Pre-flight undo steps table (Space or Enter toggles selection)"
                )
                yield table

                with Vertical(classes="warning-box", id="rollback-guidance-box"):
                    yield Label(
                        "Checking target integrity, path collisions, and missing files...",
                        id="rollback-guidance-banner",
                    )
                    trashed_cnt = int(self.session_info.get("trashed_count") or 0)
                    if trashed_cnt > 0:
                        noun = "copy" if trashed_cnt == 1 else "copies"
                        verb_rem = "remains" if trashed_cnt == 1 else "remain"
                        yield Label(
                            f"⚠️ {trashed_cnt} duplicate {noun} in this session {verb_rem} in OS Trash and cannot be restored automatically.",
                            id="lbl-trashed-warning",
                        )

                if self._is_trash_only_session():
                    yield Label(
                        "Files that are no longer at their sorted location are skipped.",
                        id="lbl-confirm-missing",
                    )
                else:
                    chk = Checkbox(
                        "Allow missing targets (finalize undo and skip missing files)",
                        value=False,
                        id="chk-ignore-missing",
                    )
                    chk.tooltip = "When enabled, missing sorted files are skipped and the session transitions to Rolled Back"
                    yield chk

            with Horizontal(classes="button-row"):
                btn_cancel = Button(
                    "Cancel", id="btn-cancel-rollback", variant="default"
                )
                btn_cancel.tooltip = "Cancel and close pre-flight undo review"
                yield btn_cancel

                btn_confirm = Button(
                    "Execute Undo",
                    id="btn-confirm-rollback",
                    variant="error",
                )
                btn_confirm.tooltip = "Execute undo for the selected steps"
                yield btn_confirm

    def on_mount(self) -> None:
        """Initialize items, run pre-flight simulation, populate table and focus controls."""
        super().on_mount()
        sid = self.session_info.get("session_id")
        if not self.all_items and sid:
            try:
                from app.core.session_catalog import get_session_moves

                self.all_items = get_session_moves(sid)
            except Exception as exc:
                logger.exception(
                    "Failed to load session history for rollback modal: %s", exc
                )
                self.all_items = []
                raw_msg = str(exc) or "Failed to load session history."
                sanitized_msg = sanitize_secret_patterns(scrub_user_home_paths(raw_msg))
                self.history_error = f"Error loading session history: {sanitized_msg}"

        if self.history_error:
            try:
                banner = self.query_one("#rollback-error-banner", Static)
                banner.update(f"⚠️ {self.history_error}")
                banner.display = True
            except Exception:
                pass

            try:
                btn_confirm = self.query_one("#btn-confirm-rollback", Button)
                btn_confirm.disabled = True
                btn_confirm.tooltip = (
                    "Cannot confirm undo because session history failed to load."
                )
            except Exception:
                pass

            notify(self.history_error, type="error")
            self.announce(self.history_error, priority="assertive")

        self.selected_step_ids = {item["step_id"] for item in self.all_items}

        dt1 = self.query_one("#rollback-items-table", DataTable)
        dt1.cursor_type = "row"
        dt1.add_columns(
            "Sel",
            "ID",
            "Pre-Flight Status",
            "Original Source Path",
            "Target Sorted Path",
            "Restoration Path",
        )

        self._run_full_preflight()
        self._refresh_table()

        if self.history_error:
            with contextlib.suppress(QueryError, AppError, ScreenError):
                self.query_one("#btn-cancel-rollback", Button).focus()
        else:
            with contextlib.suppress(QueryError, AppError, ScreenError):
                self.query_one("#btn-confirm-rollback", Button).focus()

        raw_mount_summ = (self.preview_data or {}).get("summary")
        summ = raw_mount_summ if isinstance(raw_mount_summ, dict) else {}
        mismatch_cnt = int(summ.get("hash_mismatch") or 0)
        missing_cnt = int(summ.get("missing_target") or 0)
        collision_cnt = int(summ.get("collision") or 0)
        if mismatch_cnt or missing_cnt or collision_cnt:
            self.announce(
                f"Opened pre-flight undo review: {mismatch_cnt} hash mismatch(es), "
                f"{missing_cnt} missing target(s), {collision_cnt} collision(s)."
            )
        else:
            self.announce("Opened undo confirmation modal dialog.")

    def _get_allow_missing_value(self) -> bool:
        checkboxes = self.query("#chk-ignore-missing").results(Checkbox)
        chk = next(iter(checkboxes), None)
        return bool(chk.value) if chk else False

    def _run_full_preflight(self) -> None:
        """Simulate pre-flight status across all session moves."""
        from app.core.session_catalog import preview_session_rollback

        sid = self.session_info.get("session_id")
        allow_missing = self._get_allow_missing_value()
        try:
            full_preview = preview_session_rollback(
                sid,
                selected_step_ids=None,
                ignore_missing=allow_missing,
                allow_missing=allow_missing,
                fallback_items=self.all_items,
            )
        except (OSError, ValueError, TypeError, RuntimeError):
            full_preview = {
                "steps": [],
                "summary": {
                    "total": 0,
                    "clean": 0,
                    "collision": 0,
                    "missing_target": 0,
                    "hash_mismatch": 0,
                    "identical_exists": 0,
                },
            }
        raw_steps = full_preview.get("steps")
        step_map: dict[str, dict[str, Any]] = {}
        if isinstance(raw_steps, list):
            for step in raw_steps:
                if isinstance(step, dict):
                    step_map[str(step.get("step_id"))] = step
        self._step_preview_by_id = step_map

    def _compute_dryrun_preview(self) -> dict[str, Any]:
        """Compute dry-run simulation preview for the currently selected steps."""
        from app.core.session_catalog import preview_session_rollback

        sid = self.session_info.get("session_id")
        allow_missing = self._get_allow_missing_value()
        selected_ids = list(self.selected_step_ids) if self.selected_step_ids else []
        return preview_session_rollback(
            sid,
            selected_step_ids=selected_ids,
            ignore_missing=allow_missing,
            allow_missing=allow_missing,
            fallback_items=self.all_items,
        )

    @staticmethod
    def _format_status_badge(status: str) -> str:
        if status == "HASH_MISMATCH":
            return "[bold red]HASH_MISMATCH[/bold red]"
        if status == "COLLISION":
            return "[bold red]COLLISION[/bold red]"
        if status == "MISSING_TARGET":
            return "[bold yellow]MISSING_TARGET[/bold yellow]"
        if status == "IDENTICAL_EXISTS":
            return "[bold cyan]IDENTICAL_EXISTS[/bold cyan]"
        return "[bold green]CLEAN[/bold green]"

    def _refresh_table(self) -> None:
        dt = self.query_one("#rollback-items-table", DataTable)
        dt.clear()

        query = ""
        with contextlib.suppress(QueryError, AppError, ScreenError):
            inp = self.query_one("#rollback-search-input", Input)
            query = inp.value.strip().lower()

        self.filtered_items = []
        for item in self.all_items:
            sid_str = str(item.get("step_id"))
            step_prev = self._step_preview_by_id.get(sid_str, {})
            src = str(item.get("source_path", ""))
            dst = str(item.get("target_path", ""))
            rest = str(step_prev.get("restoration_path") or src)
            pf_stat = str(step_prev.get("status") or "CLEAN")
            raw_stat = str(item.get("status", ""))
            if not query or (
                query in src.lower()
                or query in dst.lower()
                or query in rest.lower()
                or query in pf_stat.lower()
                or query in raw_stat.lower()
            ):
                self.filtered_items.append(item)

        base_dir = str(self.session_info.get("base_dir") or "").strip()

        def _compact_path(raw_p: str) -> str:
            if not raw_p or not base_dir:
                return raw_p
            with contextlib.suppress(ValueError):
                rel = os.path.relpath(raw_p, base_dir)
                if not rel.startswith(".."):
                    return rel
            return raw_p

        for item in self.filtered_items:
            sid = item["step_id"]
            sid_str = str(sid)
            step_prev = self._step_preview_by_id.get(sid_str, {})
            chk = "[X]" if sid in self.selected_step_ids else "[ ]"
            src = _compact_path(str(item.get("source_path", "")))
            dst = _compact_path(str(item.get("target_path", "")))
            rest = _compact_path(str(step_prev.get("restoration_path") or src))
            pf_stat = str(step_prev.get("status") or "CLEAN")

            dt.add_row(
                chk,
                sid_str,
                self._format_status_badge(pf_stat),
                src,
                dst,
                rest,
                key=sid_str,
            )

        self._update_summary_and_guidance()

    def _update_summary_and_guidance(self) -> None:
        total_all = len(self.all_items)
        selected_cnt = len(self.selected_step_ids)
        with contextlib.suppress(QueryError, AppError, ScreenError):
            lbl = self.query_one("#lbl-selection-count", Label)
            lbl.update(f"Selected for Undo: {selected_cnt} / {total_all} items")

        try:
            preview = self._compute_dryrun_preview()
        except (OSError, ValueError, TypeError, RuntimeError):
            preview = {
                "steps": [],
                "summary": {
                    "total": selected_cnt,
                    "clean": 0,
                    "collision": 0,
                    "missing_target": 0,
                    "hash_mismatch": 0,
                    "identical_exists": 0,
                },
            }
        self.preview_data = preview
        raw_summ = preview.get("summary")
        summ: dict[str, Any] = raw_summ if isinstance(raw_summ, dict) else {}
        total_ops = int(summ.get("total", 0))
        clean_cnt = int(summ.get("clean", 0)) + int(summ.get("identical_exists", 0))
        mismatch_cnt = int(summ.get("hash_mismatch", 0))
        collision_cnt = int(summ.get("collision", 0))
        missing_cnt = int(summ.get("missing_target", 0))

        for widget_id, text in (
            ("#lbl-summary-total", f"Total: {total_ops}"),
            ("#lbl-summary-clean", f"Clean: {clean_cnt}"),
            ("#lbl-summary-hash-mismatches", f"Hash Mismatches: {mismatch_cnt}"),
            ("#lbl-summary-collisions", f"Collisions: {collision_cnt}"),
            ("#lbl-summary-missing", f"Missing: {missing_cnt}"),
        ):
            with contextlib.suppress(QueryError, AppError, ScreenError):
                self.query_one(widget_id, Label).update(text)

        allow_missing = self._get_allow_missing_value()
        with contextlib.suppress(QueryError, AppError, ScreenError):
            guidance_lbl = self.query_one("#rollback-guidance-banner", Label)
            if mismatch_cnt > 0:
                guidance_lbl.update(
                    f"⚠️ Safety Guard: {mismatch_cnt} modified file(s) have SHA-256 hash mismatches and will remain untouched. Use 'Select Clean Only' to restore unmodified files safely."
                )
            elif missing_cnt > 0 and not allow_missing:
                guidance_lbl.update(
                    f"⚠️ Missing Targets: {missing_cnt} file(s) are missing. Clean files restore while missing steps remain in Partially Rolled Back unless 'Allow missing targets' is enabled."
                )
            elif missing_cnt > 0 and allow_missing:
                guidance_lbl.update(
                    f"⚠️ Allow Missing Active: {missing_cnt} missing file(s) will be skipped and the session finalized as Rolled Back."
                )
            elif collision_cnt > 0:
                guidance_lbl.update(
                    f"⚠️ Collision Warning: {collision_cnt} original path(s) are occupied and will restore with non-destructive suffixes."
                )
            elif selected_cnt == 0 and total_all > 0:
                guidance_lbl.update(
                    "Select at least one step to undo, or press Cancel."
                )
            else:
                guidance_lbl.update(
                    "✅ Pre-flight simulation clean. Checked files will restore to their original locations."
                )

    @on(Checkbox.Changed, "#chk-ignore-missing")
    def _on_allow_missing_changed(self, event: Checkbox.Changed) -> None:
        self._run_full_preflight()
        self._refresh_table()

    @on(Input.Changed, "#rollback-search-input")
    def _on_search_changed(self, event: Input.Changed) -> None:
        self._refresh_table()

    @on(Button.Pressed, "#btn-select-all")
    def action_select_all(self) -> None:
        """Select all items in filtered table view."""
        for item in getattr(self, "filtered_items", self.all_items):
            self.selected_step_ids.add(item["step_id"])
        self._refresh_table()
        self.announce("Selected all items for undo.")

    @on(Button.Pressed, "#btn-deselect-all")
    def action_deselect_all(self) -> None:
        """Deselect all items in filtered table view."""
        for item in getattr(self, "filtered_items", self.all_items):
            self.selected_step_ids.discard(item["step_id"])
        self._refresh_table()
        self.announce("Deselected all items for undo.")

    @on(Button.Pressed, "#btn-invert-selection")
    def action_invert_selection(self) -> None:
        """Invert selection state of all items in filtered table view."""
        for item in getattr(self, "filtered_items", self.all_items):
            sid = item["step_id"]
            if sid in self.selected_step_ids:
                self.selected_step_ids.remove(sid)
            else:
                self.selected_step_ids.add(sid)
        self._refresh_table()
        self.announce("Inverted item selection.")

    @on(Button.Pressed, "#btn-select-clean")
    def action_select_clean_only(self) -> None:
        """Select only steps without hash mismatches or missing targets."""
        clean_ids: set[Any] = set()
        for item in self.all_items:
            sid = item["step_id"]
            step_prev = self._step_preview_by_id.get(str(sid), {})
            st = str(step_prev.get("status") or "CLEAN")
            if st in ("CLEAN", "IDENTICAL_EXISTS", "COLLISION"):
                clean_ids.add(sid)
        self.selected_step_ids = clean_ids
        self._refresh_table()
        self.announce(
            f"Selected {len(clean_ids)} clean restorable item(s); excluded conflicted and missing items."
        )

    @on(DataTable.RowSelected, "#rollback-items-table")
    def _on_row_selected(self, event: DataTable.RowSelected) -> None:
        row_key = event.row_key.value
        if not row_key:
            return
        self._toggle_item_by_key(str(row_key))

    def action_toggle_current_row(self) -> None:
        """Toggle selection state for the currently focused table row."""
        dt = self.query_one("#rollback-items-table", DataTable)
        if dt.has_focus and dt.cursor_row is not None:
            try:
                row_key, _ = dt.coordinate_to_cell_key(Coordinate(dt.cursor_row, 0))
                if row_key and row_key.value:
                    self._toggle_item_by_key(str(row_key.value))
            except Exception:
                pass

    def _toggle_item_by_key(self, key_str: str) -> None:
        target_id = None
        for item in self.all_items:
            if str(item["step_id"]) == key_str:
                target_id = item["step_id"]
                break

        if target_id is not None:
            if target_id in self.selected_step_ids:
                self.selected_step_ids.remove(target_id)
            else:
                self.selected_step_ids.add(target_id)
            self._refresh_table()

    @on(Button.Pressed, "#btn-confirm-rollback")
    def action_confirm(self) -> None:
        """Confirm rollback action and dismiss modal with parameters."""
        try:
            btn = self.query_one("#btn-confirm-rollback", Button)
            if btn.disabled or self.history_error is not None:
                return
        except Exception:
            if self.history_error is not None:
                return

        allow_missing = self._get_allow_missing_value()

        selected_ids = None
        if self.all_items and len(self.selected_step_ids) < len(self.all_items):
            selected_ids = list(self.selected_step_ids)

        self.dismiss(
            {
                "confirmed": True,
                "session_id": self.session_info.get("session_id"),
                "ignore_missing": allow_missing,
                "allow_missing": allow_missing,
                "selected_step_ids": selected_ids,
            }
        )

    @on(Button.Pressed, "#btn-cancel-rollback")
    def action_cancel(self) -> None:
        """Cancel rollback confirmation dialog."""
        self.dismiss(None)

action_cancel()

Cancel rollback confirmation dialog.

Source code in app/ui/modals/session.py
1400
1401
1402
1403
@on(Button.Pressed, "#btn-cancel-rollback")
def action_cancel(self) -> None:
    """Cancel rollback confirmation dialog."""
    self.dismiss(None)

action_confirm()

Confirm rollback action and dismiss modal with parameters.

Source code in app/ui/modals/session.py
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
@on(Button.Pressed, "#btn-confirm-rollback")
def action_confirm(self) -> None:
    """Confirm rollback action and dismiss modal with parameters."""
    try:
        btn = self.query_one("#btn-confirm-rollback", Button)
        if btn.disabled or self.history_error is not None:
            return
    except Exception:
        if self.history_error is not None:
            return

    allow_missing = self._get_allow_missing_value()

    selected_ids = None
    if self.all_items and len(self.selected_step_ids) < len(self.all_items):
        selected_ids = list(self.selected_step_ids)

    self.dismiss(
        {
            "confirmed": True,
            "session_id": self.session_info.get("session_id"),
            "ignore_missing": allow_missing,
            "allow_missing": allow_missing,
            "selected_step_ids": selected_ids,
        }
    )

action_deselect_all()

Deselect all items in filtered table view.

Source code in app/ui/modals/session.py
1305
1306
1307
1308
1309
1310
1311
@on(Button.Pressed, "#btn-deselect-all")
def action_deselect_all(self) -> None:
    """Deselect all items in filtered table view."""
    for item in getattr(self, "filtered_items", self.all_items):
        self.selected_step_ids.discard(item["step_id"])
    self._refresh_table()
    self.announce("Deselected all items for undo.")

action_invert_selection()

Invert selection state of all items in filtered table view.

Source code in app/ui/modals/session.py
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
@on(Button.Pressed, "#btn-invert-selection")
def action_invert_selection(self) -> None:
    """Invert selection state of all items in filtered table view."""
    for item in getattr(self, "filtered_items", self.all_items):
        sid = item["step_id"]
        if sid in self.selected_step_ids:
            self.selected_step_ids.remove(sid)
        else:
            self.selected_step_ids.add(sid)
    self._refresh_table()
    self.announce("Inverted item selection.")

action_select_all()

Select all items in filtered table view.

Source code in app/ui/modals/session.py
1297
1298
1299
1300
1301
1302
1303
@on(Button.Pressed, "#btn-select-all")
def action_select_all(self) -> None:
    """Select all items in filtered table view."""
    for item in getattr(self, "filtered_items", self.all_items):
        self.selected_step_ids.add(item["step_id"])
    self._refresh_table()
    self.announce("Selected all items for undo.")

action_select_clean_only()

Select only steps without hash mismatches or missing targets.

Source code in app/ui/modals/session.py
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
@on(Button.Pressed, "#btn-select-clean")
def action_select_clean_only(self) -> None:
    """Select only steps without hash mismatches or missing targets."""
    clean_ids: set[Any] = set()
    for item in self.all_items:
        sid = item["step_id"]
        step_prev = self._step_preview_by_id.get(str(sid), {})
        st = str(step_prev.get("status") or "CLEAN")
        if st in ("CLEAN", "IDENTICAL_EXISTS", "COLLISION"):
            clean_ids.add(sid)
    self.selected_step_ids = clean_ids
    self._refresh_table()
    self.announce(
        f"Selected {len(clean_ids)} clean restorable item(s); excluded conflicted and missing items."
    )

action_toggle_current_row()

Toggle selection state for the currently focused table row.

Source code in app/ui/modals/session.py
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
def action_toggle_current_row(self) -> None:
    """Toggle selection state for the currently focused table row."""
    dt = self.query_one("#rollback-items-table", DataTable)
    if dt.has_focus and dt.cursor_row is not None:
        try:
            row_key, _ = dt.coordinate_to_cell_key(Coordinate(dt.cursor_row, 0))
            if row_key and row_key.value:
                self._toggle_item_by_key(str(row_key.value))
        except Exception:
            pass

compose()

Compose unified pre-flight undo and recovery review widgets.

Source code in app/ui/modals/session.py
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
def compose(self) -> ComposeResult:
    """Compose unified pre-flight undo and recovery review widgets."""
    sid = self.session_info.get("session_id", "unknown")
    b_dir = self.session_info.get("base_dir") or "N/A"
    ts = self.session_info.get("timestamp")
    ts_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts)) if ts else "N/A"

    with ModalBox(classes="confirm-box modal-box"):
        yield Heading(
            "Pre-Flight Undo & Recovery Review",
            level=1,
            classes="modal-title",
            id="confirm-title",
        )
        yield Label(
            f"Session ID: {sid} | Base Dir: {b_dir} | Date: {ts_str}",
            id="lbl-confirm-sid",
        )
        yield Static("", id="rollback-error-banner", classes="error-banner")

        with Vertical(classes="modal-body"):
            with Horizontal(classes="controls-row"):
                inp = Input(
                    placeholder="Filter steps by path or pre-flight status...",
                    id="rollback-search-input",
                )
                inp.tooltip = "Filter undo steps by source/target path or status"
                yield inp
                with Horizontal(classes="bulk-actions-row"):
                    btn_all = Button(
                        "Select All",
                        id="btn-select-all",
                        classes="bulk-btn",
                        variant="primary",
                    )
                    btn_all.tooltip = "Select all visible undo steps"
                    yield btn_all

                    btn_none = Button(
                        "Deselect All",
                        id="btn-deselect-all",
                        classes="bulk-btn",
                        variant="default",
                    )
                    btn_none.tooltip = "Deselect all visible undo steps"
                    yield btn_none

                    btn_inv = Button(
                        "Invert Selection",
                        id="btn-invert-selection",
                        classes="bulk-btn",
                        variant="default",
                    )
                    btn_inv.tooltip = "Invert selection across visible undo steps"
                    yield btn_inv

                    btn_clean = Button(
                        "Select Clean Only",
                        id="btn-select-clean",
                        classes="bulk-btn",
                        variant="success",
                    )
                    btn_clean.tooltip = "Select only clean unmodified steps (skip hash mismatches and missing targets)"
                    yield btn_clean

            with Horizontal(classes="summary-bar", id="preflight-summary-bar"):
                yield Label(
                    "Selected for Undo: 0 items",
                    id="lbl-selection-count",
                    classes="summary-stat",
                )
                yield Label(
                    "Total: 0",
                    id="lbl-summary-total",
                    classes="summary-stat",
                )
                yield Label(
                    "Clean: 0",
                    id="lbl-summary-clean",
                    classes="summary-stat clean",
                )
                yield Label(
                    "Hash Mismatches: 0",
                    id="lbl-summary-hash-mismatches",
                    classes="summary-stat mismatch",
                )
                yield Label(
                    "Collisions: 0",
                    id="lbl-summary-collisions",
                    classes="summary-stat collision",
                )
                yield Label(
                    "Missing: 0",
                    id="lbl-summary-missing",
                    classes="summary-stat missing",
                )

            table = DataTable(id="rollback-items-table")
            table.tooltip = (
                "Pre-flight undo steps table (Space or Enter toggles selection)"
            )
            yield table

            with Vertical(classes="warning-box", id="rollback-guidance-box"):
                yield Label(
                    "Checking target integrity, path collisions, and missing files...",
                    id="rollback-guidance-banner",
                )
                trashed_cnt = int(self.session_info.get("trashed_count") or 0)
                if trashed_cnt > 0:
                    noun = "copy" if trashed_cnt == 1 else "copies"
                    verb_rem = "remains" if trashed_cnt == 1 else "remain"
                    yield Label(
                        f"⚠️ {trashed_cnt} duplicate {noun} in this session {verb_rem} in OS Trash and cannot be restored automatically.",
                        id="lbl-trashed-warning",
                    )

            if self._is_trash_only_session():
                yield Label(
                    "Files that are no longer at their sorted location are skipped.",
                    id="lbl-confirm-missing",
                )
            else:
                chk = Checkbox(
                    "Allow missing targets (finalize undo and skip missing files)",
                    value=False,
                    id="chk-ignore-missing",
                )
                chk.tooltip = "When enabled, missing sorted files are skipped and the session transitions to Rolled Back"
                yield chk

        with Horizontal(classes="button-row"):
            btn_cancel = Button(
                "Cancel", id="btn-cancel-rollback", variant="default"
            )
            btn_cancel.tooltip = "Cancel and close pre-flight undo review"
            yield btn_cancel

            btn_confirm = Button(
                "Execute Undo",
                id="btn-confirm-rollback",
                variant="error",
            )
            btn_confirm.tooltip = "Execute undo for the selected steps"
            yield btn_confirm

on_mount()

Initialize items, run pre-flight simulation, populate table and focus controls.

Source code in app/ui/modals/session.py
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
def on_mount(self) -> None:
    """Initialize items, run pre-flight simulation, populate table and focus controls."""
    super().on_mount()
    sid = self.session_info.get("session_id")
    if not self.all_items and sid:
        try:
            from app.core.session_catalog import get_session_moves

            self.all_items = get_session_moves(sid)
        except Exception as exc:
            logger.exception(
                "Failed to load session history for rollback modal: %s", exc
            )
            self.all_items = []
            raw_msg = str(exc) or "Failed to load session history."
            sanitized_msg = sanitize_secret_patterns(scrub_user_home_paths(raw_msg))
            self.history_error = f"Error loading session history: {sanitized_msg}"

    if self.history_error:
        try:
            banner = self.query_one("#rollback-error-banner", Static)
            banner.update(f"⚠️ {self.history_error}")
            banner.display = True
        except Exception:
            pass

        try:
            btn_confirm = self.query_one("#btn-confirm-rollback", Button)
            btn_confirm.disabled = True
            btn_confirm.tooltip = (
                "Cannot confirm undo because session history failed to load."
            )
        except Exception:
            pass

        notify(self.history_error, type="error")
        self.announce(self.history_error, priority="assertive")

    self.selected_step_ids = {item["step_id"] for item in self.all_items}

    dt1 = self.query_one("#rollback-items-table", DataTable)
    dt1.cursor_type = "row"
    dt1.add_columns(
        "Sel",
        "ID",
        "Pre-Flight Status",
        "Original Source Path",
        "Target Sorted Path",
        "Restoration Path",
    )

    self._run_full_preflight()
    self._refresh_table()

    if self.history_error:
        with contextlib.suppress(QueryError, AppError, ScreenError):
            self.query_one("#btn-cancel-rollback", Button).focus()
    else:
        with contextlib.suppress(QueryError, AppError, ScreenError):
            self.query_one("#btn-confirm-rollback", Button).focus()

    raw_mount_summ = (self.preview_data or {}).get("summary")
    summ = raw_mount_summ if isinstance(raw_mount_summ, dict) else {}
    mismatch_cnt = int(summ.get("hash_mismatch") or 0)
    missing_cnt = int(summ.get("missing_target") or 0)
    collision_cnt = int(summ.get("collision") or 0)
    if mismatch_cnt or missing_cnt or collision_cnt:
        self.announce(
            f"Opened pre-flight undo review: {mismatch_cnt} hash mismatch(es), "
            f"{missing_cnt} missing target(s), {collision_cnt} collision(s)."
        )
    else:
        self.announce("Opened undo confirmation modal dialog.")

RollbackErrorModal

Bases: ResponsiveModalScreen[None]

Modal dialog displaying error messages encountered during session rollback.

Source code in app/ui/modals/session.py
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
class RollbackErrorModal(ResponsiveModalScreen[None]):
    """Modal dialog displaying error messages encountered during session rollback."""

    HELP_URL = f"{TROUBLESHOOTING_URL}#session-recovery"

    BINDINGS = [
        Binding("escape", "close", "Close error dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .error-box {
        border: thick $error;
    }
    .modal-title {
        color: $error;
    }
    .error-text {
        margin-top: 1;
        margin-bottom: 1;
        color: $text;
    }
    .button-row Button {
        margin-left: 1;
    }
    Button:focus {
        border: heavy $accent;
        text-style: bold;
    }
    RollbackErrorModal {
        background: rgba(0, 0, 0, 0.7);
        &.compact .error-box, &.narrow .error-box {
            max-height: 96%;
        }
        &.compact .error-text {
            margin-top: 0;
            margin-bottom: 0;
        }
        &.narrow .button-row Button {
            min-width: 0;
            padding: 0 1;
        }
    }
    """

    def __init__(
        self,
        title: str = "Undo Failed",
        error_message: str = "",
        settings: Any = None,
    ):
        super().__init__()
        self.error_title = title
        self.error_message = error_message
        self.settings = settings
        self.help_url = f"{TROUBLESHOOTING_URL}#session-recovery"
        self.last_exported_diagnostics_path: str | None = None

    def compose(self) -> ComposeResult:
        """Compose error modal widgets."""
        with ModalBox(classes="error-box modal-box"):
            yield Heading(
                self.error_title, level=1, classes="modal-title", id="error-title"
            )
            with Vertical(classes="modal-body"):
                yield Label(
                    self.error_message, classes="error-text", id="lbl-error-message"
                )
            with Horizontal(classes="button-row"):
                btn_help = Button("Help", id="btn-help", variant="default")
                btn_help.tooltip = "Open session recovery troubleshooting guide"
                yield btn_help

                btn_export = Button(
                    "Export Diagnostics",
                    id="btn-export-diagnostics",
                    variant="warning",
                )
                btn_export.tooltip = "Export scrubbed diagnostic log report"
                yield btn_export

                btn_close = Button("Close", id="btn-close-error", variant="primary")
                btn_close.tooltip = "Close undo error dialog"
                yield btn_close

    def on_mount(self) -> None:
        """Focus close button and announce error message."""
        super().on_mount()
        self.query_one("#btn-close-error", Button).focus()
        self.announce(f"Error dialog: {self.error_title}")

    def _build_scrubbed_diagnostics_payload(self, settings_obj: Any) -> str:
        """Build a redacted diagnostic report from error context and ``settings.LOG_FILE``."""
        ts_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
        clean_title = scrub_diagnostic_text(str(self.error_title or "Undo Failed"))
        clean_error = scrub_diagnostic_text(str(self.error_message or ""))

        lines = [
            "Sortify Undo Diagnostic Report",
            f"Generated: {ts_iso}",
            f"Title: {clean_title}",
            f"Error: {clean_error}",
            "",
            "--- Application Log Excerpt ---",
        ]

        log_file_val = (
            getattr(settings_obj, "LOG_FILE", None)
            if settings_obj is not None
            else None
        )
        log_loaded = False
        if log_file_val:
            try:
                log_path = Path(str(log_file_val))
                if log_path.is_file():
                    raw_lines = log_path.read_text(
                        encoding="utf-8", errors="replace"
                    ).splitlines()
                    for raw_line in raw_lines[-500:]:
                        if "enc:" in raw_line:
                            continue
                        lines.append(scrub_diagnostic_text(raw_line))
                    log_loaded = True
            except OSError:
                log_loaded = False

        if not log_loaded:
            lines.append("Application log file unavailable or absent on disk.")

        return "\n".join(lines) + "\n"

    def _write_secure_diagnostic_file(self, payload: str, app_obj: Any) -> str:
        """Write diagnostic payload with ``0o600`` permissions across fallback directories."""
        stamp = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
        filename = f"sortify-diagnostics-{stamp}.log"
        candidate_dirs: list[tuple[Path, bool]] = []

        base_dir = getattr(app_obj, "base_dir", None) if app_obj is not None else None
        if base_dir:
            base_path = Path(str(base_dir))
            if base_path.is_dir():
                candidate_dirs.append((base_path, False))

        try:
            candidate_dirs.append((Path(get_app_dir()), True))
        except Exception:
            pass

        for target_dir, allow_create in candidate_dirs:
            try:
                if allow_create:
                    target_dir.mkdir(parents=True, exist_ok=True)
                out_path = target_dir / filename
                fd = os.open(
                    str(out_path),
                    os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
                    0o600,
                )
                with os.fdopen(fd, "w", encoding="utf-8") as fh:
                    fh.write(payload)
                _set_posix_mode(str(out_path), 0o600)
                return str(out_path)
            except OSError:
                continue

        fd, tmp_path = tempfile.mkstemp(prefix="sortify-diagnostics-", suffix=".log")
        with os.fdopen(fd, "w", encoding="utf-8") as fh:
            fh.write(payload)
        _set_posix_mode(tmp_path, 0o600)
        return tmp_path

    @on(Button.Pressed, "#btn-export-diagnostics")
    def action_export_diagnostics(self) -> str:
        """Export scrubbed diagnostic log report with ``0o600`` permissions."""
        app_obj = self._resolve_app_instance()
        settings_obj = getattr(self, "settings", None) or getattr(
            app_obj, "settings", None
        )
        payload = self._build_scrubbed_diagnostics_payload(settings_obj)
        out_path = self._write_secure_diagnostic_file(payload, app_obj)
        self.last_exported_diagnostics_path = out_path
        notify(f"Exported scrubbed diagnostics: {out_path}", type="positive")
        self.announce(f"Exported scrubbed diagnostics: {out_path}")
        return out_path

    @on(Button.Pressed, "#btn-close-error")
    def action_close(self) -> None:
        """Dismiss error modal dialog."""
        self.dismiss(None)

action_close()

Dismiss error modal dialog.

Source code in app/ui/modals/session.py
1593
1594
1595
1596
@on(Button.Pressed, "#btn-close-error")
def action_close(self) -> None:
    """Dismiss error modal dialog."""
    self.dismiss(None)

action_export_diagnostics()

Export scrubbed diagnostic log report with 0o600 permissions.

Source code in app/ui/modals/session.py
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
@on(Button.Pressed, "#btn-export-diagnostics")
def action_export_diagnostics(self) -> str:
    """Export scrubbed diagnostic log report with ``0o600`` permissions."""
    app_obj = self._resolve_app_instance()
    settings_obj = getattr(self, "settings", None) or getattr(
        app_obj, "settings", None
    )
    payload = self._build_scrubbed_diagnostics_payload(settings_obj)
    out_path = self._write_secure_diagnostic_file(payload, app_obj)
    self.last_exported_diagnostics_path = out_path
    notify(f"Exported scrubbed diagnostics: {out_path}", type="positive")
    self.announce(f"Exported scrubbed diagnostics: {out_path}")
    return out_path

compose()

Compose error modal widgets.

Source code in app/ui/modals/session.py
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
def compose(self) -> ComposeResult:
    """Compose error modal widgets."""
    with ModalBox(classes="error-box modal-box"):
        yield Heading(
            self.error_title, level=1, classes="modal-title", id="error-title"
        )
        with Vertical(classes="modal-body"):
            yield Label(
                self.error_message, classes="error-text", id="lbl-error-message"
            )
        with Horizontal(classes="button-row"):
            btn_help = Button("Help", id="btn-help", variant="default")
            btn_help.tooltip = "Open session recovery troubleshooting guide"
            yield btn_help

            btn_export = Button(
                "Export Diagnostics",
                id="btn-export-diagnostics",
                variant="warning",
            )
            btn_export.tooltip = "Export scrubbed diagnostic log report"
            yield btn_export

            btn_close = Button("Close", id="btn-close-error", variant="primary")
            btn_close.tooltip = "Close undo error dialog"
            yield btn_close

on_mount()

Focus close button and announce error message.

Source code in app/ui/modals/session.py
1492
1493
1494
1495
1496
def on_mount(self) -> None:
    """Focus close button and announce error message."""
    super().on_mount()
    self.query_one("#btn-close-error", Button).focus()
    self.announce(f"Error dialog: {self.error_title}")

SessionRecoveryModal

Bases: ResponsiveModalScreen[str | None]

Modal dialog for recovering interrupted file sorting sessions.

Source code in app/ui/modals/session.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
class SessionRecoveryModal(ResponsiveModalScreen[str | None]):
    """Modal dialog for recovering interrupted file sorting sessions."""

    HELP_URL = f"{TROUBLESHOOTING_URL}#session-recovery"

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-title {
        color: $error;
    }
    .conflict-reason {
        width: 100%;
        height: auto;
        color: $warning;
        text-style: bold;
        margin-top: 0;
        margin-bottom: 0;
    }
    .button-row {
        layout: grid;
        grid-size: 4;
        grid-columns: 1fr 1fr 1fr 1fr;
        grid-gutter: 0 1;
    }
    .button-row.no-resume {
        grid-size: 3;
        grid-columns: 1fr 1fr 1fr;
    }
    .button-row Button {
        width: 100%;
        min-width: 0;
        margin: 0;
    }
    Button:focus {
        border: heavy $accent;
        text-style: bold;
    }
    SessionRecoveryModal {
        &.compact .button-row, &.narrow .button-row {
            grid-size: 2;
            grid-columns: 1fr 1fr;
        }
        &.narrow .button-row.no-resume {
            grid-size: 3;
            grid-columns: 1fr 1fr 1fr;
        }
        &.compact .button-row Button {
            height: 1;
            min-height: 1;
            border: none;
        }
    }
    """

    def __init__(self, session_info: dict[str, Any]):
        super().__init__()
        self.session_info = session_info

    def _can_resume(self) -> bool:
        """Return True when this session supports resuming forward moves."""
        if self.session_info.get("can_resume") is False:
            return False
        if self.session_info.get("recovery_kind") == "incomplete_undo":
            return False
        return True

    def compose(self) -> ComposeResult:
        """Compose session recovery modal children."""
        can_resume = self._can_resume()
        is_incomplete_undo = (
            self.session_info.get("recovery_kind") == "incomplete_undo"
            or not can_resume
        )
        title_text = (
            "Incomplete Undo Detected"
            if is_incomplete_undo
            else "Interrupted Session Detected"
        )
        conflict_summary = self.session_info.get("conflict_summary")
        btn_row_classes = "button-row" if can_resume else "button-row no-resume"

        with ModalBox(classes="modal-box"):
            yield Heading(
                title_text,
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            with Vertical(classes="modal-body"):
                yield Label(
                    f"Session ID: {self.session_info.get('session_id', 'Unknown')}"
                )
                yield Label(
                    f"Target Directory: {self.session_info.get('base_dir', 'Unknown')}"
                )
                yield Label(f"Status: {self.session_info.get('status', 'Unknown')}")
                if conflict_summary:
                    yield Label(
                        f"Conflict Cause: {conflict_summary}",
                        id="lbl-recovery-conflict",
                        classes="conflict-reason",
                    )
                yield Heading("Select session recovery action:", level=2)

            with Horizontal(classes=btn_row_classes):
                btn_clean = Button("Clean", id="btn-clean", variant="error")
                btn_clean.tooltip = "Discard session files and clean workspace"
                yield btn_clean

                btn_rollback = Button(
                    "Rollback",
                    id="btn-rollback",
                    variant="primary" if not can_resume else "warning",
                )
                btn_rollback.tooltip = (
                    "Retry rolling back remaining unmodified files"
                    if not can_resume
                    else "Rollback partial file moves from interrupted run"
                )
                yield btn_rollback

                btn_help = Button("Help", id="btn-help", variant="default")
                btn_help.tooltip = "Open session recovery troubleshooting guide"
                yield btn_help

                btn_resume = Button("Resume", id="btn-resume", variant="primary")
                btn_resume.tooltip = "Resume pending file moves for interrupted run"
                if not can_resume:
                    btn_resume.disabled = True
                    btn_resume.display = False
                yield btn_resume

    def on_mount(self) -> None:
        """Focus primary recovery action on mount and emit screen reader announcement."""
        super().on_mount()
        can_resume = self._can_resume()
        conflict_summary = self.session_info.get("conflict_summary")
        if can_resume:
            self.query_one("#btn-resume", Button).focus()
            msg = "Opened interrupted session recovery dialog."
            if conflict_summary:
                msg = f"{msg} {conflict_summary}"
            self.announce(msg)
        else:
            self.query_one("#btn-rollback", Button).focus()
            cause = (
                conflict_summary
                or "Undo stopped due to file conflicts. Resume is unavailable; choose Rollback or Clean."
            )
            self.announce(f"Opened incomplete undo recovery dialog. {cause}")

    @on(Button.Pressed, "#btn-resume")
    def action_resume(self) -> None:
        """Confirm resume action."""
        if not self._can_resume():
            self.announce(
                "Cannot resume an incomplete undo session. Choose Rollback or Clean."
            )
            return
        self.announce("Confirmed session resume.")
        self.dismiss("resume")

    @on(Button.Pressed, "#btn-rollback")
    def action_rollback(self) -> None:
        """Confirm rollback action."""
        self.announce("Confirmed session rollback.")
        self.dismiss("rollback")

    @on(Button.Pressed, "#btn-clean")
    def action_clean(self) -> None:
        """Confirm clean action."""
        self.announce("Confirmed session clean.")
        self.dismiss("clean")

    @on(Button.Pressed, "#btn-cancel")
    def action_cancel(self) -> None:
        """Cancel recovery dialog."""
        self.announce("Cancelled session recovery dialog.")
        self.dismiss(None)

action_cancel()

Cancel recovery dialog.

Source code in app/ui/modals/session.py
210
211
212
213
214
@on(Button.Pressed, "#btn-cancel")
def action_cancel(self) -> None:
    """Cancel recovery dialog."""
    self.announce("Cancelled session recovery dialog.")
    self.dismiss(None)

action_clean()

Confirm clean action.

Source code in app/ui/modals/session.py
204
205
206
207
208
@on(Button.Pressed, "#btn-clean")
def action_clean(self) -> None:
    """Confirm clean action."""
    self.announce("Confirmed session clean.")
    self.dismiss("clean")

action_resume()

Confirm resume action.

Source code in app/ui/modals/session.py
187
188
189
190
191
192
193
194
195
196
@on(Button.Pressed, "#btn-resume")
def action_resume(self) -> None:
    """Confirm resume action."""
    if not self._can_resume():
        self.announce(
            "Cannot resume an incomplete undo session. Choose Rollback or Clean."
        )
        return
    self.announce("Confirmed session resume.")
    self.dismiss("resume")

action_rollback()

Confirm rollback action.

Source code in app/ui/modals/session.py
198
199
200
201
202
@on(Button.Pressed, "#btn-rollback")
def action_rollback(self) -> None:
    """Confirm rollback action."""
    self.announce("Confirmed session rollback.")
    self.dismiss("rollback")

compose()

Compose session recovery modal children.

Source code in app/ui/modals/session.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def compose(self) -> ComposeResult:
    """Compose session recovery modal children."""
    can_resume = self._can_resume()
    is_incomplete_undo = (
        self.session_info.get("recovery_kind") == "incomplete_undo"
        or not can_resume
    )
    title_text = (
        "Incomplete Undo Detected"
        if is_incomplete_undo
        else "Interrupted Session Detected"
    )
    conflict_summary = self.session_info.get("conflict_summary")
    btn_row_classes = "button-row" if can_resume else "button-row no-resume"

    with ModalBox(classes="modal-box"):
        yield Heading(
            title_text,
            level=1,
            classes="modal-title",
            id="modal-title",
        )
        with Vertical(classes="modal-body"):
            yield Label(
                f"Session ID: {self.session_info.get('session_id', 'Unknown')}"
            )
            yield Label(
                f"Target Directory: {self.session_info.get('base_dir', 'Unknown')}"
            )
            yield Label(f"Status: {self.session_info.get('status', 'Unknown')}")
            if conflict_summary:
                yield Label(
                    f"Conflict Cause: {conflict_summary}",
                    id="lbl-recovery-conflict",
                    classes="conflict-reason",
                )
            yield Heading("Select session recovery action:", level=2)

        with Horizontal(classes=btn_row_classes):
            btn_clean = Button("Clean", id="btn-clean", variant="error")
            btn_clean.tooltip = "Discard session files and clean workspace"
            yield btn_clean

            btn_rollback = Button(
                "Rollback",
                id="btn-rollback",
                variant="primary" if not can_resume else "warning",
            )
            btn_rollback.tooltip = (
                "Retry rolling back remaining unmodified files"
                if not can_resume
                else "Rollback partial file moves from interrupted run"
            )
            yield btn_rollback

            btn_help = Button("Help", id="btn-help", variant="default")
            btn_help.tooltip = "Open session recovery troubleshooting guide"
            yield btn_help

            btn_resume = Button("Resume", id="btn-resume", variant="primary")
            btn_resume.tooltip = "Resume pending file moves for interrupted run"
            if not can_resume:
                btn_resume.disabled = True
                btn_resume.display = False
            yield btn_resume

on_mount()

Focus primary recovery action on mount and emit screen reader announcement.

Source code in app/ui/modals/session.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def on_mount(self) -> None:
    """Focus primary recovery action on mount and emit screen reader announcement."""
    super().on_mount()
    can_resume = self._can_resume()
    conflict_summary = self.session_info.get("conflict_summary")
    if can_resume:
        self.query_one("#btn-resume", Button).focus()
        msg = "Opened interrupted session recovery dialog."
        if conflict_summary:
            msg = f"{msg} {conflict_summary}"
        self.announce(msg)
    else:
        self.query_one("#btn-rollback", Button).focus()
        cause = (
            conflict_summary
            or "Undo stopped due to file conflicts. Resume is unavailable; choose Rollback or Clean."
        )
        self.announce(f"Opened incomplete undo recovery dialog. {cause}")

app.ui.modals.settings

app.ui.modals.settings

Settings dialog and its scrub-artifacts and consent-revocation confirmations.

ConsentRevocationModal

Bases: _ArtifactConfirmModal

Modal dialog for confirming revocation of AI consent and cascading artifact scrubbing.

Source code in app/ui/modals/settings.py
183
184
185
186
187
188
189
190
191
192
193
194
195
class ConsentRevocationModal(_ArtifactConfirmModal):
    """Modal dialog for confirming revocation of AI consent and cascading artifact scrubbing."""

    MODAL_TITLE = "Confirm AI Consent Revocation"
    WARNING_TEXT = (
        "Revoking AI consent will disable AI features, unload models from memory, "
        "scrub stored document vectors from SQLite tables, and purge model cache files from disk. "
        "Do you wish to proceed?"
    )
    CANCEL_LABEL = "Keep Consent Active"
    CANCEL_BUTTON_ID = "btn-cancel-revoke"
    CONFIRM_LABEL = "Revoke Consent & Scrub Data"
    CONFIRM_BUTTON_ID = "btn-confirm-revoke"

ScrubArtifactsModal

Bases: _ArtifactConfirmModal

Modal dialog for confirming manual scrubbing of AI vector database rows and model cache files.

Source code in app/ui/modals/settings.py
168
169
170
171
172
173
174
175
176
177
178
179
180
class ScrubArtifactsModal(_ArtifactConfirmModal):
    """Modal dialog for confirming manual scrubbing of AI vector database rows and model cache files."""

    MODAL_TITLE = "Scrub AI Artifacts Confirmation"
    WARNING_TEXT = (
        "Warning: This operation will permanently remove all stored document vector embeddings "
        "from the SQLite database and purge local model cache files from disk. "
        "Are you sure you want to scrub AI artifacts?"
    )
    CANCEL_LABEL = "Cancel"
    CANCEL_BUTTON_ID = "btn-cancel-scrub"
    CONFIRM_LABEL = "Scrub AI Artifacts"
    CONFIRM_BUTTON_ID = "btn-confirm-scrub"

SettingsModal

Bases: ResponsiveModalScreen[dict[str, Any] | None]

Modal dialog for modifying application settings.

Source code in app/ui/modals/settings.py
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
class SettingsModal(ResponsiveModalScreen[dict[str, Any] | None]):
    """Modal dialog for modifying application settings."""

    AUTO_FOCUS = None
    HELP_URL = f"{TROUBLESHOOTING_URL}#settings-configuration"

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .field-label {
        margin-top: 1;
        color: $text;
        text-style: bold;
    }
    .setting-hint {
        width: 100%;
        color: $text-muted;
        margin-bottom: 1;
    }
    .settings-error {
        width: 100%;
        height: auto;
        color: $error;
        text-style: bold;
    }
    .settings-error.hidden {
        display: none;
    }
    .switch-row {
        margin-top: 1;
        margin-bottom: 1;
        height: 3;
        align: left middle;
    }
    .button-row {
        layout: grid;
        grid-size: 3;
        grid-gutter: 0 1;
        min-height: 3;
    }
    .button-row Button {
        width: 100%;
        min-width: 0;
    }
    Button:focus, Input:focus, Select:focus, Switch:focus {
        border: heavy $accent;
        text-style: bold;
    }
    SettingsModal {
        &.compact .field-label {
            margin-top: 0;
        }
        &.compact .switch-row {
            margin-top: 0;
            margin-bottom: 0;
        }
        &.narrow .button-row {
            grid-size: 2;
        }
    }
    SettingsModal TabbedContent {
        height: 1fr;
        min-height: 0;
    }
    SettingsModal ContentSwitcher {
        height: 1fr;
        min-height: 0;
    }
    SettingsModal TabPane {
        height: 1fr;
        min-height: 0;
        padding: 0;
        overflow-y: auto;
    }
    .readiness-panel {
        height: auto;
        width: 100%;
        padding: 0 1;
        margin-bottom: 1;
        border: round $primary;
    }
    .readiness-row {
        width: 100%;
        color: $text;
    }
    .readiness-guidance {
        width: 100%;
        color: $warning;
    }
    SettingsModal.compact .readiness-panel {
        padding: 0;
        margin-bottom: 0;
        border: none;
    }
    """

    def __init__(self, settings):
        super().__init__()
        self.settings = settings
        self.help_url = f"{TROUBLESHOOTING_URL}#settings-configuration"
        self._announced_switch_values: dict[str, bool] = {}
        self._staged_consent_revocation: bool = False
        self._ai_assisted_naming_touched: bool = False
        self._syncing_ai_switches: bool = False
        self._preserve_hierarchy_promoted_depth: bool = False
        self._syncing_scan_depth_promotion: bool = False
        self._scan_depth_edited_by_user: bool = False
        self._syncing_strategy_select: bool = False
        self._remembered_ai_assisted_val: bool = bool(
            getattr(settings, "AI_ASSISTED_NAMING", False)
        )
        self._generative_ready: bool = False
        self._generative_state: dict[str, Any] = {}
        initial_strat = str(
            getattr(settings, "SORTING_STRATEGY", "default") or "default"
        )
        self._last_valid_strategy: str = (
            "default" if initial_strat == "generative" else initial_strat
        )

    def query_one(self, selector: Any, expect_type: Any = None) -> Any:
        """Query one widget, aliasing alternative switch IDs."""
        if selector in (
            "#switch-enable-character-key-shortcuts",
            "#switch-character-shortcuts",
        ):
            selector = "#switch-character-key-shortcuts"
        elif selector in (
            "#switch-cleanup",
            "#switch-cleanup-folders",
            "#switch-cleanup-empty-directories",
            "#switch-empty-directory-cleanup",
            "#switch-clean-up-empty-folders",
        ):
            selector = "#switch-cleanup-empty-folders"
        elif selector in (
            "#switch-preserve",
            "#switch-preserve-folder-hierarchy",
            "#switch-folder-hierarchy-preservation",
            "#switch-preserve-directory-hierarchy",
            "#switch-hierarchy",
        ):
            selector = "#switch-preserve-hierarchy"
        elif selector in (
            "#switch-ai-assisted",
            "#switch-assisted-naming",
        ):
            selector = "#switch-ai-assisted-naming"
        return super().query_one(selector, expect_type=expect_type)

    def compose(self) -> ComposeResult:
        """Compose modal dialog children."""
        with ModalBox(classes="modal-box"):
            yield Heading(
                "Application Settings [Ctrl+O]",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            with TabbedContent(initial="tab-general", id="settings-tabbed-content"):
                with TabPane(
                    "General Settings", id="tab-general", classes="modal-body"
                ):
                    yield Label(
                        "Protected Directories (comma-separated):",
                        classes="field-label",
                    )
                    prot = getattr(self.settings, "PROTECTED_PATHS", [])
                    prot_str = (
                        ", ".join(prot)
                        if isinstance(prot, (list, tuple, set))
                        else str(prot)
                    )
                    inp_prot = Input(
                        value=prot_str,
                        placeholder="/path/1, /path/2",
                        id="input-protected",
                    )
                    inp_prot.tooltip = "Comma-separated protected directories exempt from automated moves"
                    yield inp_prot

                    yield Label(
                        "Ignored Extensions (comma-separated):",
                        classes="field-label",
                    )
                    ign = getattr(self.settings, "IGNORED_EXTENSIONS", [])
                    ign_str = (
                        ", ".join(ign)
                        if isinstance(ign, (list, tuple, set))
                        else str(ign)
                    )
                    inp_ign = Input(
                        value=ign_str,
                        placeholder=".tmp, .bak, .log",
                        id="input-ignored",
                    )
                    inp_ign.tooltip = (
                        "Comma-separated file extensions to ignore during scanning"
                    )
                    yield inp_ign

                    yield Label("Max Folders:", classes="field-label")
                    max_f_str = str(getattr(self.settings, "MAX_FOLDERS", 12))
                    inp_max_f = Input(
                        value=max_f_str, placeholder="12", id="input-max-folders"
                    )
                    inp_max_f.tooltip = (
                        "Maximum subdirectories generated during sorting"
                    )
                    yield inp_max_f

                    yield Label("Worker Concurrency (Threads):", classes="field-label")
                    conc_str = str(getattr(self.settings, "MAX_WORKERS", 4))
                    inp_conc = Input(
                        value=conc_str, placeholder="4", id="input-concurrency"
                    )
                    inp_conc.tooltip = "Worker concurrency thread limit for processing"
                    yield inp_conc

                    yield Label("Conflict Policy:", classes="field-label")
                    conflict_pol = getattr(self.settings, "CONFLICT_POLICY", "rename")
                    conflict_options = [
                        ("Overwrite", "overwrite"),
                        ("Auto-Rename", "rename"),
                        ("Skip", "skip"),
                    ]
                    sel_conflict = Select(
                        options=conflict_options,
                        value=conflict_pol,
                        id="select-conflict-policy",
                    )
                    sel_conflict.tooltip = "Select collision handling strategy for conflicting target files"
                    yield sel_conflict

                    yield Heading("Duplicate Handling:", level=2, classes="field-label")
                    dup_act_raw = str(
                        getattr(self.settings, "DUPLICATE_ACTION", "off") or "off"
                    ).lower()
                    dup_options = [
                        ("Off (ignore byte-identical duplicates)", "off"),
                        ("Interactive Review (confirm before execution)", "review"),
                        ("Skip Redundant Copies (keep original only)", "skip"),
                        ("Stage Copies for Undo (.sortify_duplicates)", "stage"),
                        ("Trash Copies (two-step staging)", "trash"),
                    ]
                    valid_dup_acts = {val for _lbl, val in dup_options}
                    dup_act_val = (
                        dup_act_raw if dup_act_raw in valid_dup_acts else "off"
                    )
                    sel_dup = Select(
                        dup_options,
                        value=dup_act_val,
                        allow_blank=False,
                        id="select-duplicate-action",
                    )
                    sel_dup.tooltip = (
                        "Select how byte-identical duplicate files are handled"
                    )
                    setattr(
                        sel_dup,
                        "aria_label",
                        "Byte-identical duplicate handling mode",
                    )
                    yield sel_dup

                    yield Heading(
                        "Original Selection Criterion:",
                        level=2,
                        classes="field-label",
                    )
                    det_orig_raw = str(
                        getattr(self.settings, "DETECT_ORIGINAL_BY", "first_seen")
                        or "first_seen"
                    ).lower()
                    det_orig_options = [
                        ("First Seen (discovery order)", "first_seen"),
                        ("Last Seen (reverse discovery order)", "-first_seen"),
                        ("Filename (A -> Z)", "name"),
                        ("Filename (Z -> A)", "-name"),
                        ("Oldest Created Timestamp", "created"),
                        ("Newest Created Timestamp", "-created"),
                        ("Oldest Modified Timestamp", "lastmodified"),
                        ("Newest Modified Timestamp", "-lastmodified"),
                    ]
                    valid_det_orig = {val for _lbl, val in det_orig_options}
                    det_orig_val = (
                        det_orig_raw if det_orig_raw in valid_det_orig else "first_seen"
                    )
                    sel_det_orig = Select(
                        det_orig_options,
                        value=det_orig_val,
                        allow_blank=False,
                        id="select-detect-original-by",
                    )
                    sel_det_orig.tooltip = "Select tie-breaker criterion for choosing the surviving original file"
                    setattr(
                        sel_det_orig,
                        "aria_label",
                        "Surviving original selection criterion",
                    )
                    yield sel_det_orig

                    yield LabeledSwitch(
                        label="Cleanup Empty Folders",
                        value=bool(
                            getattr(self.settings, "CLEANUP_EMPTY_FOLDERS", True)
                        ),
                        switch_id="switch-cleanup-empty-folders",
                        tooltip="Automatically prune empty source directories after moving organized files",
                    )

                    yield LabeledSwitch(
                        label="Preserve Folder Hierarchy",
                        value=bool(getattr(self.settings, "PRESERVE_HIERARCHY", False)),
                        switch_id="switch-preserve-hierarchy",
                        tooltip="Maintain source directory levels and folder structure during classification",
                    )

                    yield Label(
                        "Max Scan Depth (0 = top-level only):",
                        classes="field-label",
                    )
                    inp_scan_depth = Input(
                        value=str(getattr(self.settings, "SCAN_MAX_DEPTH", 0)),
                        id="input-scan-max-depth",
                    )
                    inp_scan_depth.tooltip = (
                        "Maximum subfolder depth to scan (0 keeps subfolders untouched)"
                    )
                    yield inp_scan_depth

                with TabPane(
                    "AI & Privacy Settings",
                    id="tab-ai-privacy",
                    classes="modal-body",
                ):
                    from app.core.downloader import (
                        get_ai_runtime_state,
                        inspect_generative_runtime_state,
                    )
                    from app.core.plugin_registry import PluginRegistry

                    onnx_state = get_ai_runtime_state(self.settings)
                    gen_state = inspect_generative_runtime_state()
                    self._generative_state = gen_state
                    self._generative_ready = bool(gen_state.get("ready", False))

                    strat = str(
                        getattr(self.settings, "SORTING_STRATEGY", "default")
                        or "default"
                    )
                    if self._generative_ready and strat == "generative":
                        self._last_valid_strategy = "generative"
                    elif strat != "generative":
                        self._last_valid_strategy = strat
                    else:
                        self._last_valid_strategy = "default"

                    gen_option_label = (
                        "Generative AI (Local GGUF)"
                        if self._generative_ready
                        else "Generative AI (Unavailable — Local GGUF Setup Required)"
                    )
                    yield Heading("Sorting Strategy:", level=2, classes="field-label")
                    options = [
                        ("Standard Semantic", "default"),
                        (gen_option_label, "generative"),
                    ]

                    reg = PluginRegistry.get_instance()
                    reg.load_plugins_from_settings(self.settings)
                    options.extend(reg.get_tui_strategy_options())
                    if not any(opt[1] == strat for opt in options):
                        options.append((f"Extension ({strat})", strat))
                    sel_strat = Select(
                        options=options, value=strat, id="select-strategy"
                    )
                    sel_strat.tooltip = (
                        "Select sorting strategy engine for document classification"
                    )
                    yield sel_strat

                    yield Heading(
                        "Local AI Capability Readiness:",
                        level=2,
                        classes="field-label",
                    )
                    onnx_txt, gguf_txt, gguf_guidance_txt = (
                        self._format_ai_readiness_texts(onnx_state, gen_state)
                    )
                    with Vertical(classes="readiness-panel", id="ai-readiness-panel"):
                        yield Label(
                            onnx_txt,
                            id="lbl-onnx-readiness",
                            classes="readiness-row",
                            markup=False,
                        )
                        yield Label(
                            gguf_txt,
                            id="lbl-gguf-readiness",
                            classes="readiness-row",
                            markup=False,
                        )
                        lbl_guidance = Label(
                            gguf_guidance_txt,
                            id="lbl-gguf-setup-guidance",
                            classes="readiness-guidance",
                            markup=False,
                        )
                        lbl_guidance.display = bool(gguf_guidance_txt)
                        yield lbl_guidance

                    yield Heading(
                        "Compliance & Renaming Toggles:",
                        level=2,
                        classes="field-label",
                    )
                    for sw_cfg in reg.get_tui_switches():
                        sw_key = sw_cfg.get("key", "")
                        sw_id = sw_cfg.get("id", f"switch-{sw_key.lower()}")
                        sw_lbl = sw_cfg.get("label", f" {sw_key}")
                        sw_tip = sw_cfg.get("tooltip", "")
                        sw_val = bool(getattr(self.settings, sw_key, False))
                        yield LabeledSwitch(
                            label=sw_lbl,
                            value=sw_val,
                            switch_id=sw_id,
                            tooltip=sw_tip,
                        )

                    ai_consent_val = bool(
                        getattr(self.settings, "AI_CONSENT_GRANTED", False)
                    )
                    ai_assisted_val = bool(
                        ai_consent_val
                        and getattr(self.settings, "AI_ASSISTED_NAMING", False)
                    )

                    yield LabeledSwitch(
                        label="AI Consent Granted",
                        value=ai_consent_val,
                        switch_id="switch-ai-consent",
                        tooltip="Toggle AI consent for semantic document classification and processing",
                    )

                    yield LabeledSwitch(
                        label="AI Assisted Naming",
                        value=ai_assisted_val,
                        switch_id="switch-ai-assisted-naming",
                        disabled=not ai_consent_val,
                        tooltip="Rank semantic file keyphrases via local ONNX embeddings independently of Sorting Strategy (requires AI Consent Granted)",
                    )

                    yield LabeledSwitch(
                        label="AI Contextual Renaming",
                        value=bool(
                            getattr(self.settings, "CONTEXTUAL_RENAMING", False)
                        ),
                        switch_id="switch-contextual-renaming",
                        tooltip="Replace generic scan stems (e.g. scan_01) with document keywords while keeping descriptive stems intact unless {keywords} is in template",
                    )

                    yield Label(
                        "Default Rename Template:",
                        classes="field-label",
                    )
                    yield Label(
                        "Applies standalone with literal {stem}/{original}; enable AI Contextual Renaming or add {keywords} to insert document terms.",
                        classes="setting-hint",
                        id="lbl-rename-template-hint",
                    )
                    ren_pat_val = str(
                        getattr(self.settings, "RENAME_PATTERN", "") or ""
                    )
                    inp_ren_pat = Input(
                        value=ren_pat_val,
                        placeholder="e.g. {date}_{stem}{extension} or {date}_{keywords}_{stem}",
                        id="input-rename-pattern",
                    )
                    inp_ren_pat.tooltip = "Standalone rename template supporting literal {stem}/{original}, extracted {keywords}, {date}, {year}, {month}, {day}, {category}, {seq}, and {extension}"
                    yield inp_ren_pat

                    current_auto_ratings = {
                        str(r).upper()
                        for r in (
                            getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or []
                        )
                        if r
                    }
                    yield LabeledSwitch(
                        label="Auto-Quarantine CRITICAL Sensitivity",
                        value="CRITICAL" in current_auto_ratings,
                        switch_id="switch-quarantine-critical",
                        tooltip="Automatically hold CRITICAL sensitivity documents in compliance quarantine during sorting and daemon monitoring",
                    )

                    yield LabeledSwitch(
                        label="Auto-Quarantine HIGH Sensitivity",
                        value="HIGH" in current_auto_ratings,
                        switch_id="switch-quarantine-high",
                        tooltip="Automatically hold HIGH sensitivity documents in compliance quarantine during sorting and daemon monitoring",
                    )

                    yield Label(
                        "Compliance Quarantine Folder Name:",
                        classes="field-label",
                    )
                    q_dir_val = (
                        getattr(
                            self.settings,
                            "QUARANTINE_DIR_NAME",
                            "_Compliance_Quarantine",
                        )
                        or "_Compliance_Quarantine"
                    )
                    inp_qdir = Input(
                        value=str(q_dir_val),
                        placeholder="_Compliance_Quarantine",
                        id="input-quarantine-dir",
                    )
                    inp_qdir.tooltip = "Workspace subfolder name used when staging held compliance files"
                    yield inp_qdir

                    yield LabeledSwitch(
                        label="Speak Status Messages Aloud",
                        value=bool(
                            getattr(self.settings, "SPEAK_ANNOUNCEMENTS", False)
                        ),
                        switch_id="switch-speak-announcements",
                        tooltip="Read each status message aloud with the system speech command (say / spd-say)",
                    )

                    yield LabeledSwitch(
                        label="Single-Character Shortcuts",
                        value=bool(
                            getattr(
                                self.settings,
                                "ENABLE_CHARACTER_KEY_SHORTCUTS",
                                True,
                            )
                        ),
                        switch_id="switch-character-key-shortcuts",
                        tooltip="Enable single-character keyboard shortcuts in the plan tree (WCAG 2.1.4)",
                    )

                    btn_scrub = Button(
                        "Scrub AI Artifacts",
                        id="btn-scrub-artifacts",
                        variant="warning",
                    )
                    btn_scrub.tooltip = "Report vector count and cache footprint, and scrub stored vectors and model files"
                    yield btn_scrub

                    btn_templates = Button(
                        "Starter Rule Template Gallery",
                        id="btn-open-templates",
                        variant="primary",
                    )
                    btn_templates.tooltip = (
                        "View and apply pre-configured starter rule template packs"
                    )
                    yield btn_templates

                    btn_active_rules = Button(
                        "Active Rule Manager",
                        id="btn-open-rules",
                        variant="primary",
                    )
                    btn_active_rules.tooltip = "Inspect, add, edit, toggle, and delete active rules and policies"
                    yield btn_active_rules

                with TabPane(
                    "Extraction & OCR",
                    id="tab-extraction",
                    classes="modal-body",
                ):
                    yield Label(
                        "PDF Text Density Threshold (chars/page):",
                        classes="field-label",
                    )
                    density_val = getattr(
                        self.settings, "PDF_TEXT_DENSITY_THRESHOLD", 50
                    )
                    inp_density = Input(
                        value=str(density_val),
                        placeholder="50",
                        id="input-pdf-density-threshold",
                    )
                    inp_density.tooltip = "Pages with fewer embedded characters trigger EasyOCR rasterization fallback"
                    yield inp_density

                    slider_density = DensitySlider(
                        value=int(density_val),
                        min_value=0,
                        max_value=500,
                        step=5,
                        id="slider-pdf-density-threshold",
                    )
                    slider_density.tooltip = "Adjust PDF text density threshold slider"
                    yield slider_density

            yield Static(
                "",
                id="lbl-settings-error",
                classes="settings-error hidden",
                markup=False,
            )
            with Horizontal(classes="button-row"):
                btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
                btn_cancel.tooltip = "Cancel settings modification and close dialog"
                yield btn_cancel
                btn_model_mgr = Button(
                    "Model Manager", id="btn-model-mgr", variant="primary"
                )
                btn_model_mgr.tooltip = (
                    "Open dedicated interactive model management modal"
                )
                yield btn_model_mgr
                btn_help = Button(
                    "Help", id="btn-help", variant="warning", classes="hidden"
                )
                btn_help.tooltip = "Open settings configuration troubleshooting guide"
                yield btn_help
                btn_save = Button("Save Settings", id="btn-save", variant="primary")
                btn_save.tooltip = "Save modified application settings"
                yield btn_save

    def _format_ai_readiness_texts(
        self, onnx_state: dict[str, Any], gen_state: dict[str, Any]
    ) -> tuple[str, str, str]:
        """Format ONNX and GGUF readiness summary and setup guidance strings."""
        onnx_verified = bool(onnx_state.get("verified", False))
        onnx_rt = bool(onnx_state.get("onnxruntime_available", False))
        if onnx_verified and onnx_rt:
            onnx_txt = (
                "ONNX Embeddings: Ready (powers Standard Semantic & AI Assisted Naming)"
            )
        elif onnx_verified and not onnx_rt:
            onnx_txt = "ONNX Embeddings: Weights present, missing 'smart-autosorter[ml]' runtime"
        else:
            onnx_txt = "ONNX Embeddings: Not downloaded (use Model Manager; TF-IDF fallback active)"

        gen_status = str(gen_state.get("status") or "NOT_CONFIGURED")
        if gen_state.get("ready"):
            gguf_name = os.path.basename(
                str(
                    gen_state.get("gguf_file")
                    or gen_state.get("model_path")
                    or "model.gguf"
                )
            )
            gguf_txt = f"Generative AI (GGUF): Ready ({gguf_name} + llama_cpp)"
            guidance_txt = ""
        elif gen_status == "MISSING_ML_EXTRA":
            gguf_txt = "Generative AI (GGUF): Disabled — llama-cpp-python missing"
            guidance_txt = (
                "Generative AI setup: local GGUF found via GENERATIVE_NAMING_PATH, "
                "but llama_cpp is missing. Install 'smart-autosorter[ml]' (uv sync --extra ml)."
            )
        elif gen_status == "INVALID_WEIGHTS":
            gguf_txt = "Generative AI (GGUF): Disabled — invalid local GGUF weights"
            guidance_txt = (
                f"{gen_state.get('detail') or 'Invalid GGUF weights.'} "
                "Set GENERATIVE_NAMING_PATH=/path/to/model.gguf and install 'smart-autosorter[ml]'."
            )
        else:
            gguf_txt = (
                "Generative AI (GGUF): Disabled — local GGUF weights not configured"
            )
            guidance_txt = (
                "Generative AI setup: set GENERATIVE_NAMING_PATH=/path/to/model.gguf "
                "and install 'smart-autosorter[ml]' (uv sync --extra ml)."
            )
        return onnx_txt, gguf_txt, guidance_txt

    def _apply_generative_select_gate(self) -> None:
        """Disable or enable the 'generative' option inside #select-strategy's OptionList."""
        from textual.widgets._select import SelectOverlay

        try:
            sel = self.query_one("#select-strategy", Select)
            overlay = sel.query_one(SelectOverlay)
            for idx, (_prompt, val) in enumerate(getattr(sel, "_options", [])):
                if val == "generative":
                    if self._generative_ready:
                        overlay.enable_option_at_index(idx)
                    else:
                        overlay.disable_option_at_index(idx)
                    break
        except (NoMatches, LookupError, AttributeError, IndexError):
            return

    def _refresh_ai_readiness_ui(self) -> None:
        """Re-evaluate ONNX and GGUF readiness and synchronize labels and strategy gate."""
        from app.core.downloader import (
            get_ai_runtime_state,
            inspect_generative_runtime_state,
        )

        onnx_state = get_ai_runtime_state(self.settings)
        gen_state = inspect_generative_runtime_state()
        self._generative_state = gen_state
        self._generative_ready = bool(gen_state.get("ready", False))
        onnx_txt, gguf_txt, guidance_txt = self._format_ai_readiness_texts(
            onnx_state, gen_state
        )
        try:
            self.query_one("#lbl-onnx-readiness", Label).update(onnx_txt)
            self.query_one("#lbl-gguf-readiness", Label).update(gguf_txt)
            lbl_guidance = self.query_one("#lbl-gguf-setup-guidance", Label)
            lbl_guidance.update(guidance_txt)
            lbl_guidance.display = bool(guidance_txt)
        except (NoMatches, LookupError, AttributeError):
            pass
        self._apply_generative_select_gate()

    def on_mount(self) -> None:
        """Focus initial input field on mount and emit announcement."""
        super().on_mount()
        self._apply_generative_select_gate()
        self.query_one("#input-protected", Input).focus(scroll_visible=False)
        self.query_one(".modal-box", ModalBox).scroll_home(
            animate=False, immediate=True
        )
        for sw_id in (
            "#switch-character-key-shortcuts",
            "#switch-quarantine-critical",
            "#switch-quarantine-high",
        ):
            try:
                sw = self.query_one(sw_id, Switch)
                self._announced_switch_values[sw_id] = bool(sw.value)
                self.watch(
                    sw,
                    "value",
                    lambda val, sid=sw_id: self._announce_switch_toggle(sid, bool(val)),
                    init=False,
                )
            except Exception:
                pass
        self.announce("Opened application settings dialog.")

    def _announce_switch_toggle(self, switch_id: str, value: bool) -> None:
        """Emit deduplicated accessibility announcement when a settings switch changes."""
        if self._announced_switch_values.get(switch_id) == value:
            return
        self._announced_switch_values[switch_id] = value
        state_str = "enabled" if value else "disabled"
        if not hasattr(self, "announce"):
            return
        if switch_id == "#switch-character-key-shortcuts":
            self.announce(f"Character key shortcuts {state_str}.", priority="polite")
        elif switch_id == "#switch-quarantine-critical":
            self.announce(
                f"Automatic CRITICAL sensitivity quarantine {state_str}.",
                priority="polite",
            )
        elif switch_id == "#switch-quarantine-high":
            self.announce(
                f"Automatic HIGH sensitivity quarantine {state_str}.",
                priority="polite",
            )

    def _get_scoped_rule_settings(self) -> Any:
        """Resolve folder-scoped settings for rule dialogs when a workspace folder is active."""
        from app.config import resolve_scoped_settings

        get_active_fn = (
            getattr(self.app, "get_active_settings", None)
            if hasattr(self, "app") and self.app
            else None
        )
        if callable(get_active_fn):
            return get_active_fn()
        base_dir = (
            getattr(self.app, "base_dir", None)
            if hasattr(self, "app") and self.app
            else None
        )
        return resolve_scoped_settings(self.settings, base_dir, fallback_to_global=True)

    @on(Button.Pressed, "#btn-open-templates")
    def action_open_templates(self) -> None:
        """Open starter rule template gallery modal."""
        self.app.push_screen(TemplateGalleryModal(self._get_scoped_rule_settings()))

    @on(Button.Pressed, "#btn-open-rules")
    def action_open_active_rules(self) -> None:
        """Open active rule manager modal."""
        from app.ui.modals.rules import ActiveRuleManagerModal

        def on_rules_closed(mutated: bool | None = None) -> None:
            if mutated:
                update_fn = getattr(self.app, "update_status", None)
                if callable(update_fn):
                    update_fn()
                if getattr(self.app, "base_dir", None):
                    scan_fn = getattr(self.app, "action_scan_directory", None)
                    if callable(scan_fn):
                        scan_fn()

        self.app.push_screen(
            ActiveRuleManagerModal(self._get_scoped_rule_settings()), on_rules_closed
        )

    @on(DensitySlider.Changed, "#slider-pdf-density-threshold")
    def _on_density_slider_changed(self, event: DensitySlider.Changed) -> None:
        try:
            inp = self.query_one("#input-pdf-density-threshold", Input)
            if inp.value != str(event.value):
                inp.value = str(event.value)
        except Exception:
            pass

    @on(Input.Changed, "#input-pdf-density-threshold")
    def _on_density_input_changed(self, event: Input.Changed) -> None:
        try:
            val = int(event.value.strip())
            slider = self.query_one("#slider-pdf-density-threshold", DensitySlider)
            if slider.value != val and slider.min_value <= val <= slider.max_value:
                slider.value = val
        except Exception:
            pass

    @on(Button.Pressed, "#btn-scrub-artifacts")
    def action_scrub_artifacts(self) -> None:
        """Open Scrub AI Artifacts confirmation modal."""
        db_inst = getattr(self.app, "db", None) if hasattr(self, "app") else None
        v_count = _get_vector_count(db_inst)
        footprint_mb = _get_model_cache_footprint_mb()

        def _on_scrub_modal_result(confirmed: bool | None) -> None:
            if confirmed:
                self._execute_scrub_and_purge()

        if hasattr(self, "app") and self.app:
            self.app.push_screen(
                ScrubArtifactsModal(v_count, footprint_mb), _on_scrub_modal_result
            )

    def _set_ai_assisted_switch_enabled(
        self, enabled: bool, value: bool | None = None
    ) -> None:
        """Synchronize disabled and value state on #switch-ai-assisted-naming and its row."""
        try:
            sw = self.query_one("#switch-ai-assisted-naming", Switch)
        except (NoMatches, LookupError, AttributeError):
            return
        self._syncing_ai_switches = True
        try:
            sw.disabled = not enabled
            if sw.parent is not None and isinstance(sw.parent, LabeledSwitch):
                sw.parent.disabled = not enabled
            if value is not None:
                sw.value = value
        finally:
            self._syncing_ai_switches = False

    @on(Switch.Changed, "#switch-preserve-hierarchy")
    def _on_preserve_hierarchy_changed(self, event: Switch.Changed) -> None:
        """Promote Max Scan Depth from 0 to 5 when Preserve Folder Hierarchy is toggled on."""
        self._clear_settings_error()
        if not event.value:
            return
        try:
            inp_depth = self.query_one("#input-scan-max-depth", Input)
        except (NoMatches, LookupError, AttributeError):
            return
        if inp_depth.value.strip() == "0":
            self._syncing_scan_depth_promotion = True
            try:
                inp_depth.value = "5"
            finally:
                self._syncing_scan_depth_promotion = False
            self._preserve_hierarchy_promoted_depth = True
            self.announce(
                "Max Scan Depth promoted from 0 to 5 for Preserve Folder Hierarchy."
            )

    @on(Input.Changed, "#input-scan-max-depth")
    def _on_scan_max_depth_changed(self, event: Input.Changed) -> None:
        """Track explicit user edits to Max Scan Depth."""
        self._clear_settings_error()
        if not self._syncing_scan_depth_promotion:
            self._scan_depth_edited_by_user = True

    @on(Switch.Changed, "#switch-ai-assisted-naming")
    def on_ai_assisted_naming_changed(self, event: Switch.Changed) -> None:
        """Record explicit user toggles on AI Assisted Naming."""
        if self._syncing_ai_switches:
            return
        self._ai_assisted_naming_touched = True
        self._remembered_ai_assisted_val = bool(event.value)
        state_str = "enabled" if event.value else "disabled"
        if hasattr(self, "announce"):
            self.announce(f"AI assisted naming {state_str}.", priority="polite")

    @on(Select.Changed, "#select-strategy")
    def on_strategy_changed(self, event: Select.Changed) -> None:
        """Enforce local GGUF readiness gate on Generative AI without mutating AI Assisted Naming."""
        if self._syncing_strategy_select:
            return
        selected_val = (
            "default"
            if event.value is None or event.value == Select.BLANK
            else str(event.value)
        )
        if selected_val == "generative" and not self._generative_ready:
            self._syncing_strategy_select = True
            try:
                cast(Select[str], event.select).value = self._last_valid_strategy
            finally:
                self._syncing_strategy_select = False
            msg = (
                "Generative AI is unavailable: set GENERATIVE_NAMING_PATH to a valid "
                "local .gguf model and install 'smart-autosorter[ml]'."
            )
            from app.ui.notifications import notify

            notify(msg, type="warning")
            if hasattr(self, "announce"):
                self.announce(msg, priority="assertive")
            return
        self._last_valid_strategy = selected_val

    @on(Switch.Changed, "#switch-ai-consent")
    def on_ai_consent_changed(self, event: Switch.Changed) -> None:
        """Prompt user confirmation when AI consent switch is toggled off."""
        if event.value:
            self._staged_consent_revocation = False
            self._set_ai_assisted_switch_enabled(
                True, value=self._remembered_ai_assisted_val
            )
            return

        self._set_ai_assisted_switch_enabled(False, value=False)

        db_inst = getattr(self.app, "db", None) if hasattr(self, "app") else None
        v_count = _get_vector_count(db_inst)
        footprint_mb = _get_model_cache_footprint_mb()

        def _on_revoke_modal_result(confirmed: bool | None) -> None:
            if confirmed:
                self._staged_consent_revocation = True
                self._set_ai_assisted_switch_enabled(False, value=False)
                if hasattr(self, "announce"):
                    self.announce(
                        "AI consent revocation staged; save settings to apply.",
                        priority="polite",
                    )
            else:
                self._staged_consent_revocation = False
                event.switch.value = True

        if hasattr(self, "app") and self.app and self.is_current:
            self.app.push_screen(
                ConsentRevocationModal(v_count, footprint_mb),
                _on_revoke_modal_result,
            )

    @on(Switch.Changed, "#switch-character-key-shortcuts")
    def on_character_shortcuts_changed(self, event: Switch.Changed) -> None:
        """Announce shortcut status update when single-character shortcuts switch is toggled."""
        self._announce_switch_toggle(
            "#switch-character-key-shortcuts", bool(event.value)
        )

    @on(Switch.Changed, "#switch-quarantine-critical")
    def on_quarantine_critical_changed(self, event: Switch.Changed) -> None:
        """Announce status update when CRITICAL sensitivity auto-quarantine switch is toggled."""
        self._announce_switch_toggle("#switch-quarantine-critical", bool(event.value))

    @on(Switch.Changed, "#switch-quarantine-high")
    def on_quarantine_high_changed(self, event: Switch.Changed) -> None:
        """Announce status update when HIGH sensitivity auto-quarantine switch is toggled."""
        self._announce_switch_toggle("#switch-quarantine-high", bool(event.value))

    def _execute_scrub_and_purge(self) -> None:
        """Execute memory model unload, database vector clearing, and background model cache purging."""
        try:
            from app.core.shared_registry import SharedModelRegistry

            SharedModelRegistry.get_instance().unload_all_models()
        except Exception:
            pass

        try:
            app_db = getattr(self.app, "db", None) if hasattr(self, "app") else None
            if app_db is not None:
                app_db.clear_all_document_vectors()
        except Exception:
            pass

        try:
            from app.core.db import Database

            Database.scrub_all_vectors()
        except Exception:
            pass

        try:
            from app.config import get_app_dir
            from app.core.downloader import DownloadManager

            model_dir = str(get_app_dir() / "model")
            dm = DownloadManager.get_instance()

            def _on_purge_done(success: bool, err: Exception | None):
                if success:
                    if hasattr(self, "announce"):
                        self.announce(
                            "AI artifacts scrubbed and model cache purged successfully.",
                            priority="polite",
                        )
                else:
                    if hasattr(self, "announce"):
                        self.announce(
                            f"Model cache purge failed: {err}", priority="assertive"
                        )

            dm.delete_model_async(model_dir, on_done=_on_purge_done)
        except Exception as e:
            logger.error(f"Error purging model cache: {e}")

        try:
            from app.ui.notifications import notify

            notify(
                "AI artifacts scrubbed and model cache purging started.", type="info"
            )
        except Exception:
            pass
        if hasattr(self, "announce"):
            self.announce("AI artifacts scrubbed and model cache purging started.")

    def _clear_settings_error(self) -> None:
        """Clear and hide inline settings validation error banner."""
        with contextlib.suppress(NoMatches, LookupError, AttributeError):
            err_lbl = self.query_one("#lbl-settings-error", Static)
            err_lbl.update("")
            err_lbl.add_class("hidden")

    def _report_settings_error(self, message: str) -> None:
        """Show inline validation error, contextual Help button, and screen-reader announcement."""
        help_url = f"{TROUBLESHOOTING_URL}#settings-configuration"
        self._show_help_button(help_url)
        from app.ui.notifications import notify

        err_msg = f"Settings error: {message}"
        with contextlib.suppress(NoMatches, LookupError, AttributeError):
            err_lbl = self.query_one("#lbl-settings-error", Static)
            err_lbl.update(err_msg)
            err_lbl.remove_class("hidden")
        notify(err_msg, type="error", help_url=help_url)
        self.announce(err_msg, help_url=help_url)

    @on(Button.Pressed, "#btn-save")
    def action_save(self) -> None:
        """Save settings and dismiss modal."""
        from app.config import Settings

        p_str = self.query_one("#input-protected", Input).value
        raw_p_list = [p.strip() for p in p_str.split(",") if p.strip()]
        expanded_p_list = [
            os.path.expanduser(p) if p.startswith("~") else p for p in raw_p_list
        ]
        try:
            p_list = Settings.validate_protected_paths(expanded_p_list)
        except ValueError as e:
            self._report_settings_error(str(e))
            return

        i_str = self.query_one("#input-ignored", Input).value
        raw_i_list = [i.strip() for i in i_str.split(",") if i.strip()]
        try:
            i_list = Settings.validate_ignored_extensions(raw_i_list)
        except ValueError as e:
            self._report_settings_error(str(e))
            return

        try:
            conc_val = self.query_one("#input-concurrency", Input).value.strip()
            conc = int(conc_val)
            if not (1 <= conc <= 64):
                raise ValueError("Worker concurrency must be between 1 and 64.")
        except ValueError as e:
            self._report_settings_error(str(e))
            return

        try:
            max_f_val = self.query_one("#input-max-folders", Input).value.strip()
            max_f = int(max_f_val)
            if not (1 <= max_f <= 50):
                raise ValueError("Max folders must be between 1 and 50.")
        except ValueError as e:
            self._report_settings_error(str(e))
            return

        try:
            density_val_str = self.query_one(
                "#input-pdf-density-threshold", Input
            ).value.strip()
            pdf_density = int(density_val_str)
            if pdf_density < 0:
                raise ValueError("PDF text density threshold must be non-negative.")
        except ValueError as e:
            self._report_settings_error(str(e))
            return

        strat = self.query_one("#select-strategy", Select).value
        if strat == Select.BLANK:
            strat = "default"
        if strat == "generative" and not self._generative_ready:
            self._report_settings_error(
                "Generative AI requires valid local GGUF weights via GENERATIVE_NAMING_PATH "
                "and optional ML extras ('smart-autosorter[ml]')."
            )
            return

        try:
            clin_renaming = self.query_one("#switch-clinical-renaming", Switch).value
        except Exception:
            clin_renaming = bool(
                getattr(self.settings, "CLINICAL_SMART_RENAMING", False)
            )
        try:
            ctx_renaming = self.query_one("#switch-contextual-renaming", Switch).value
        except Exception:
            ctx_renaming = bool(getattr(self.settings, "CONTEXTUAL_RENAMING", False))
        try:
            speak = self.query_one("#switch-speak-announcements", Switch).value
        except Exception:
            speak = bool(getattr(self.settings, "SPEAK_ANNOUNCEMENTS", False))
        try:
            char_shortcuts = self.query_one(
                "#switch-character-key-shortcuts", Switch
            ).value
        except Exception:
            char_shortcuts = bool(
                getattr(self.settings, "ENABLE_CHARACTER_KEY_SHORTCUTS", True)
            )
        try:
            ai_consent = self.query_one("#switch-ai-consent", Switch).value
        except Exception:
            ai_consent = bool(getattr(self.settings, "AI_CONSENT_GRANTED", False))

        try:
            conflict_pol = self.query_one("#select-conflict-policy", Select).value
            if conflict_pol == Select.BLANK:
                conflict_pol = "rename"
        except Exception:
            conflict_pol = getattr(self.settings, "CONFLICT_POLICY", "rename")

        try:
            dup_sel_val = self.query_one("#select-duplicate-action", Select).value
            duplicate_action = (
                str(dup_sel_val)
                if dup_sel_val is not None and dup_sel_val != Select.BLANK
                else str(getattr(self.settings, "DUPLICATE_ACTION", "off") or "off")
            )
        except Exception:
            duplicate_action = str(
                getattr(self.settings, "DUPLICATE_ACTION", "off") or "off"
            )

        try:
            det_sel_val = self.query_one("#select-detect-original-by", Select).value
            detect_original_by = (
                str(det_sel_val)
                if det_sel_val is not None and det_sel_val != Select.BLANK
                else str(
                    getattr(self.settings, "DETECT_ORIGINAL_BY", "first_seen")
                    or "first_seen"
                )
            )
        except Exception:
            detect_original_by = str(
                getattr(self.settings, "DETECT_ORIGINAL_BY", "first_seen")
                or "first_seen"
            )

        try:
            q_dir_raw = self.query_one("#input-quarantine-dir", Input).value.strip()
        except Exception:
            q_dir_raw = getattr(
                self.settings, "QUARANTINE_DIR_NAME", "_Compliance_Quarantine"
            )
        q_dir_str = q_dir_raw or "_Compliance_Quarantine"
        from app.core.path_utils import validate_target_path

        try:
            if any(ch in q_dir_str for ch in ("*", "?", "[", "]")):
                raise ValueError(
                    "Wildcard characters are not allowed in quarantine folder name."
                )
            validate_target_path(q_dir_str, keyword="QUARANTINE_DIR_NAME")
        except ValueError as e:
            self._report_settings_error(f"Invalid quarantine folder name: {e}")
            return

        existing_ratings = [
            str(r).upper()
            for r in (getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or [])
            if r and str(r).upper() not in ("CRITICAL", "HIGH")
        ]
        try:
            q_crit = self.query_one("#switch-quarantine-critical", Switch).value
        except Exception:
            q_crit = "CRITICAL" in {
                str(r).upper()
                for r in (getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or [])
            }
        try:
            q_high = self.query_one("#switch-quarantine-high", Switch).value
        except Exception:
            q_high = "HIGH" in {
                str(r).upper()
                for r in (getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or [])
            }
        auto_quarantine_ratings: list[str] = []
        if q_crit:
            auto_quarantine_ratings.append("CRITICAL")
        if q_high:
            auto_quarantine_ratings.append("HIGH")
        for extra_r in existing_ratings:
            if extra_r not in auto_quarantine_ratings:
                auto_quarantine_ratings.append(extra_r)

        try:
            cleanup_empty = self.query_one(
                "#switch-cleanup-empty-folders", Switch
            ).value
        except Exception:
            cleanup_empty = bool(getattr(self.settings, "CLEANUP_EMPTY_FOLDERS", True))
        try:
            preserve_hier = self.query_one("#switch-preserve-hierarchy", Switch).value
        except Exception:
            preserve_hier = bool(getattr(self.settings, "PRESERVE_HIERARCHY", False))

        try:
            scan_depth_str = self.query_one(
                "#input-scan-max-depth", Input
            ).value.strip()
        except (NoMatches, LookupError, AttributeError):
            scan_depth_str = str(getattr(self.settings, "SCAN_MAX_DEPTH", 0))
        try:
            scan_max_depth = int(scan_depth_str)
            if not (0 <= scan_max_depth <= 20):
                raise ValueError("Max Scan Depth must be between 0 and 20.")
        except ValueError:
            self._report_settings_error(
                f"Invalid Max Scan Depth '{scan_depth_str}'. "
                "Expected an integer from 0 to 20."
            )
            return

        if preserve_hier and scan_max_depth == 0:
            was_previously_enabled = bool(
                getattr(self.settings, "PRESERVE_HIERARCHY", False)
            )
            if (
                not was_previously_enabled
                and not self._preserve_hierarchy_promoted_depth
                and not self._scan_depth_edited_by_user
            ):
                scan_max_depth = 5
                self._preserve_hierarchy_promoted_depth = True
                with contextlib.suppress(NoMatches, LookupError, AttributeError):
                    self._syncing_scan_depth_promotion = True
                    try:
                        self.query_one("#input-scan-max-depth", Input).value = "5"
                    finally:
                        self._syncing_scan_depth_promotion = False
            else:
                self._report_settings_error(
                    "Max Scan Depth must be at least 1 when Preserve Folder Hierarchy is enabled."
                )
                with contextlib.suppress(NoMatches, LookupError, AttributeError):
                    self.query_one("#input-scan-max-depth", Input).focus()
                return

        try:
            rename_pat_raw = self.query_one(
                "#input-rename-pattern", Input
            ).value.strip()
        except Exception:
            rename_pat_raw = str(getattr(self.settings, "RENAME_PATTERN", "") or "")
        if rename_pat_raw:
            from app.core.path_utils import ILLEGAL_PATH_CHARS_SET

            if (
                "/" in rename_pat_raw
                or "\\" in rename_pat_raw
                or ".." in rename_pat_raw
                or "\x00" in rename_pat_raw
                or any(ch in ILLEGAL_PATH_CHARS_SET for ch in rename_pat_raw)
            ):
                self._report_settings_error(
                    "Default rename template cannot contain path separators, '..', "
                    "null bytes, or illegal filename characters."
                )
                return

        if not ai_consent and (
            self._staged_consent_revocation
            or getattr(self.settings, "AI_CONSENT_GRANTED", None) is True
        ):
            self._staged_consent_revocation = False
            self._execute_scrub_and_purge()

        try:
            sw_ai_assisted_val = bool(
                self.query_one("#switch-ai-assisted-naming", Switch).value
            )
        except (NoMatches, LookupError, AttributeError):
            sw_ai_assisted_val = bool(
                getattr(self.settings, "AI_ASSISTED_NAMING", False)
            )

        ai_assisted_naming = bool(ai_consent and sw_ai_assisted_val)

        res = {
            "PROTECTED_PATHS": p_list,
            "IGNORED_EXTENSIONS": i_list,
            "MAX_WORKERS": conc,
            "MAX_FOLDERS": max_f,
            "PDF_TEXT_DENSITY_THRESHOLD": pdf_density,
            "CONFLICT_POLICY": conflict_pol,
            "DUPLICATE_ACTION": duplicate_action,
            "DETECT_ORIGINAL_BY": detect_original_by,
            "SORTING_STRATEGY": strat,
            "AI_ASSISTED_NAMING": ai_assisted_naming,
            "CLINICAL_SMART_RENAMING": clin_renaming,
            "CONTEXTUAL_RENAMING": ctx_renaming,
            "RENAME_PATTERN": rename_pat_raw,
            "AI_CONSENT_GRANTED": ai_consent,
            "SPEAK_ANNOUNCEMENTS": speak,
            "ENABLE_CHARACTER_KEY_SHORTCUTS": char_shortcuts,
            "CLEANUP_EMPTY_FOLDERS": cleanup_empty,
            "PRESERVE_HIERARCHY": preserve_hier,
            "SCAN_MAX_DEPTH": scan_max_depth,
            "AUTO_QUARANTINE_RATINGS": auto_quarantine_ratings,
            "QUARANTINE_DIR_NAME": q_dir_str,
        }
        self.announce("Saved application settings.")
        self.dismiss(res)

    @on(Button.Pressed, "#btn-cancel")
    def action_cancel(self) -> None:
        """Cancel settings modification."""
        self._staged_consent_revocation = False
        self.announce("Cancelled settings modification.")
        self.dismiss(None)

    @on(Button.Pressed, "#btn-model-mgr")
    def action_open_model_manager(self) -> None:
        """Open model manager modal."""
        if hasattr(self, "app") and self.app:
            self.app.push_screen(
                ModelManagerModal(self.settings),
                lambda _res=None: self._refresh_ai_readiness_ui(),
            )

action_cancel()

Cancel settings modification.

Source code in app/ui/modals/settings.py
1549
1550
1551
1552
1553
1554
@on(Button.Pressed, "#btn-cancel")
def action_cancel(self) -> None:
    """Cancel settings modification."""
    self._staged_consent_revocation = False
    self.announce("Cancelled settings modification.")
    self.dismiss(None)

action_open_active_rules()

Open active rule manager modal.

Source code in app/ui/modals/settings.py
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
@on(Button.Pressed, "#btn-open-rules")
def action_open_active_rules(self) -> None:
    """Open active rule manager modal."""
    from app.ui.modals.rules import ActiveRuleManagerModal

    def on_rules_closed(mutated: bool | None = None) -> None:
        if mutated:
            update_fn = getattr(self.app, "update_status", None)
            if callable(update_fn):
                update_fn()
            if getattr(self.app, "base_dir", None):
                scan_fn = getattr(self.app, "action_scan_directory", None)
                if callable(scan_fn):
                    scan_fn()

    self.app.push_screen(
        ActiveRuleManagerModal(self._get_scoped_rule_settings()), on_rules_closed
    )

action_open_model_manager()

Open model manager modal.

Source code in app/ui/modals/settings.py
1556
1557
1558
1559
1560
1561
1562
1563
@on(Button.Pressed, "#btn-model-mgr")
def action_open_model_manager(self) -> None:
    """Open model manager modal."""
    if hasattr(self, "app") and self.app:
        self.app.push_screen(
            ModelManagerModal(self.settings),
            lambda _res=None: self._refresh_ai_readiness_ui(),
        )

action_open_templates()

Open starter rule template gallery modal.

Source code in app/ui/modals/settings.py
983
984
985
986
@on(Button.Pressed, "#btn-open-templates")
def action_open_templates(self) -> None:
    """Open starter rule template gallery modal."""
    self.app.push_screen(TemplateGalleryModal(self._get_scoped_rule_settings()))

action_save()

Save settings and dismiss modal.

Source code in app/ui/modals/settings.py
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
@on(Button.Pressed, "#btn-save")
def action_save(self) -> None:
    """Save settings and dismiss modal."""
    from app.config import Settings

    p_str = self.query_one("#input-protected", Input).value
    raw_p_list = [p.strip() for p in p_str.split(",") if p.strip()]
    expanded_p_list = [
        os.path.expanduser(p) if p.startswith("~") else p for p in raw_p_list
    ]
    try:
        p_list = Settings.validate_protected_paths(expanded_p_list)
    except ValueError as e:
        self._report_settings_error(str(e))
        return

    i_str = self.query_one("#input-ignored", Input).value
    raw_i_list = [i.strip() for i in i_str.split(",") if i.strip()]
    try:
        i_list = Settings.validate_ignored_extensions(raw_i_list)
    except ValueError as e:
        self._report_settings_error(str(e))
        return

    try:
        conc_val = self.query_one("#input-concurrency", Input).value.strip()
        conc = int(conc_val)
        if not (1 <= conc <= 64):
            raise ValueError("Worker concurrency must be between 1 and 64.")
    except ValueError as e:
        self._report_settings_error(str(e))
        return

    try:
        max_f_val = self.query_one("#input-max-folders", Input).value.strip()
        max_f = int(max_f_val)
        if not (1 <= max_f <= 50):
            raise ValueError("Max folders must be between 1 and 50.")
    except ValueError as e:
        self._report_settings_error(str(e))
        return

    try:
        density_val_str = self.query_one(
            "#input-pdf-density-threshold", Input
        ).value.strip()
        pdf_density = int(density_val_str)
        if pdf_density < 0:
            raise ValueError("PDF text density threshold must be non-negative.")
    except ValueError as e:
        self._report_settings_error(str(e))
        return

    strat = self.query_one("#select-strategy", Select).value
    if strat == Select.BLANK:
        strat = "default"
    if strat == "generative" and not self._generative_ready:
        self._report_settings_error(
            "Generative AI requires valid local GGUF weights via GENERATIVE_NAMING_PATH "
            "and optional ML extras ('smart-autosorter[ml]')."
        )
        return

    try:
        clin_renaming = self.query_one("#switch-clinical-renaming", Switch).value
    except Exception:
        clin_renaming = bool(
            getattr(self.settings, "CLINICAL_SMART_RENAMING", False)
        )
    try:
        ctx_renaming = self.query_one("#switch-contextual-renaming", Switch).value
    except Exception:
        ctx_renaming = bool(getattr(self.settings, "CONTEXTUAL_RENAMING", False))
    try:
        speak = self.query_one("#switch-speak-announcements", Switch).value
    except Exception:
        speak = bool(getattr(self.settings, "SPEAK_ANNOUNCEMENTS", False))
    try:
        char_shortcuts = self.query_one(
            "#switch-character-key-shortcuts", Switch
        ).value
    except Exception:
        char_shortcuts = bool(
            getattr(self.settings, "ENABLE_CHARACTER_KEY_SHORTCUTS", True)
        )
    try:
        ai_consent = self.query_one("#switch-ai-consent", Switch).value
    except Exception:
        ai_consent = bool(getattr(self.settings, "AI_CONSENT_GRANTED", False))

    try:
        conflict_pol = self.query_one("#select-conflict-policy", Select).value
        if conflict_pol == Select.BLANK:
            conflict_pol = "rename"
    except Exception:
        conflict_pol = getattr(self.settings, "CONFLICT_POLICY", "rename")

    try:
        dup_sel_val = self.query_one("#select-duplicate-action", Select).value
        duplicate_action = (
            str(dup_sel_val)
            if dup_sel_val is not None and dup_sel_val != Select.BLANK
            else str(getattr(self.settings, "DUPLICATE_ACTION", "off") or "off")
        )
    except Exception:
        duplicate_action = str(
            getattr(self.settings, "DUPLICATE_ACTION", "off") or "off"
        )

    try:
        det_sel_val = self.query_one("#select-detect-original-by", Select).value
        detect_original_by = (
            str(det_sel_val)
            if det_sel_val is not None and det_sel_val != Select.BLANK
            else str(
                getattr(self.settings, "DETECT_ORIGINAL_BY", "first_seen")
                or "first_seen"
            )
        )
    except Exception:
        detect_original_by = str(
            getattr(self.settings, "DETECT_ORIGINAL_BY", "first_seen")
            or "first_seen"
        )

    try:
        q_dir_raw = self.query_one("#input-quarantine-dir", Input).value.strip()
    except Exception:
        q_dir_raw = getattr(
            self.settings, "QUARANTINE_DIR_NAME", "_Compliance_Quarantine"
        )
    q_dir_str = q_dir_raw or "_Compliance_Quarantine"
    from app.core.path_utils import validate_target_path

    try:
        if any(ch in q_dir_str for ch in ("*", "?", "[", "]")):
            raise ValueError(
                "Wildcard characters are not allowed in quarantine folder name."
            )
        validate_target_path(q_dir_str, keyword="QUARANTINE_DIR_NAME")
    except ValueError as e:
        self._report_settings_error(f"Invalid quarantine folder name: {e}")
        return

    existing_ratings = [
        str(r).upper()
        for r in (getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or [])
        if r and str(r).upper() not in ("CRITICAL", "HIGH")
    ]
    try:
        q_crit = self.query_one("#switch-quarantine-critical", Switch).value
    except Exception:
        q_crit = "CRITICAL" in {
            str(r).upper()
            for r in (getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or [])
        }
    try:
        q_high = self.query_one("#switch-quarantine-high", Switch).value
    except Exception:
        q_high = "HIGH" in {
            str(r).upper()
            for r in (getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or [])
        }
    auto_quarantine_ratings: list[str] = []
    if q_crit:
        auto_quarantine_ratings.append("CRITICAL")
    if q_high:
        auto_quarantine_ratings.append("HIGH")
    for extra_r in existing_ratings:
        if extra_r not in auto_quarantine_ratings:
            auto_quarantine_ratings.append(extra_r)

    try:
        cleanup_empty = self.query_one(
            "#switch-cleanup-empty-folders", Switch
        ).value
    except Exception:
        cleanup_empty = bool(getattr(self.settings, "CLEANUP_EMPTY_FOLDERS", True))
    try:
        preserve_hier = self.query_one("#switch-preserve-hierarchy", Switch).value
    except Exception:
        preserve_hier = bool(getattr(self.settings, "PRESERVE_HIERARCHY", False))

    try:
        scan_depth_str = self.query_one(
            "#input-scan-max-depth", Input
        ).value.strip()
    except (NoMatches, LookupError, AttributeError):
        scan_depth_str = str(getattr(self.settings, "SCAN_MAX_DEPTH", 0))
    try:
        scan_max_depth = int(scan_depth_str)
        if not (0 <= scan_max_depth <= 20):
            raise ValueError("Max Scan Depth must be between 0 and 20.")
    except ValueError:
        self._report_settings_error(
            f"Invalid Max Scan Depth '{scan_depth_str}'. "
            "Expected an integer from 0 to 20."
        )
        return

    if preserve_hier and scan_max_depth == 0:
        was_previously_enabled = bool(
            getattr(self.settings, "PRESERVE_HIERARCHY", False)
        )
        if (
            not was_previously_enabled
            and not self._preserve_hierarchy_promoted_depth
            and not self._scan_depth_edited_by_user
        ):
            scan_max_depth = 5
            self._preserve_hierarchy_promoted_depth = True
            with contextlib.suppress(NoMatches, LookupError, AttributeError):
                self._syncing_scan_depth_promotion = True
                try:
                    self.query_one("#input-scan-max-depth", Input).value = "5"
                finally:
                    self._syncing_scan_depth_promotion = False
        else:
            self._report_settings_error(
                "Max Scan Depth must be at least 1 when Preserve Folder Hierarchy is enabled."
            )
            with contextlib.suppress(NoMatches, LookupError, AttributeError):
                self.query_one("#input-scan-max-depth", Input).focus()
            return

    try:
        rename_pat_raw = self.query_one(
            "#input-rename-pattern", Input
        ).value.strip()
    except Exception:
        rename_pat_raw = str(getattr(self.settings, "RENAME_PATTERN", "") or "")
    if rename_pat_raw:
        from app.core.path_utils import ILLEGAL_PATH_CHARS_SET

        if (
            "/" in rename_pat_raw
            or "\\" in rename_pat_raw
            or ".." in rename_pat_raw
            or "\x00" in rename_pat_raw
            or any(ch in ILLEGAL_PATH_CHARS_SET for ch in rename_pat_raw)
        ):
            self._report_settings_error(
                "Default rename template cannot contain path separators, '..', "
                "null bytes, or illegal filename characters."
            )
            return

    if not ai_consent and (
        self._staged_consent_revocation
        or getattr(self.settings, "AI_CONSENT_GRANTED", None) is True
    ):
        self._staged_consent_revocation = False
        self._execute_scrub_and_purge()

    try:
        sw_ai_assisted_val = bool(
            self.query_one("#switch-ai-assisted-naming", Switch).value
        )
    except (NoMatches, LookupError, AttributeError):
        sw_ai_assisted_val = bool(
            getattr(self.settings, "AI_ASSISTED_NAMING", False)
        )

    ai_assisted_naming = bool(ai_consent and sw_ai_assisted_val)

    res = {
        "PROTECTED_PATHS": p_list,
        "IGNORED_EXTENSIONS": i_list,
        "MAX_WORKERS": conc,
        "MAX_FOLDERS": max_f,
        "PDF_TEXT_DENSITY_THRESHOLD": pdf_density,
        "CONFLICT_POLICY": conflict_pol,
        "DUPLICATE_ACTION": duplicate_action,
        "DETECT_ORIGINAL_BY": detect_original_by,
        "SORTING_STRATEGY": strat,
        "AI_ASSISTED_NAMING": ai_assisted_naming,
        "CLINICAL_SMART_RENAMING": clin_renaming,
        "CONTEXTUAL_RENAMING": ctx_renaming,
        "RENAME_PATTERN": rename_pat_raw,
        "AI_CONSENT_GRANTED": ai_consent,
        "SPEAK_ANNOUNCEMENTS": speak,
        "ENABLE_CHARACTER_KEY_SHORTCUTS": char_shortcuts,
        "CLEANUP_EMPTY_FOLDERS": cleanup_empty,
        "PRESERVE_HIERARCHY": preserve_hier,
        "SCAN_MAX_DEPTH": scan_max_depth,
        "AUTO_QUARANTINE_RATINGS": auto_quarantine_ratings,
        "QUARANTINE_DIR_NAME": q_dir_str,
    }
    self.announce("Saved application settings.")
    self.dismiss(res)

action_scrub_artifacts()

Open Scrub AI Artifacts confirmation modal.

Source code in app/ui/modals/settings.py
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
@on(Button.Pressed, "#btn-scrub-artifacts")
def action_scrub_artifacts(self) -> None:
    """Open Scrub AI Artifacts confirmation modal."""
    db_inst = getattr(self.app, "db", None) if hasattr(self, "app") else None
    v_count = _get_vector_count(db_inst)
    footprint_mb = _get_model_cache_footprint_mb()

    def _on_scrub_modal_result(confirmed: bool | None) -> None:
        if confirmed:
            self._execute_scrub_and_purge()

    if hasattr(self, "app") and self.app:
        self.app.push_screen(
            ScrubArtifactsModal(v_count, footprint_mb), _on_scrub_modal_result
        )

compose()

Compose modal dialog children.

Source code in app/ui/modals/settings.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
def compose(self) -> ComposeResult:
    """Compose modal dialog children."""
    with ModalBox(classes="modal-box"):
        yield Heading(
            "Application Settings [Ctrl+O]",
            level=1,
            classes="modal-title",
            id="modal-title",
        )
        with TabbedContent(initial="tab-general", id="settings-tabbed-content"):
            with TabPane(
                "General Settings", id="tab-general", classes="modal-body"
            ):
                yield Label(
                    "Protected Directories (comma-separated):",
                    classes="field-label",
                )
                prot = getattr(self.settings, "PROTECTED_PATHS", [])
                prot_str = (
                    ", ".join(prot)
                    if isinstance(prot, (list, tuple, set))
                    else str(prot)
                )
                inp_prot = Input(
                    value=prot_str,
                    placeholder="/path/1, /path/2",
                    id="input-protected",
                )
                inp_prot.tooltip = "Comma-separated protected directories exempt from automated moves"
                yield inp_prot

                yield Label(
                    "Ignored Extensions (comma-separated):",
                    classes="field-label",
                )
                ign = getattr(self.settings, "IGNORED_EXTENSIONS", [])
                ign_str = (
                    ", ".join(ign)
                    if isinstance(ign, (list, tuple, set))
                    else str(ign)
                )
                inp_ign = Input(
                    value=ign_str,
                    placeholder=".tmp, .bak, .log",
                    id="input-ignored",
                )
                inp_ign.tooltip = (
                    "Comma-separated file extensions to ignore during scanning"
                )
                yield inp_ign

                yield Label("Max Folders:", classes="field-label")
                max_f_str = str(getattr(self.settings, "MAX_FOLDERS", 12))
                inp_max_f = Input(
                    value=max_f_str, placeholder="12", id="input-max-folders"
                )
                inp_max_f.tooltip = (
                    "Maximum subdirectories generated during sorting"
                )
                yield inp_max_f

                yield Label("Worker Concurrency (Threads):", classes="field-label")
                conc_str = str(getattr(self.settings, "MAX_WORKERS", 4))
                inp_conc = Input(
                    value=conc_str, placeholder="4", id="input-concurrency"
                )
                inp_conc.tooltip = "Worker concurrency thread limit for processing"
                yield inp_conc

                yield Label("Conflict Policy:", classes="field-label")
                conflict_pol = getattr(self.settings, "CONFLICT_POLICY", "rename")
                conflict_options = [
                    ("Overwrite", "overwrite"),
                    ("Auto-Rename", "rename"),
                    ("Skip", "skip"),
                ]
                sel_conflict = Select(
                    options=conflict_options,
                    value=conflict_pol,
                    id="select-conflict-policy",
                )
                sel_conflict.tooltip = "Select collision handling strategy for conflicting target files"
                yield sel_conflict

                yield Heading("Duplicate Handling:", level=2, classes="field-label")
                dup_act_raw = str(
                    getattr(self.settings, "DUPLICATE_ACTION", "off") or "off"
                ).lower()
                dup_options = [
                    ("Off (ignore byte-identical duplicates)", "off"),
                    ("Interactive Review (confirm before execution)", "review"),
                    ("Skip Redundant Copies (keep original only)", "skip"),
                    ("Stage Copies for Undo (.sortify_duplicates)", "stage"),
                    ("Trash Copies (two-step staging)", "trash"),
                ]
                valid_dup_acts = {val for _lbl, val in dup_options}
                dup_act_val = (
                    dup_act_raw if dup_act_raw in valid_dup_acts else "off"
                )
                sel_dup = Select(
                    dup_options,
                    value=dup_act_val,
                    allow_blank=False,
                    id="select-duplicate-action",
                )
                sel_dup.tooltip = (
                    "Select how byte-identical duplicate files are handled"
                )
                setattr(
                    sel_dup,
                    "aria_label",
                    "Byte-identical duplicate handling mode",
                )
                yield sel_dup

                yield Heading(
                    "Original Selection Criterion:",
                    level=2,
                    classes="field-label",
                )
                det_orig_raw = str(
                    getattr(self.settings, "DETECT_ORIGINAL_BY", "first_seen")
                    or "first_seen"
                ).lower()
                det_orig_options = [
                    ("First Seen (discovery order)", "first_seen"),
                    ("Last Seen (reverse discovery order)", "-first_seen"),
                    ("Filename (A -> Z)", "name"),
                    ("Filename (Z -> A)", "-name"),
                    ("Oldest Created Timestamp", "created"),
                    ("Newest Created Timestamp", "-created"),
                    ("Oldest Modified Timestamp", "lastmodified"),
                    ("Newest Modified Timestamp", "-lastmodified"),
                ]
                valid_det_orig = {val for _lbl, val in det_orig_options}
                det_orig_val = (
                    det_orig_raw if det_orig_raw in valid_det_orig else "first_seen"
                )
                sel_det_orig = Select(
                    det_orig_options,
                    value=det_orig_val,
                    allow_blank=False,
                    id="select-detect-original-by",
                )
                sel_det_orig.tooltip = "Select tie-breaker criterion for choosing the surviving original file"
                setattr(
                    sel_det_orig,
                    "aria_label",
                    "Surviving original selection criterion",
                )
                yield sel_det_orig

                yield LabeledSwitch(
                    label="Cleanup Empty Folders",
                    value=bool(
                        getattr(self.settings, "CLEANUP_EMPTY_FOLDERS", True)
                    ),
                    switch_id="switch-cleanup-empty-folders",
                    tooltip="Automatically prune empty source directories after moving organized files",
                )

                yield LabeledSwitch(
                    label="Preserve Folder Hierarchy",
                    value=bool(getattr(self.settings, "PRESERVE_HIERARCHY", False)),
                    switch_id="switch-preserve-hierarchy",
                    tooltip="Maintain source directory levels and folder structure during classification",
                )

                yield Label(
                    "Max Scan Depth (0 = top-level only):",
                    classes="field-label",
                )
                inp_scan_depth = Input(
                    value=str(getattr(self.settings, "SCAN_MAX_DEPTH", 0)),
                    id="input-scan-max-depth",
                )
                inp_scan_depth.tooltip = (
                    "Maximum subfolder depth to scan (0 keeps subfolders untouched)"
                )
                yield inp_scan_depth

            with TabPane(
                "AI & Privacy Settings",
                id="tab-ai-privacy",
                classes="modal-body",
            ):
                from app.core.downloader import (
                    get_ai_runtime_state,
                    inspect_generative_runtime_state,
                )
                from app.core.plugin_registry import PluginRegistry

                onnx_state = get_ai_runtime_state(self.settings)
                gen_state = inspect_generative_runtime_state()
                self._generative_state = gen_state
                self._generative_ready = bool(gen_state.get("ready", False))

                strat = str(
                    getattr(self.settings, "SORTING_STRATEGY", "default")
                    or "default"
                )
                if self._generative_ready and strat == "generative":
                    self._last_valid_strategy = "generative"
                elif strat != "generative":
                    self._last_valid_strategy = strat
                else:
                    self._last_valid_strategy = "default"

                gen_option_label = (
                    "Generative AI (Local GGUF)"
                    if self._generative_ready
                    else "Generative AI (Unavailable — Local GGUF Setup Required)"
                )
                yield Heading("Sorting Strategy:", level=2, classes="field-label")
                options = [
                    ("Standard Semantic", "default"),
                    (gen_option_label, "generative"),
                ]

                reg = PluginRegistry.get_instance()
                reg.load_plugins_from_settings(self.settings)
                options.extend(reg.get_tui_strategy_options())
                if not any(opt[1] == strat for opt in options):
                    options.append((f"Extension ({strat})", strat))
                sel_strat = Select(
                    options=options, value=strat, id="select-strategy"
                )
                sel_strat.tooltip = (
                    "Select sorting strategy engine for document classification"
                )
                yield sel_strat

                yield Heading(
                    "Local AI Capability Readiness:",
                    level=2,
                    classes="field-label",
                )
                onnx_txt, gguf_txt, gguf_guidance_txt = (
                    self._format_ai_readiness_texts(onnx_state, gen_state)
                )
                with Vertical(classes="readiness-panel", id="ai-readiness-panel"):
                    yield Label(
                        onnx_txt,
                        id="lbl-onnx-readiness",
                        classes="readiness-row",
                        markup=False,
                    )
                    yield Label(
                        gguf_txt,
                        id="lbl-gguf-readiness",
                        classes="readiness-row",
                        markup=False,
                    )
                    lbl_guidance = Label(
                        gguf_guidance_txt,
                        id="lbl-gguf-setup-guidance",
                        classes="readiness-guidance",
                        markup=False,
                    )
                    lbl_guidance.display = bool(gguf_guidance_txt)
                    yield lbl_guidance

                yield Heading(
                    "Compliance & Renaming Toggles:",
                    level=2,
                    classes="field-label",
                )
                for sw_cfg in reg.get_tui_switches():
                    sw_key = sw_cfg.get("key", "")
                    sw_id = sw_cfg.get("id", f"switch-{sw_key.lower()}")
                    sw_lbl = sw_cfg.get("label", f" {sw_key}")
                    sw_tip = sw_cfg.get("tooltip", "")
                    sw_val = bool(getattr(self.settings, sw_key, False))
                    yield LabeledSwitch(
                        label=sw_lbl,
                        value=sw_val,
                        switch_id=sw_id,
                        tooltip=sw_tip,
                    )

                ai_consent_val = bool(
                    getattr(self.settings, "AI_CONSENT_GRANTED", False)
                )
                ai_assisted_val = bool(
                    ai_consent_val
                    and getattr(self.settings, "AI_ASSISTED_NAMING", False)
                )

                yield LabeledSwitch(
                    label="AI Consent Granted",
                    value=ai_consent_val,
                    switch_id="switch-ai-consent",
                    tooltip="Toggle AI consent for semantic document classification and processing",
                )

                yield LabeledSwitch(
                    label="AI Assisted Naming",
                    value=ai_assisted_val,
                    switch_id="switch-ai-assisted-naming",
                    disabled=not ai_consent_val,
                    tooltip="Rank semantic file keyphrases via local ONNX embeddings independently of Sorting Strategy (requires AI Consent Granted)",
                )

                yield LabeledSwitch(
                    label="AI Contextual Renaming",
                    value=bool(
                        getattr(self.settings, "CONTEXTUAL_RENAMING", False)
                    ),
                    switch_id="switch-contextual-renaming",
                    tooltip="Replace generic scan stems (e.g. scan_01) with document keywords while keeping descriptive stems intact unless {keywords} is in template",
                )

                yield Label(
                    "Default Rename Template:",
                    classes="field-label",
                )
                yield Label(
                    "Applies standalone with literal {stem}/{original}; enable AI Contextual Renaming or add {keywords} to insert document terms.",
                    classes="setting-hint",
                    id="lbl-rename-template-hint",
                )
                ren_pat_val = str(
                    getattr(self.settings, "RENAME_PATTERN", "") or ""
                )
                inp_ren_pat = Input(
                    value=ren_pat_val,
                    placeholder="e.g. {date}_{stem}{extension} or {date}_{keywords}_{stem}",
                    id="input-rename-pattern",
                )
                inp_ren_pat.tooltip = "Standalone rename template supporting literal {stem}/{original}, extracted {keywords}, {date}, {year}, {month}, {day}, {category}, {seq}, and {extension}"
                yield inp_ren_pat

                current_auto_ratings = {
                    str(r).upper()
                    for r in (
                        getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or []
                    )
                    if r
                }
                yield LabeledSwitch(
                    label="Auto-Quarantine CRITICAL Sensitivity",
                    value="CRITICAL" in current_auto_ratings,
                    switch_id="switch-quarantine-critical",
                    tooltip="Automatically hold CRITICAL sensitivity documents in compliance quarantine during sorting and daemon monitoring",
                )

                yield LabeledSwitch(
                    label="Auto-Quarantine HIGH Sensitivity",
                    value="HIGH" in current_auto_ratings,
                    switch_id="switch-quarantine-high",
                    tooltip="Automatically hold HIGH sensitivity documents in compliance quarantine during sorting and daemon monitoring",
                )

                yield Label(
                    "Compliance Quarantine Folder Name:",
                    classes="field-label",
                )
                q_dir_val = (
                    getattr(
                        self.settings,
                        "QUARANTINE_DIR_NAME",
                        "_Compliance_Quarantine",
                    )
                    or "_Compliance_Quarantine"
                )
                inp_qdir = Input(
                    value=str(q_dir_val),
                    placeholder="_Compliance_Quarantine",
                    id="input-quarantine-dir",
                )
                inp_qdir.tooltip = "Workspace subfolder name used when staging held compliance files"
                yield inp_qdir

                yield LabeledSwitch(
                    label="Speak Status Messages Aloud",
                    value=bool(
                        getattr(self.settings, "SPEAK_ANNOUNCEMENTS", False)
                    ),
                    switch_id="switch-speak-announcements",
                    tooltip="Read each status message aloud with the system speech command (say / spd-say)",
                )

                yield LabeledSwitch(
                    label="Single-Character Shortcuts",
                    value=bool(
                        getattr(
                            self.settings,
                            "ENABLE_CHARACTER_KEY_SHORTCUTS",
                            True,
                        )
                    ),
                    switch_id="switch-character-key-shortcuts",
                    tooltip="Enable single-character keyboard shortcuts in the plan tree (WCAG 2.1.4)",
                )

                btn_scrub = Button(
                    "Scrub AI Artifacts",
                    id="btn-scrub-artifacts",
                    variant="warning",
                )
                btn_scrub.tooltip = "Report vector count and cache footprint, and scrub stored vectors and model files"
                yield btn_scrub

                btn_templates = Button(
                    "Starter Rule Template Gallery",
                    id="btn-open-templates",
                    variant="primary",
                )
                btn_templates.tooltip = (
                    "View and apply pre-configured starter rule template packs"
                )
                yield btn_templates

                btn_active_rules = Button(
                    "Active Rule Manager",
                    id="btn-open-rules",
                    variant="primary",
                )
                btn_active_rules.tooltip = "Inspect, add, edit, toggle, and delete active rules and policies"
                yield btn_active_rules

            with TabPane(
                "Extraction & OCR",
                id="tab-extraction",
                classes="modal-body",
            ):
                yield Label(
                    "PDF Text Density Threshold (chars/page):",
                    classes="field-label",
                )
                density_val = getattr(
                    self.settings, "PDF_TEXT_DENSITY_THRESHOLD", 50
                )
                inp_density = Input(
                    value=str(density_val),
                    placeholder="50",
                    id="input-pdf-density-threshold",
                )
                inp_density.tooltip = "Pages with fewer embedded characters trigger EasyOCR rasterization fallback"
                yield inp_density

                slider_density = DensitySlider(
                    value=int(density_val),
                    min_value=0,
                    max_value=500,
                    step=5,
                    id="slider-pdf-density-threshold",
                )
                slider_density.tooltip = "Adjust PDF text density threshold slider"
                yield slider_density

        yield Static(
            "",
            id="lbl-settings-error",
            classes="settings-error hidden",
            markup=False,
        )
        with Horizontal(classes="button-row"):
            btn_cancel = Button("Cancel", id="btn-cancel", variant="default")
            btn_cancel.tooltip = "Cancel settings modification and close dialog"
            yield btn_cancel
            btn_model_mgr = Button(
                "Model Manager", id="btn-model-mgr", variant="primary"
            )
            btn_model_mgr.tooltip = (
                "Open dedicated interactive model management modal"
            )
            yield btn_model_mgr
            btn_help = Button(
                "Help", id="btn-help", variant="warning", classes="hidden"
            )
            btn_help.tooltip = "Open settings configuration troubleshooting guide"
            yield btn_help
            btn_save = Button("Save Settings", id="btn-save", variant="primary")
            btn_save.tooltip = "Save modified application settings"
            yield btn_save

on_ai_assisted_naming_changed(event)

Record explicit user toggles on AI Assisted Naming.

Source code in app/ui/modals/settings.py
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
@on(Switch.Changed, "#switch-ai-assisted-naming")
def on_ai_assisted_naming_changed(self, event: Switch.Changed) -> None:
    """Record explicit user toggles on AI Assisted Naming."""
    if self._syncing_ai_switches:
        return
    self._ai_assisted_naming_touched = True
    self._remembered_ai_assisted_val = bool(event.value)
    state_str = "enabled" if event.value else "disabled"
    if hasattr(self, "announce"):
        self.announce(f"AI assisted naming {state_str}.", priority="polite")

Prompt user confirmation when AI consent switch is toggled off.

Source code in app/ui/modals/settings.py
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
@on(Switch.Changed, "#switch-ai-consent")
def on_ai_consent_changed(self, event: Switch.Changed) -> None:
    """Prompt user confirmation when AI consent switch is toggled off."""
    if event.value:
        self._staged_consent_revocation = False
        self._set_ai_assisted_switch_enabled(
            True, value=self._remembered_ai_assisted_val
        )
        return

    self._set_ai_assisted_switch_enabled(False, value=False)

    db_inst = getattr(self.app, "db", None) if hasattr(self, "app") else None
    v_count = _get_vector_count(db_inst)
    footprint_mb = _get_model_cache_footprint_mb()

    def _on_revoke_modal_result(confirmed: bool | None) -> None:
        if confirmed:
            self._staged_consent_revocation = True
            self._set_ai_assisted_switch_enabled(False, value=False)
            if hasattr(self, "announce"):
                self.announce(
                    "AI consent revocation staged; save settings to apply.",
                    priority="polite",
                )
        else:
            self._staged_consent_revocation = False
            event.switch.value = True

    if hasattr(self, "app") and self.app and self.is_current:
        self.app.push_screen(
            ConsentRevocationModal(v_count, footprint_mb),
            _on_revoke_modal_result,
        )

on_character_shortcuts_changed(event)

Announce shortcut status update when single-character shortcuts switch is toggled.

Source code in app/ui/modals/settings.py
1162
1163
1164
1165
1166
1167
@on(Switch.Changed, "#switch-character-key-shortcuts")
def on_character_shortcuts_changed(self, event: Switch.Changed) -> None:
    """Announce shortcut status update when single-character shortcuts switch is toggled."""
    self._announce_switch_toggle(
        "#switch-character-key-shortcuts", bool(event.value)
    )

on_mount()

Focus initial input field on mount and emit announcement.

Source code in app/ui/modals/settings.py
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
def on_mount(self) -> None:
    """Focus initial input field on mount and emit announcement."""
    super().on_mount()
    self._apply_generative_select_gate()
    self.query_one("#input-protected", Input).focus(scroll_visible=False)
    self.query_one(".modal-box", ModalBox).scroll_home(
        animate=False, immediate=True
    )
    for sw_id in (
        "#switch-character-key-shortcuts",
        "#switch-quarantine-critical",
        "#switch-quarantine-high",
    ):
        try:
            sw = self.query_one(sw_id, Switch)
            self._announced_switch_values[sw_id] = bool(sw.value)
            self.watch(
                sw,
                "value",
                lambda val, sid=sw_id: self._announce_switch_toggle(sid, bool(val)),
                init=False,
            )
        except Exception:
            pass
    self.announce("Opened application settings dialog.")

on_quarantine_critical_changed(event)

Announce status update when CRITICAL sensitivity auto-quarantine switch is toggled.

Source code in app/ui/modals/settings.py
1169
1170
1171
1172
@on(Switch.Changed, "#switch-quarantine-critical")
def on_quarantine_critical_changed(self, event: Switch.Changed) -> None:
    """Announce status update when CRITICAL sensitivity auto-quarantine switch is toggled."""
    self._announce_switch_toggle("#switch-quarantine-critical", bool(event.value))

on_quarantine_high_changed(event)

Announce status update when HIGH sensitivity auto-quarantine switch is toggled.

Source code in app/ui/modals/settings.py
1174
1175
1176
1177
@on(Switch.Changed, "#switch-quarantine-high")
def on_quarantine_high_changed(self, event: Switch.Changed) -> None:
    """Announce status update when HIGH sensitivity auto-quarantine switch is toggled."""
    self._announce_switch_toggle("#switch-quarantine-high", bool(event.value))

on_strategy_changed(event)

Enforce local GGUF readiness gate on Generative AI without mutating AI Assisted Naming.

Source code in app/ui/modals/settings.py
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
@on(Select.Changed, "#select-strategy")
def on_strategy_changed(self, event: Select.Changed) -> None:
    """Enforce local GGUF readiness gate on Generative AI without mutating AI Assisted Naming."""
    if self._syncing_strategy_select:
        return
    selected_val = (
        "default"
        if event.value is None or event.value == Select.BLANK
        else str(event.value)
    )
    if selected_val == "generative" and not self._generative_ready:
        self._syncing_strategy_select = True
        try:
            cast(Select[str], event.select).value = self._last_valid_strategy
        finally:
            self._syncing_strategy_select = False
        msg = (
            "Generative AI is unavailable: set GENERATIVE_NAMING_PATH to a valid "
            "local .gguf model and install 'smart-autosorter[ml]'."
        )
        from app.ui.notifications import notify

        notify(msg, type="warning")
        if hasattr(self, "announce"):
            self.announce(msg, priority="assertive")
        return
    self._last_valid_strategy = selected_val

query_one(selector, expect_type=None)

Query one widget, aliasing alternative switch IDs.

Source code in app/ui/modals/settings.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
def query_one(self, selector: Any, expect_type: Any = None) -> Any:
    """Query one widget, aliasing alternative switch IDs."""
    if selector in (
        "#switch-enable-character-key-shortcuts",
        "#switch-character-shortcuts",
    ):
        selector = "#switch-character-key-shortcuts"
    elif selector in (
        "#switch-cleanup",
        "#switch-cleanup-folders",
        "#switch-cleanup-empty-directories",
        "#switch-empty-directory-cleanup",
        "#switch-clean-up-empty-folders",
    ):
        selector = "#switch-cleanup-empty-folders"
    elif selector in (
        "#switch-preserve",
        "#switch-preserve-folder-hierarchy",
        "#switch-folder-hierarchy-preservation",
        "#switch-preserve-directory-hierarchy",
        "#switch-hierarchy",
    ):
        selector = "#switch-preserve-hierarchy"
    elif selector in (
        "#switch-ai-assisted",
        "#switch-assisted-naming",
    ):
        selector = "#switch-ai-assisted-naming"
    return super().query_one(selector, expect_type=expect_type)

app.ui.modals.wizard

app.ui.modals.wizard

First-run onboarding wizard.

WizardModal

Bases: ResponsiveModalScreen[None]

Modal dialog for model onboarding wizard.

Source code in app/ui/modals/wizard.py
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
class WizardModal(ResponsiveModalScreen[None]):
    """Modal dialog for model onboarding wizard."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel dialog", show=True),
        Binding("question_mark", "open_help_overlay(True)", "Help", show=False),
        Binding("f1", "open_help_overlay(False)", "Help", show=False),
    ]

    MODAL_CSS = """
    .modal-frame {
        padding: 1 2;
        background: $panel;
        border: thick $primary;
        width: 90%;
        max-width: 80;
        min-width: 30;
        height: auto;
        max-height: 90%;
        overflow-y: hidden;
    }
    .modal-box {
        padding: 0;
        border: none;
        width: 100%;
        max-width: 100%;
        min-width: 0;
        max-height: 100%;
        overflow-y: auto;
    }
    .privacy-card {
        border: round $primary;
        padding: 0 1;
        margin-top: 1;
        margin-bottom: 1;
        background: $surface;
        height: auto;
    }
    .privacy-card:focus {
        border: heavy $accent;
    }
    .privacy-badge {
        color: $success;
        text-style: bold;
    }
    .privacy-title {
        color: $accent;
        text-style: bold;
    }
    .privacy-guarantee {
        color: $text;
    }
    .field-label {
        margin-top: 1;
        color: $text;
        text-style: bold;
    }
    .error-banner {
        color: $error;
        text-style: bold;
    }
    .preset-label {
        margin-top: 1;
        color: $text-muted;
    }
    .preset-row {
        width: 100%;
        layout: grid;
        grid-size: 3;
        grid-gutter: 0 1;
        margin-top: 1;
        margin-bottom: 1;
        height: auto;
        min-height: 3;
    }
    .preset-row Button {
        width: 100%;
        min-width: 0;
    }
    .switch-row {
        margin-top: 1;
        margin-bottom: 1;
        height: 3;
        align: left middle;
    }
    .button-row {
        height: auto;
        min-height: 4;
        align: right middle;
    }
    .rule-summary {
        width: 100%;
        height: 1;
        color: $text-muted;
        text-overflow: ellipsis;
        overflow: hidden;
    }
    Button:focus, Checkbox:focus, Switch:focus, Input:focus, .privacy-card:focus {
        border: heavy $accent;
        text-style: bold;
    }
    Checkbox {
        height: 1;
        border: none;
        padding: 0 1;
    }
    WizardModal {
        &.compact .modal-frame {
            padding: 0 1;
            width: 96%;
            max-height: 96%;
        }
        &.narrow .modal-frame {
            padding: 0 1;
            width: 96%;
        }
        &.compact .modal-box, &.narrow .modal-box {
            padding: 0;
            width: 100%;
            max-height: 100%;
        }
        &.narrow .privacy-card {
            padding: 0 1;
            border: round $primary;
        }
        &.compact .privacy-card {
            margin-top: 0;
            margin-bottom: 0;
        }
        &.compact .field-label, &.compact .preset-label {
            margin-top: 0;
        }
        &.compact .switch-row {
            margin-top: 0;
            margin-bottom: 0;
        }
        &.compact .button-row {
            margin-top: 0;
            min-height: 2;
        }
        &.compact .preset-row {
            margin-top: 0;
            margin-bottom: 0;
            min-height: 1;
        }
        &.compact .preset-row Button {
            height: 1;
            min-height: 1;
            border: none;
        }
        &.narrow .preset-row {
            grid-size: 2;
        }
        &.narrow .button-row Button {
            min-width: 0;
            padding: 0 1;
        }
    }
    """

    def __init__(self, settings, current_dir: str | None = None):
        super().__init__()
        self.settings = settings
        self.current_dir = current_dir
        self._playground_committed_dir: str | None = None
        self._sample_auto_enabled_by_demo: bool = False
        self._packs_auto_suggested_by_preset: set[str] = set()
        self._updating_preset_packs: bool = False

    def compose(self) -> ComposeResult:
        """Compose modal dialog children."""
        with ModalBox(classes="modal-frame"):
            with Vertical(classes="modal-body modal-box"):
                yield Heading(
                    "Model Onboarding Wizard [Ctrl+W]",
                    level=1,
                    classes="modal-title",
                    id="modal-title",
                )
                yield Label("Welcome to Smart AutoSorter AI Pro TUI.")
                yield Label("Enable AI semantic categorization consent below:")

                priv_card = Vertical(id="privacy-card", classes="privacy-card")
                priv_card.can_focus = True
                priv_card.tooltip = (
                    "Local-first privacy guarantees: 100% local model execution, "
                    "zero document cloud telemetry, and encrypted local SQLCipher storage"
                )
                with priv_card:
                    yield Label(
                        "[100% On-Device & Offline]",
                        classes="privacy-badge",
                        id="privacy-badge",
                    )
                    yield Label(
                        "Local-First Privacy Guarantees:",
                        classes="privacy-title",
                        id="privacy-card-title",
                    )
                    yield Label(
                        "• 100% local model execution: ML classification and clustering run entirely on-device.",
                        classes="privacy-guarantee",
                        id="privacy-guarantee-local",
                    )
                    yield Label(
                        "• Zero document cloud telemetry: Document contents and names are never sent to external servers.",
                        classes="privacy-guarantee",
                        id="privacy-guarantee-telemetry",
                    )
                    yield Label(
                        "• Encrypted local SQLCipher storage: Databases, extracted text, and vectors are encrypted at rest.",
                        classes="privacy-guarantee",
                        id="privacy-guarantee-storage",
                    )

                consent_val = getattr(self.settings, "AI_CONSENT_GRANTED", None)
                if consent_val is None:
                    consent_val = False
                sw_consent = LabeledSwitch(
                    label="AI Consent Granted",
                    value=bool(consent_val),
                    switch_id="switch-consent",
                    tooltip=(
                        "Toggle AI consent for semantic document classification "
                        "([100% On-Device & Offline]: 100% local model execution, "
                        "zero document cloud telemetry, and encrypted local SQLCipher storage)"
                    ),
                )
                self._watch_toggle_control(sw_consent, self.on_switch_changed)
                yield sw_consent

                yield Label(
                    self._format_model_status_text(
                        consent_enabled=bool(consent_val),
                        defer_download=False,
                    ),
                    id="lbl-wizard-model-status",
                    markup=False,
                )

                chk_defer = Checkbox(
                    "Defer model download (metered or offline network)",
                    value=False,
                    id="chk-defer-download",
                )
                chk_defer.tooltip = "Skip automatic background model download and sort immediately with local keyword/TF-IDF rules"
                self._watch_toggle_control(chk_defer, self.on_checkbox_changed)
                yield chk_defer

                proxy_val = (
                    getattr(self.settings, "PROXY", "") or ""
                    if self.settings is not None
                    else ""
                )
                yield Label("Network Proxy (optional):", classes="preset-label")
                inp_proxy = Input(
                    value=str(proxy_val),
                    placeholder="Optional HTTP/HTTPS proxy URL (e.g. http://proxy.example.com:8080)",
                    id="input-wizard-proxy",
                )
                inp_proxy.tooltip = "Optional HTTP/HTTPS proxy URL used when downloading local AI model weights"
                yield inp_proxy

                yield Heading("Workspace Directory:", level=2, classes="field-label")
                initial_dir = (
                    self.current_dir
                    if getattr(self, "current_dir", None) is not None
                    else (getattr(getattr(self, "app", None), "base_dir", "") or "")
                )
                inp = Input(
                    value=initial_dir,
                    placeholder="Enter absolute workspace directory path...",
                    id="input-dir",
                )
                inp.tooltip = "Enter target directory path to scan and organize"
                yield inp
                yield Static("", id="lbl-error", classes="error-banner")

                yield Label("Quick Presets:", classes="preset-label")
                with Horizontal(classes="preset-row"):
                    p_demo = Button(
                        "Demo Workspace", id="preset-demo", variant="default"
                    )
                    p_demo.tooltip = "Select sandbox demo workspace quick preset"
                    yield p_demo
                    p_dl = Button("Downloads", id="preset-downloads", variant="default")
                    p_dl.tooltip = "Select user Downloads folder quick preset"
                    yield p_dl
                    p_docs = Button(
                        "Documents", id="preset-documents", variant="default"
                    )
                    p_docs.tooltip = "Select user Documents folder quick preset"
                    yield p_docs

                btn_pg = Button(
                    "Try Interactive Sample Playground",
                    id="btn-open-playground",
                    variant="primary",
                )
                btn_pg.tooltip = (
                    "Preview sample documents and live rule classification matrix"
                )
                yield btn_pg

                chk_sample = Checkbox(
                    "Generate Sample Documents",
                    value=False,
                    id="chk-sample-corpus",
                )
                chk_sample.tooltip = (
                    "Generate sample document corpus in active workspace directory"
                )
                self._watch_toggle_control(chk_sample, self.on_checkbox_changed)
                yield chk_sample

                yield Heading(
                    "Starter Rule Template Packs:", level=2, classes="field-label"
                )
                yield Label(
                    "Select pre-built template packs to populate keyword rules & compliance policies:"
                )
                chk_stage_wizard = Checkbox(
                    "Stage new starter rules disabled for review",
                    value=True,
                    id="chk-wizard-stage-disabled",
                )
                chk_stage_wizard.tooltip = "Stage newly applied starter template rules in disabled state until reviewed in Active Rule Manager"
                self._watch_toggle_control(chk_stage_wizard, self.on_checkbox_changed)
                yield chk_stage_wizard

                from app.core.rule_templates import get_starter_templates

                for pack in get_starter_templates():
                    chk = Checkbox(
                        f"{pack.icon} {pack.title}",
                        value=False,
                        id=f"chk-template-{pack.id}",
                    )
                    chk.tooltip = pack.description
                    self._watch_toggle_control(chk, self.on_checkbox_changed)
                    yield chk

                yield Heading(
                    "Compliance Sensitivity Quarantine (Opt-In):",
                    level=2,
                    classes="field-label",
                )
                yield Label(
                    "Enable automatic quarantine holds only if you want HIGH or CRITICAL sensitivity files staged for review:"
                )
                current_auto_ratings = {
                    str(r).upper()
                    for r in (
                        getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or []
                    )
                    if r
                }
                sw_quarantine_critical = LabeledSwitch(
                    label="Auto-Quarantine CRITICAL Sensitivity",
                    value="CRITICAL" in current_auto_ratings,
                    switch_id="switch-wizard-quarantine-critical",
                    tooltip="Automatically hold CRITICAL sensitivity documents (e.g. clinical/medical records) in compliance quarantine",
                )
                self._watch_toggle_control(
                    sw_quarantine_critical, self.on_switch_changed
                )
                yield sw_quarantine_critical
                sw_quarantine_high = LabeledSwitch(
                    label="Auto-Quarantine HIGH Sensitivity",
                    value="HIGH" in current_auto_ratings,
                    switch_id="switch-wizard-quarantine-high",
                    tooltip="Automatically hold HIGH sensitivity documents (e.g. financial, tax, legal, resume records) in compliance quarantine",
                )
                self._watch_toggle_control(sw_quarantine_high, self.on_switch_changed)
                yield sw_quarantine_high

            with Vertical(classes="button-row"):
                yield Label(
                    self._format_selected_rules_summary(selected_pack_ids=[]),
                    id="lbl-wizard-rule-summary",
                    classes="rule-summary",
                    markup=False,
                )
                btn_finish = Button("Finish & Save", id="btn-finish", variant="primary")
                btn_finish.tooltip = (
                    "Save AI consent setting and complete onboarding wizard"
                )
                yield btn_finish

    def _format_model_status_text(
        self,
        consent_enabled: bool | None = None,
        defer_download: bool | None = None,
    ) -> str:
        """Build truthful live model status description for the wizard."""
        from app.core.downloader import inspect_local_model_bundle

        if consent_enabled is None:
            try:
                consent_enabled = bool(self.query_one("#switch-consent", Switch).value)
            except Exception:
                consent_enabled = bool(
                    getattr(self.settings, "AI_CONSENT_GRANTED", False)
                )

        if defer_download is None:
            try:
                defer_download = bool(
                    self.query_one("#chk-defer-download", Checkbox).value
                )
            except Exception:
                defer_download = False

        bundle = inspect_local_model_bundle()
        onnx_available = bool(bundle.get("onnxruntime_available", False))
        if bundle["is_downloading"]:
            pct = int(round(bundle["progress_percent"]))
            return (
                f"Model Status: Downloading local AI model weights ({pct}%) — "
                "workspace sorts with keyword clustering until verification completes."
            )
        if bundle["verified"]:
            if not onnx_available:
                return (
                    "Model Status: [AI: Fallback] Verified weights on disk, but optional "
                    "'onnxruntime' is absent — install 'smart-autosorter[ml]' for semantic vectors "
                    "(using local keyword/TF-IDF fallback)."
                )
            if consent_enabled:
                return "Model Status: [AI: Active] Verified local AI model weights ready on disk."
            return "Model Status: Verified local AI model weights ready on disk."
        if bundle["disk_bundle_status"] in ("incomplete", "corrupted"):
            reason = bundle["detail"]
            if consent_enabled and not defer_download:
                return (
                    f"Model Status: Unverified/incomplete weights ({reason}) — "
                    "fresh background download will start on Finish."
                )
            return (
                f"Model Status: [AI: Fallback] Unverified/incomplete weights ({reason}) — "
                "using local keyword/TF-IDF fallback."
            )
        if consent_enabled and not defer_download:
            if not onnx_available:
                return (
                    "Model Status: [AI: Fallback] Missing local model weights "
                    "(install 'smart-autosorter[ml]' for ONNX runtime) — background download (~80 MB) "
                    "will start automatically on Finish."
                )
            return (
                "Model Status: Missing local model weights — background download (~80 MB) "
                "will start automatically on Finish."
            )
        if consent_enabled and defer_download:
            return (
                "Model Status: [AI: Fallback] Missing local model weights — download deferred "
                "(using local keyword/TF-IDF fallback)."
            )
        return (
            "Model Status: Missing local model weights — AI disabled "
            "(using local keyword/TF-IDF sorting)."
        )

    def _selected_pack_rule_totals(
        self, selected_pack_ids: list[str] | None = None
    ) -> tuple[int, int, int]:
        """Return (pack_count, keyword_rule_count, policy_count) for selected starter packs."""
        from app.core.rule_templates import get_starter_templates

        ids = (
            set(selected_pack_ids)
            if selected_pack_ids is not None
            else set(self._get_selected_pack_ids())
        )
        kw_keys: set[str] = set()
        pol_count = 0
        matched_packs = 0
        for pack in get_starter_templates():
            if pack.id in ids:
                matched_packs += 1
                kw_keys.update(k.lower() for k in pack.keyword_rules)
                pol_count += len(pack.policies)
        return matched_packs, len(kw_keys), pol_count

    def _format_selected_rules_summary(
        self, selected_pack_ids: list[str] | None = None
    ) -> str:
        """Build concise summary of selected starter rules and target folders pinned above Finish."""
        from app.core.rule_templates import get_starter_templates

        ids = (
            list(selected_pack_ids)
            if selected_pack_ids is not None
            else self._get_selected_pack_ids()
        )
        pack_count, kw_count, pol_count = self._selected_pack_rule_totals(ids)
        pack_word = "pack" if pack_count == 1 else "packs"
        rule_word = "rule" if kw_count == 1 else "rules"
        pol_word = "policy" if pol_count == 1 else "policies"
        base = (
            f"Selected: {kw_count} keyword {rule_word}, "
            f"{pol_count} {pol_word} ({pack_count} {pack_word})"
        )
        if not ids:
            return base

        targets: list[str] = []
        id_set = set(ids)
        for pack in get_starter_templates():
            if pack.id not in id_set:
                continue
            for folder in pack.keyword_rules.values():
                if folder not in targets:
                    targets.append(folder)
            for pol in pack.policies:
                t_path = str(pol.get("target_path", "")).strip()
                if t_path and t_path not in targets:
                    targets.append(t_path)
            for cat_folder in pack.extension_categories:
                if cat_folder not in targets:
                    targets.append(str(cat_folder))
        if not targets:
            return base
        shown = ", ".join(targets[:3])
        if len(targets) > 3:
            shown = f"{shown} +{len(targets) - 3}"
        return f"{base} -> {shown}"

    def _refresh_rule_summary_label(self) -> None:
        """Refresh the pinned starter rule counter label inside the button row."""
        try:
            lbl = self.query_one("#lbl-wizard-rule-summary", Label)
        except NoMatches:
            return
        lbl.update(self._format_selected_rules_summary())

    def _refresh_model_status_label(self) -> None:
        """Refresh the live model status label inside the wizard."""
        try:
            lbl = self.query_one("#lbl-wizard-model-status", Label)
            lbl.update(self._format_model_status_text())
        except Exception:
            pass

    def _show_error(self, message: str) -> None:
        """Display inline error banner, announce message, and focus input."""
        banner = self.query("#lbl-error")
        if banner:
            banner.first(Static).update(message)
        self.announce(message, priority="assertive")
        inp = self.query("#input-dir")
        if inp:
            inp.first(Input).focus()

    @on(Input.Changed, "#input-dir")
    def on_input_changed(self, event: Input.Changed) -> None:
        """Clear error banner when user changes directory path."""
        banner = self.query("#lbl-error")
        if banner:
            banner.first(Static).update("")

    @on(Input.Submitted, "#input-dir")
    def on_input_submitted(self, event: Input.Submitted) -> None:
        """Finish wizard when Enter is pressed inside directory input."""
        self.action_finish()

    def _clear_auto_suggested_packs(self) -> None:
        """Clear starter packs that were auto-suggested by a quick preset without touching manual selections."""
        import contextlib

        if not self._packs_auto_suggested_by_preset:
            return
        self._updating_preset_packs = True
        try:
            for pack_id in list(self._packs_auto_suggested_by_preset):
                with contextlib.suppress(NoMatches):
                    self.query_one(f"#chk-template-{pack_id}", Checkbox).value = False
            self._packs_auto_suggested_by_preset.clear()
        finally:
            self._updating_preset_packs = False
        self._refresh_rule_summary_label()

    @on(Button.Pressed, "#preset-demo")
    def action_preset_demo(self) -> None:
        """Select sandbox demo workspace quick preset and enable sample generation."""
        path = os.path.abspath("sandbox/demo_workspace")
        if not os.path.exists(path):
            try:
                os.makedirs(path, exist_ok=True)
            except Exception as exc:
                self._show_error(f"Failed to create directory '{path}': {exc}")
                return
        self._clear_auto_suggested_packs()
        self._set_directory_input(path, "demo workspace")
        try:
            chk_sample = self.query_one("#chk-sample-corpus", Checkbox)
            if not chk_sample.value:
                self._sample_auto_enabled_by_demo = True
                chk_sample.value = True
        except Exception:
            pass

    @on(Button.Pressed, "#preset-downloads")
    def action_preset_downloads(self) -> None:
        """Select user Downloads folder quick preset and suggest Downloads starter packs."""
        from app.core.rule_templates import get_recommended_starter_pack_ids

        path = os.path.expanduser("~/Downloads")
        if self._sample_auto_enabled_by_demo:
            self._sample_auto_enabled_by_demo = False
            try:
                self.query_one("#chk-sample-corpus", Checkbox).value = False
            except Exception:
                pass
        self._set_directory_input(path, "Downloads")

        current_checked = set(self._get_selected_pack_ids())
        if (
            not current_checked
            or current_checked == self._packs_auto_suggested_by_preset
        ):
            suggested = get_recommended_starter_pack_ids("downloads")
            import contextlib

            self._updating_preset_packs = True
            try:
                for pack_id in suggested:
                    with contextlib.suppress(NoMatches):
                        self.query_one(
                            f"#chk-template-{pack_id}", Checkbox
                        ).value = True
                        self._packs_auto_suggested_by_preset.add(pack_id)
            finally:
                self._updating_preset_packs = False
            self._refresh_rule_summary_label()
            if suggested:
                self.announce(
                    f"Suggested {len(suggested)} Downloads starter packs staged disabled for review."
                )

    @on(Button.Pressed, "#preset-documents")
    def action_preset_documents(self) -> None:
        """Select user Documents folder quick preset."""
        path = os.path.expanduser("~/Documents")
        if self._sample_auto_enabled_by_demo:
            self._sample_auto_enabled_by_demo = False
            try:
                self.query_one("#chk-sample-corpus", Checkbox).value = False
            except Exception:
                pass
        self._clear_auto_suggested_packs()
        self._set_directory_input(path, "Documents")

    def _set_directory_input(self, path: str, preset_name: str) -> None:
        try:
            inp = self.query_one("#input-dir", Input)
            inp.value = path
        except Exception:
            pass
        self.announce(f"Selected {preset_name} preset: {path}")
        from app.ui.modals.edit import DirectorySelectModal

        err = DirectorySelectModal._validate_directory_path(
            path, settings=self.settings
        )
        if err:
            self._show_error(err)
        else:
            try:
                self.query_one("#lbl-error", Static).update("")
            except Exception:
                pass

    def on_mount(self) -> None:
        """Focus switch on mount, refresh model status, and emit screen reader announcement."""
        super().on_mount()
        self._refresh_model_status_label()
        self._refresh_rule_summary_label()
        self.set_interval(0.5, self._refresh_model_status_label)
        try:
            self.query_one("#switch-consent", Switch).focus()
        except Exception:
            pass
        self.announce("Opened model onboarding wizard dialog.")

    @on(events.DescendantFocus)
    def on_descendant_focus(self, event: events.DescendantFocus) -> None:
        """Announce privacy disclosure when focus lands on AI consent switch or privacy card."""
        widget_id = getattr(event.widget, "id", None)
        if widget_id == "switch-consent":
            self.announce(
                f"AI Consent switch focused. {PRIVACY_GUARANTEE_ANNOUNCEMENT}"
            )
        elif widget_id == "privacy-card":
            self.announce(
                f"Privacy disclosure card focused. {PRIVACY_GUARANTEE_ANNOUNCEMENT}"
            )
        elif widget_id == "input-dir":
            self.announce(
                "Workspace directory input focused. Enter path or choose a quick preset."
            )

    @on(Switch.Changed)
    def on_switch_changed(self, event: Switch.Changed) -> None:
        """Announce switch state changes for screen reader accessibility."""
        if self._should_skip_bubbled_toggle_event(event):
            return
        switch_id = (
            getattr(event.switch, "id", None)
            or getattr(event.control, "id", None)
            or ""
        )
        value = bool(event.value)
        if switch_id == "switch-consent":
            state = "enabled" if value else "disabled"
            self._refresh_model_status_label()
            self.announce(f"AI consent {state}.")
            self.announce(f"AI consent {state}. {PRIVACY_GUARANTEE_ANNOUNCEMENT}")
        elif switch_id == "switch-sample-corpus":
            state = "enabled" if value else "disabled"
            self.announce(f"Sample document corpus generation {state}.")
        elif switch_id == "switch-wizard-quarantine-critical":
            state = "enabled" if value else "disabled"
            self.announce(f"Automatic CRITICAL sensitivity quarantine {state}.")
        elif switch_id == "switch-wizard-quarantine-high":
            state = "enabled" if value else "disabled"
            self.announce(f"Automatic HIGH sensitivity quarantine {state}.")

    @on(Checkbox.Changed)
    def on_checkbox_changed(self, event: Checkbox.Changed) -> None:
        """Announce starter template and provisioning checkbox selection state changes."""
        if self._should_skip_bubbled_toggle_event(event):
            return
        chk_id = (
            getattr(event.checkbox, "id", None)
            or getattr(event.control, "id", None)
            or ""
        )
        value = bool(event.value)
        if chk_id == "chk-defer-download":
            self._refresh_model_status_label()
            state = "deferred" if value else "automatic"
            self.announce(f"Model download mode set to {state}.")
            return

        if chk_id == "chk-sample-corpus":
            state = "enabled" if value else "disabled"
            self.announce(f"Sample document corpus generation {state}.")
            return

        if chk_id == "chk-wizard-stage-disabled":
            mode = "disabled for review" if value else "enabled immediately"
            self.announce(f"Starter rule staging mode set to {mode}.")
            return

        prefix = ""
        if chk_id.startswith("chk-template-"):
            prefix = "chk-template-"
        elif chk_id.startswith("chk-gallery-"):
            prefix = "chk-gallery-"
        else:
            return

        pack_id = chk_id[len(prefix) :]
        if not self._updating_preset_packs and not value:
            self._packs_auto_suggested_by_preset.discard(pack_id)
        self._refresh_rule_summary_label()
        from app.core.rule_templates import get_starter_templates

        for pack in get_starter_templates():
            if pack.id == pack_id:
                state = "selected" if value else "deselected"
                self.announce(f"{pack.title} template pack {state}.")
                break

    def _get_selected_pack_ids(self) -> list[str]:
        """Return starter template pack IDs currently checked in the wizard."""
        from app.core.rule_templates import get_starter_templates

        selected: list[str] = []
        for pack in get_starter_templates():
            try:
                if self.query_one(f"#chk-template-{pack.id}", Checkbox).value:
                    selected.append(pack.id)
            except Exception:
                pass
        return selected

    def _sync_from_playground(self, payload: dict) -> None:
        """Synchronize starter pack toggles and committed sandbox directory from SamplePlaygroundModal."""
        from app.core.rule_templates import get_starter_templates

        selected_packs = set(payload.get("selected_packs") or [])
        self._packs_auto_suggested_by_preset.clear()
        for pack in get_starter_templates():
            try:
                chk = self.query_one(f"#chk-template-{pack.id}", Checkbox)
                desired = pack.id in selected_packs
                if chk.value != desired:
                    chk.value = desired
            except Exception:
                pass
        if "stage_disabled" in payload:
            import contextlib

            with contextlib.suppress(NoMatches):
                self.query_one("#chk-wizard-stage-disabled", Checkbox).value = bool(
                    payload["stage_disabled"]
                )
        self._refresh_rule_summary_label()

        if payload.get("committed"):
            committed_dir = str(payload.get("target_dir") or "").strip()
            if committed_dir:
                self.current_dir = committed_dir
                self._playground_committed_dir = committed_dir
                try:
                    self.query_one("#input-dir", Input).value = committed_dir
                except Exception:
                    pass
                try:
                    self.query_one("#chk-sample-corpus", Checkbox).value = False
                    self._sample_auto_enabled_by_demo = False
                except Exception:
                    pass

    @on(Button.Pressed, "#btn-open-playground")
    def action_open_playground(self) -> None:
        """Open interactive sample playground modal screen with bidirectional state sync."""
        from app.ui.modals.sample_playground import SamplePlaygroundModal

        target_dir = ""
        try:
            val = self.query_one("#input-dir", Input).value.strip()
            if val:
                target_dir = os.path.abspath(os.path.expanduser(val))
        except Exception:
            pass
        if not target_dir:
            target_dir = getattr(self.app, "base_dir", "") or os.getcwd()

        self.app.push_screen(
            SamplePlaygroundModal(
                self.settings,
                target_dir=target_dir,
                initial_selected_packs=self._get_selected_pack_ids(),
                on_sync=self._sync_from_playground,
            )
        )

    @on(Button.Pressed, "#btn-finish")
    def action_finish(self) -> None:
        """Finish wizard, validate directory, save consent/proxy, start background provisioning, and scan."""
        raw_dir = ""
        try:
            raw_dir = self.query_one("#input-dir", Input).value.strip()
        except Exception:
            pass

        if raw_dir:
            from app.ui.modals.edit import DirectorySelectModal

            err = DirectorySelectModal._validate_directory_path(
                raw_dir, settings=self.settings
            )
            if err:
                self._show_error(err)
                return
            chosen_dir = os.path.abspath(os.path.expanduser(raw_dir))
        else:
            chosen_dir = os.path.abspath(os.getcwd())

        try:
            consent = self.query_one("#switch-consent", Switch).value
        except Exception:
            consent = False
        self.settings.AI_CONSENT_GRANTED = consent

        proxy_val = ""
        try:
            proxy_val = self.query_one("#input-wizard-proxy", Input).value.strip()
            self.settings.PROXY = proxy_val
        except Exception:
            proxy_val = str(getattr(self.settings, "PROXY", "") or "").strip()

        existing_ratings = [
            str(r).upper()
            for r in (getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or [])
            if r and str(r).upper() not in ("CRITICAL", "HIGH")
        ]
        try:
            q_crit = self.query_one("#switch-wizard-quarantine-critical", Switch).value
        except Exception:
            q_crit = "CRITICAL" in {
                str(r).upper()
                for r in (getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or [])
            }
        try:
            q_high = self.query_one("#switch-wizard-quarantine-high", Switch).value
        except Exception:
            q_high = "HIGH" in {
                str(r).upper()
                for r in (getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or [])
            }

        updated_ratings: list[str] = []
        if q_crit:
            updated_ratings.append("CRITICAL")
        if q_high:
            updated_ratings.append("HIGH")
        for extra_r in existing_ratings:
            if extra_r not in updated_ratings:
                updated_ratings.append(extra_r)
        try:
            self.settings.AUTO_QUARANTINE_RATINGS = updated_ratings
        except Exception:
            pass

        defer_download = False
        try:
            defer_download = bool(self.query_one("#chk-defer-download", Checkbox).value)
        except Exception:
            defer_download = False

        gen_sample = False
        try:
            gen_sample = self.query_one("#chk-sample-corpus", Checkbox).value
        except Exception:
            try:
                gen_sample = self.query_one("#switch-sample-corpus", Switch).value
            except Exception:
                pass

        target_dir = chosen_dir
        if gen_sample:
            from app.core.sample_corpus import generate_sample_corpus

            is_demo_preset = os.path.normpath(chosen_dir).endswith(
                os.path.normpath("sandbox/demo_workspace")
            )
            sample_fn = getattr(self.app, "_sample_dataset_dir", None)
            if is_demo_preset or chosen_dir == self._playground_committed_dir:
                sample_target = chosen_dir
            elif callable(sample_fn):
                sample_target = sample_fn(chosen_dir)
            else:
                if (
                    os.path.basename(os.path.normpath(chosen_dir))
                    == "sortify-sample-dataset"
                ):
                    sample_target = chosen_dir
                else:
                    try:
                        with os.scandir(chosen_dir) as entries:
                            is_empty = not any(entries)
                    except FileNotFoundError:
                        is_empty = True
                    sample_target = (
                        chosen_dir
                        if is_empty
                        else os.path.join(chosen_dir, "sortify-sample-dataset")
                    )

            target_dir = sample_target
            try:
                generate_sample_corpus(target_dir, overwrite=False)
                self.announce(f"Generated sample document corpus in '{target_dir}'.")
            except FileExistsError:
                self.announce(f"Using the existing sample dataset in '{target_dir}'.")
            except Exception as exc:
                logger.error(f"Failed to generate sample corpus: {exc}")

        from app.config import resolve_scoped_settings
        from app.core.rule_templates import apply_starter_templates

        selected_packs = self._get_selected_pack_ids()
        stage_disabled = True
        try:
            stage_disabled = bool(
                self.query_one("#chk-wizard-stage-disabled", Checkbox).value
            )
        except NoMatches:
            stage_disabled = True

        applied_starter_ok = True
        toast_msg = "Saved onboarding settings (0 starter rules added)."
        if selected_packs:
            try:
                scoped_settings = resolve_scoped_settings(
                    self.settings, target_dir, fallback_to_global=True
                )
                prev_kw_count = len(
                    getattr(scoped_settings, "KEYWORD_RULES", {}) or {}
                ) + len(getattr(scoped_settings, "DISABLED_KEYWORD_RULES", {}) or {})
                prev_pol_count = len(getattr(scoped_settings, "POLICIES", []) or [])
                new_keywords, new_policies = apply_starter_templates(
                    scoped_settings,
                    selected_packs,
                    stage_disabled=stage_disabled,
                )
                after_kw_count = len(new_keywords) + len(
                    getattr(scoped_settings, "DISABLED_KEYWORD_RULES", {}) or {}
                )
                added_kw = max(0, after_kw_count - prev_kw_count)
                added_pol = max(0, len(new_policies) - prev_pol_count)
                pack_count, total_kw, total_pol = self._selected_pack_rule_totals(
                    selected_packs
                )
                state_word = "staged" if stage_disabled else "active"
                action_word = "Staged" if stage_disabled else "Applied"
                if added_kw > 0 or added_pol > 0:
                    toast_msg = (
                        f"{action_word} {pack_count} starter pack(s): "
                        f"added {added_kw} keyword rule(s) and {added_pol} policy rule(s)."
                    )
                else:
                    toast_msg = (
                        f"Saved {pack_count} starter pack(s) "
                        f"({total_kw} keyword rule(s) and {total_pol} policy rule(s) {state_word})."
                    )
            except Exception as exc:
                applied_starter_ok = False
                logger.error(f"Failed to apply starter templates: {exc}")
                err_msg = f"Failed to apply starter rule template pack(s): {exc}"
                self.announce(err_msg)
                if hasattr(self.app, "notify"):
                    self.app.notify(err_msg, severity="error")

        if applied_starter_ok:
            self.announce(toast_msg)
            if hasattr(self.app, "notify"):
                self.app.notify(toast_msg)

        if hasattr(self.settings, "_save"):
            try:
                self.settings._save()
            except Exception as e:
                logger.error(f"Error saving consent setting: {e}")

        if consent and not defer_download:
            try:
                from app.core.downloader import (
                    DEFAULT_MODEL_URL,
                    DownloadManager,
                    resolve_default_model_dir,
                    verify_downloaded_model,
                )

                model_dir = resolve_default_model_dir()
                dm = DownloadManager.get_instance()
                if proxy_val:
                    dm.update_proxy(proxy_val)
                if not dm.state.get(
                    "is_downloading", False
                ) and not verify_downloaded_model(model_dir):
                    dm.start_download(DEFAULT_MODEL_URL, model_dir, proxy=proxy_val)
                    self.announce(
                        "Started background AI model download. Using local keyword clustering until verification completes."
                    )
            except Exception as dl_exc:
                logger.warning(
                    f"Background model provisioning could not start during onboarding: {dl_exc}"
                )
                self.announce(
                    f"Model download unavailable ({dl_exc}). Continuing with local keyword clustering."
                )

        if hasattr(self.app, "base_dir"):
            setattr(self.app, "base_dir", target_dir)
        if hasattr(self.app, "source_dirs"):
            setattr(self.app, "source_dirs", [target_dir])

        update_status_fn = getattr(self.app, "update_status", None)
        if callable(update_status_fn):
            try:
                update_status_fn()
            except Exception:
                pass

        update_cta = getattr(self.app, "_update_onboarding_cta_visibility", None)
        if callable(update_cta):
            try:
                update_cta()
            except Exception:
                pass
        try:
            ws_state = self.app.query_one("#onboarding-workspace-state", Static)
            ws_state.update(f"Active Workspace: {target_dir}")
        except Exception:
            pass

        self.announce(
            "Finished model onboarding wizard, saved consent settings, and applied selected starter rule templates."
        )
        try:
            self.set_focus(None)
        except Exception:
            pass
        self.dismiss(None)

        scan_fn = getattr(self.app, "action_scan_directory", None)
        if callable(scan_fn):
            scan_fn()

    def action_cancel(self) -> None:
        """Cancel wizard on Escape key press."""
        if hasattr(self.app, "_wizard_dismissed_this_session"):
            setattr(self.app, "_wizard_dismissed_this_session", True)
        self.announce("Closed model onboarding wizard dialog.")
        self.dismiss(None)

action_cancel()

Cancel wizard on Escape key press.

Source code in app/ui/modals/wizard.py
1129
1130
1131
1132
1133
1134
def action_cancel(self) -> None:
    """Cancel wizard on Escape key press."""
    if hasattr(self.app, "_wizard_dismissed_this_session"):
        setattr(self.app, "_wizard_dismissed_this_session", True)
    self.announce("Closed model onboarding wizard dialog.")
    self.dismiss(None)

action_finish()

Finish wizard, validate directory, save consent/proxy, start background provisioning, and scan.

Source code in app/ui/modals/wizard.py
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
@on(Button.Pressed, "#btn-finish")
def action_finish(self) -> None:
    """Finish wizard, validate directory, save consent/proxy, start background provisioning, and scan."""
    raw_dir = ""
    try:
        raw_dir = self.query_one("#input-dir", Input).value.strip()
    except Exception:
        pass

    if raw_dir:
        from app.ui.modals.edit import DirectorySelectModal

        err = DirectorySelectModal._validate_directory_path(
            raw_dir, settings=self.settings
        )
        if err:
            self._show_error(err)
            return
        chosen_dir = os.path.abspath(os.path.expanduser(raw_dir))
    else:
        chosen_dir = os.path.abspath(os.getcwd())

    try:
        consent = self.query_one("#switch-consent", Switch).value
    except Exception:
        consent = False
    self.settings.AI_CONSENT_GRANTED = consent

    proxy_val = ""
    try:
        proxy_val = self.query_one("#input-wizard-proxy", Input).value.strip()
        self.settings.PROXY = proxy_val
    except Exception:
        proxy_val = str(getattr(self.settings, "PROXY", "") or "").strip()

    existing_ratings = [
        str(r).upper()
        for r in (getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or [])
        if r and str(r).upper() not in ("CRITICAL", "HIGH")
    ]
    try:
        q_crit = self.query_one("#switch-wizard-quarantine-critical", Switch).value
    except Exception:
        q_crit = "CRITICAL" in {
            str(r).upper()
            for r in (getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or [])
        }
    try:
        q_high = self.query_one("#switch-wizard-quarantine-high", Switch).value
    except Exception:
        q_high = "HIGH" in {
            str(r).upper()
            for r in (getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or [])
        }

    updated_ratings: list[str] = []
    if q_crit:
        updated_ratings.append("CRITICAL")
    if q_high:
        updated_ratings.append("HIGH")
    for extra_r in existing_ratings:
        if extra_r not in updated_ratings:
            updated_ratings.append(extra_r)
    try:
        self.settings.AUTO_QUARANTINE_RATINGS = updated_ratings
    except Exception:
        pass

    defer_download = False
    try:
        defer_download = bool(self.query_one("#chk-defer-download", Checkbox).value)
    except Exception:
        defer_download = False

    gen_sample = False
    try:
        gen_sample = self.query_one("#chk-sample-corpus", Checkbox).value
    except Exception:
        try:
            gen_sample = self.query_one("#switch-sample-corpus", Switch).value
        except Exception:
            pass

    target_dir = chosen_dir
    if gen_sample:
        from app.core.sample_corpus import generate_sample_corpus

        is_demo_preset = os.path.normpath(chosen_dir).endswith(
            os.path.normpath("sandbox/demo_workspace")
        )
        sample_fn = getattr(self.app, "_sample_dataset_dir", None)
        if is_demo_preset or chosen_dir == self._playground_committed_dir:
            sample_target = chosen_dir
        elif callable(sample_fn):
            sample_target = sample_fn(chosen_dir)
        else:
            if (
                os.path.basename(os.path.normpath(chosen_dir))
                == "sortify-sample-dataset"
            ):
                sample_target = chosen_dir
            else:
                try:
                    with os.scandir(chosen_dir) as entries:
                        is_empty = not any(entries)
                except FileNotFoundError:
                    is_empty = True
                sample_target = (
                    chosen_dir
                    if is_empty
                    else os.path.join(chosen_dir, "sortify-sample-dataset")
                )

        target_dir = sample_target
        try:
            generate_sample_corpus(target_dir, overwrite=False)
            self.announce(f"Generated sample document corpus in '{target_dir}'.")
        except FileExistsError:
            self.announce(f"Using the existing sample dataset in '{target_dir}'.")
        except Exception as exc:
            logger.error(f"Failed to generate sample corpus: {exc}")

    from app.config import resolve_scoped_settings
    from app.core.rule_templates import apply_starter_templates

    selected_packs = self._get_selected_pack_ids()
    stage_disabled = True
    try:
        stage_disabled = bool(
            self.query_one("#chk-wizard-stage-disabled", Checkbox).value
        )
    except NoMatches:
        stage_disabled = True

    applied_starter_ok = True
    toast_msg = "Saved onboarding settings (0 starter rules added)."
    if selected_packs:
        try:
            scoped_settings = resolve_scoped_settings(
                self.settings, target_dir, fallback_to_global=True
            )
            prev_kw_count = len(
                getattr(scoped_settings, "KEYWORD_RULES", {}) or {}
            ) + len(getattr(scoped_settings, "DISABLED_KEYWORD_RULES", {}) or {})
            prev_pol_count = len(getattr(scoped_settings, "POLICIES", []) or [])
            new_keywords, new_policies = apply_starter_templates(
                scoped_settings,
                selected_packs,
                stage_disabled=stage_disabled,
            )
            after_kw_count = len(new_keywords) + len(
                getattr(scoped_settings, "DISABLED_KEYWORD_RULES", {}) or {}
            )
            added_kw = max(0, after_kw_count - prev_kw_count)
            added_pol = max(0, len(new_policies) - prev_pol_count)
            pack_count, total_kw, total_pol = self._selected_pack_rule_totals(
                selected_packs
            )
            state_word = "staged" if stage_disabled else "active"
            action_word = "Staged" if stage_disabled else "Applied"
            if added_kw > 0 or added_pol > 0:
                toast_msg = (
                    f"{action_word} {pack_count} starter pack(s): "
                    f"added {added_kw} keyword rule(s) and {added_pol} policy rule(s)."
                )
            else:
                toast_msg = (
                    f"Saved {pack_count} starter pack(s) "
                    f"({total_kw} keyword rule(s) and {total_pol} policy rule(s) {state_word})."
                )
        except Exception as exc:
            applied_starter_ok = False
            logger.error(f"Failed to apply starter templates: {exc}")
            err_msg = f"Failed to apply starter rule template pack(s): {exc}"
            self.announce(err_msg)
            if hasattr(self.app, "notify"):
                self.app.notify(err_msg, severity="error")

    if applied_starter_ok:
        self.announce(toast_msg)
        if hasattr(self.app, "notify"):
            self.app.notify(toast_msg)

    if hasattr(self.settings, "_save"):
        try:
            self.settings._save()
        except Exception as e:
            logger.error(f"Error saving consent setting: {e}")

    if consent and not defer_download:
        try:
            from app.core.downloader import (
                DEFAULT_MODEL_URL,
                DownloadManager,
                resolve_default_model_dir,
                verify_downloaded_model,
            )

            model_dir = resolve_default_model_dir()
            dm = DownloadManager.get_instance()
            if proxy_val:
                dm.update_proxy(proxy_val)
            if not dm.state.get(
                "is_downloading", False
            ) and not verify_downloaded_model(model_dir):
                dm.start_download(DEFAULT_MODEL_URL, model_dir, proxy=proxy_val)
                self.announce(
                    "Started background AI model download. Using local keyword clustering until verification completes."
                )
        except Exception as dl_exc:
            logger.warning(
                f"Background model provisioning could not start during onboarding: {dl_exc}"
            )
            self.announce(
                f"Model download unavailable ({dl_exc}). Continuing with local keyword clustering."
            )

    if hasattr(self.app, "base_dir"):
        setattr(self.app, "base_dir", target_dir)
    if hasattr(self.app, "source_dirs"):
        setattr(self.app, "source_dirs", [target_dir])

    update_status_fn = getattr(self.app, "update_status", None)
    if callable(update_status_fn):
        try:
            update_status_fn()
        except Exception:
            pass

    update_cta = getattr(self.app, "_update_onboarding_cta_visibility", None)
    if callable(update_cta):
        try:
            update_cta()
        except Exception:
            pass
    try:
        ws_state = self.app.query_one("#onboarding-workspace-state", Static)
        ws_state.update(f"Active Workspace: {target_dir}")
    except Exception:
        pass

    self.announce(
        "Finished model onboarding wizard, saved consent settings, and applied selected starter rule templates."
    )
    try:
        self.set_focus(None)
    except Exception:
        pass
    self.dismiss(None)

    scan_fn = getattr(self.app, "action_scan_directory", None)
    if callable(scan_fn):
        scan_fn()

action_open_playground()

Open interactive sample playground modal screen with bidirectional state sync.

Source code in app/ui/modals/wizard.py
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
@on(Button.Pressed, "#btn-open-playground")
def action_open_playground(self) -> None:
    """Open interactive sample playground modal screen with bidirectional state sync."""
    from app.ui.modals.sample_playground import SamplePlaygroundModal

    target_dir = ""
    try:
        val = self.query_one("#input-dir", Input).value.strip()
        if val:
            target_dir = os.path.abspath(os.path.expanduser(val))
    except Exception:
        pass
    if not target_dir:
        target_dir = getattr(self.app, "base_dir", "") or os.getcwd()

    self.app.push_screen(
        SamplePlaygroundModal(
            self.settings,
            target_dir=target_dir,
            initial_selected_packs=self._get_selected_pack_ids(),
            on_sync=self._sync_from_playground,
        )
    )

action_preset_demo()

Select sandbox demo workspace quick preset and enable sample generation.

Source code in app/ui/modals/wizard.py
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
@on(Button.Pressed, "#preset-demo")
def action_preset_demo(self) -> None:
    """Select sandbox demo workspace quick preset and enable sample generation."""
    path = os.path.abspath("sandbox/demo_workspace")
    if not os.path.exists(path):
        try:
            os.makedirs(path, exist_ok=True)
        except Exception as exc:
            self._show_error(f"Failed to create directory '{path}': {exc}")
            return
    self._clear_auto_suggested_packs()
    self._set_directory_input(path, "demo workspace")
    try:
        chk_sample = self.query_one("#chk-sample-corpus", Checkbox)
        if not chk_sample.value:
            self._sample_auto_enabled_by_demo = True
            chk_sample.value = True
    except Exception:
        pass

action_preset_documents()

Select user Documents folder quick preset.

Source code in app/ui/modals/wizard.py
665
666
667
668
669
670
671
672
673
674
675
676
@on(Button.Pressed, "#preset-documents")
def action_preset_documents(self) -> None:
    """Select user Documents folder quick preset."""
    path = os.path.expanduser("~/Documents")
    if self._sample_auto_enabled_by_demo:
        self._sample_auto_enabled_by_demo = False
        try:
            self.query_one("#chk-sample-corpus", Checkbox).value = False
        except Exception:
            pass
    self._clear_auto_suggested_packs()
    self._set_directory_input(path, "Documents")

action_preset_downloads()

Select user Downloads folder quick preset and suggest Downloads starter packs.

Source code in app/ui/modals/wizard.py
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
@on(Button.Pressed, "#preset-downloads")
def action_preset_downloads(self) -> None:
    """Select user Downloads folder quick preset and suggest Downloads starter packs."""
    from app.core.rule_templates import get_recommended_starter_pack_ids

    path = os.path.expanduser("~/Downloads")
    if self._sample_auto_enabled_by_demo:
        self._sample_auto_enabled_by_demo = False
        try:
            self.query_one("#chk-sample-corpus", Checkbox).value = False
        except Exception:
            pass
    self._set_directory_input(path, "Downloads")

    current_checked = set(self._get_selected_pack_ids())
    if (
        not current_checked
        or current_checked == self._packs_auto_suggested_by_preset
    ):
        suggested = get_recommended_starter_pack_ids("downloads")
        import contextlib

        self._updating_preset_packs = True
        try:
            for pack_id in suggested:
                with contextlib.suppress(NoMatches):
                    self.query_one(
                        f"#chk-template-{pack_id}", Checkbox
                    ).value = True
                    self._packs_auto_suggested_by_preset.add(pack_id)
        finally:
            self._updating_preset_packs = False
        self._refresh_rule_summary_label()
        if suggested:
            self.announce(
                f"Suggested {len(suggested)} Downloads starter packs staged disabled for review."
            )

compose()

Compose modal dialog children.

Source code in app/ui/modals/wizard.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
def compose(self) -> ComposeResult:
    """Compose modal dialog children."""
    with ModalBox(classes="modal-frame"):
        with Vertical(classes="modal-body modal-box"):
            yield Heading(
                "Model Onboarding Wizard [Ctrl+W]",
                level=1,
                classes="modal-title",
                id="modal-title",
            )
            yield Label("Welcome to Smart AutoSorter AI Pro TUI.")
            yield Label("Enable AI semantic categorization consent below:")

            priv_card = Vertical(id="privacy-card", classes="privacy-card")
            priv_card.can_focus = True
            priv_card.tooltip = (
                "Local-first privacy guarantees: 100% local model execution, "
                "zero document cloud telemetry, and encrypted local SQLCipher storage"
            )
            with priv_card:
                yield Label(
                    "[100% On-Device & Offline]",
                    classes="privacy-badge",
                    id="privacy-badge",
                )
                yield Label(
                    "Local-First Privacy Guarantees:",
                    classes="privacy-title",
                    id="privacy-card-title",
                )
                yield Label(
                    "• 100% local model execution: ML classification and clustering run entirely on-device.",
                    classes="privacy-guarantee",
                    id="privacy-guarantee-local",
                )
                yield Label(
                    "• Zero document cloud telemetry: Document contents and names are never sent to external servers.",
                    classes="privacy-guarantee",
                    id="privacy-guarantee-telemetry",
                )
                yield Label(
                    "• Encrypted local SQLCipher storage: Databases, extracted text, and vectors are encrypted at rest.",
                    classes="privacy-guarantee",
                    id="privacy-guarantee-storage",
                )

            consent_val = getattr(self.settings, "AI_CONSENT_GRANTED", None)
            if consent_val is None:
                consent_val = False
            sw_consent = LabeledSwitch(
                label="AI Consent Granted",
                value=bool(consent_val),
                switch_id="switch-consent",
                tooltip=(
                    "Toggle AI consent for semantic document classification "
                    "([100% On-Device & Offline]: 100% local model execution, "
                    "zero document cloud telemetry, and encrypted local SQLCipher storage)"
                ),
            )
            self._watch_toggle_control(sw_consent, self.on_switch_changed)
            yield sw_consent

            yield Label(
                self._format_model_status_text(
                    consent_enabled=bool(consent_val),
                    defer_download=False,
                ),
                id="lbl-wizard-model-status",
                markup=False,
            )

            chk_defer = Checkbox(
                "Defer model download (metered or offline network)",
                value=False,
                id="chk-defer-download",
            )
            chk_defer.tooltip = "Skip automatic background model download and sort immediately with local keyword/TF-IDF rules"
            self._watch_toggle_control(chk_defer, self.on_checkbox_changed)
            yield chk_defer

            proxy_val = (
                getattr(self.settings, "PROXY", "") or ""
                if self.settings is not None
                else ""
            )
            yield Label("Network Proxy (optional):", classes="preset-label")
            inp_proxy = Input(
                value=str(proxy_val),
                placeholder="Optional HTTP/HTTPS proxy URL (e.g. http://proxy.example.com:8080)",
                id="input-wizard-proxy",
            )
            inp_proxy.tooltip = "Optional HTTP/HTTPS proxy URL used when downloading local AI model weights"
            yield inp_proxy

            yield Heading("Workspace Directory:", level=2, classes="field-label")
            initial_dir = (
                self.current_dir
                if getattr(self, "current_dir", None) is not None
                else (getattr(getattr(self, "app", None), "base_dir", "") or "")
            )
            inp = Input(
                value=initial_dir,
                placeholder="Enter absolute workspace directory path...",
                id="input-dir",
            )
            inp.tooltip = "Enter target directory path to scan and organize"
            yield inp
            yield Static("", id="lbl-error", classes="error-banner")

            yield Label("Quick Presets:", classes="preset-label")
            with Horizontal(classes="preset-row"):
                p_demo = Button(
                    "Demo Workspace", id="preset-demo", variant="default"
                )
                p_demo.tooltip = "Select sandbox demo workspace quick preset"
                yield p_demo
                p_dl = Button("Downloads", id="preset-downloads", variant="default")
                p_dl.tooltip = "Select user Downloads folder quick preset"
                yield p_dl
                p_docs = Button(
                    "Documents", id="preset-documents", variant="default"
                )
                p_docs.tooltip = "Select user Documents folder quick preset"
                yield p_docs

            btn_pg = Button(
                "Try Interactive Sample Playground",
                id="btn-open-playground",
                variant="primary",
            )
            btn_pg.tooltip = (
                "Preview sample documents and live rule classification matrix"
            )
            yield btn_pg

            chk_sample = Checkbox(
                "Generate Sample Documents",
                value=False,
                id="chk-sample-corpus",
            )
            chk_sample.tooltip = (
                "Generate sample document corpus in active workspace directory"
            )
            self._watch_toggle_control(chk_sample, self.on_checkbox_changed)
            yield chk_sample

            yield Heading(
                "Starter Rule Template Packs:", level=2, classes="field-label"
            )
            yield Label(
                "Select pre-built template packs to populate keyword rules & compliance policies:"
            )
            chk_stage_wizard = Checkbox(
                "Stage new starter rules disabled for review",
                value=True,
                id="chk-wizard-stage-disabled",
            )
            chk_stage_wizard.tooltip = "Stage newly applied starter template rules in disabled state until reviewed in Active Rule Manager"
            self._watch_toggle_control(chk_stage_wizard, self.on_checkbox_changed)
            yield chk_stage_wizard

            from app.core.rule_templates import get_starter_templates

            for pack in get_starter_templates():
                chk = Checkbox(
                    f"{pack.icon} {pack.title}",
                    value=False,
                    id=f"chk-template-{pack.id}",
                )
                chk.tooltip = pack.description
                self._watch_toggle_control(chk, self.on_checkbox_changed)
                yield chk

            yield Heading(
                "Compliance Sensitivity Quarantine (Opt-In):",
                level=2,
                classes="field-label",
            )
            yield Label(
                "Enable automatic quarantine holds only if you want HIGH or CRITICAL sensitivity files staged for review:"
            )
            current_auto_ratings = {
                str(r).upper()
                for r in (
                    getattr(self.settings, "AUTO_QUARANTINE_RATINGS", []) or []
                )
                if r
            }
            sw_quarantine_critical = LabeledSwitch(
                label="Auto-Quarantine CRITICAL Sensitivity",
                value="CRITICAL" in current_auto_ratings,
                switch_id="switch-wizard-quarantine-critical",
                tooltip="Automatically hold CRITICAL sensitivity documents (e.g. clinical/medical records) in compliance quarantine",
            )
            self._watch_toggle_control(
                sw_quarantine_critical, self.on_switch_changed
            )
            yield sw_quarantine_critical
            sw_quarantine_high = LabeledSwitch(
                label="Auto-Quarantine HIGH Sensitivity",
                value="HIGH" in current_auto_ratings,
                switch_id="switch-wizard-quarantine-high",
                tooltip="Automatically hold HIGH sensitivity documents (e.g. financial, tax, legal, resume records) in compliance quarantine",
            )
            self._watch_toggle_control(sw_quarantine_high, self.on_switch_changed)
            yield sw_quarantine_high

        with Vertical(classes="button-row"):
            yield Label(
                self._format_selected_rules_summary(selected_pack_ids=[]),
                id="lbl-wizard-rule-summary",
                classes="rule-summary",
                markup=False,
            )
            btn_finish = Button("Finish & Save", id="btn-finish", variant="primary")
            btn_finish.tooltip = (
                "Save AI consent setting and complete onboarding wizard"
            )
            yield btn_finish

on_checkbox_changed(event)

Announce starter template and provisioning checkbox selection state changes.

Source code in app/ui/modals/wizard.py
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
@on(Checkbox.Changed)
def on_checkbox_changed(self, event: Checkbox.Changed) -> None:
    """Announce starter template and provisioning checkbox selection state changes."""
    if self._should_skip_bubbled_toggle_event(event):
        return
    chk_id = (
        getattr(event.checkbox, "id", None)
        or getattr(event.control, "id", None)
        or ""
    )
    value = bool(event.value)
    if chk_id == "chk-defer-download":
        self._refresh_model_status_label()
        state = "deferred" if value else "automatic"
        self.announce(f"Model download mode set to {state}.")
        return

    if chk_id == "chk-sample-corpus":
        state = "enabled" if value else "disabled"
        self.announce(f"Sample document corpus generation {state}.")
        return

    if chk_id == "chk-wizard-stage-disabled":
        mode = "disabled for review" if value else "enabled immediately"
        self.announce(f"Starter rule staging mode set to {mode}.")
        return

    prefix = ""
    if chk_id.startswith("chk-template-"):
        prefix = "chk-template-"
    elif chk_id.startswith("chk-gallery-"):
        prefix = "chk-gallery-"
    else:
        return

    pack_id = chk_id[len(prefix) :]
    if not self._updating_preset_packs and not value:
        self._packs_auto_suggested_by_preset.discard(pack_id)
    self._refresh_rule_summary_label()
    from app.core.rule_templates import get_starter_templates

    for pack in get_starter_templates():
        if pack.id == pack_id:
            state = "selected" if value else "deselected"
            self.announce(f"{pack.title} template pack {state}.")
            break

on_descendant_focus(event)

Announce privacy disclosure when focus lands on AI consent switch or privacy card.

Source code in app/ui/modals/wizard.py
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
@on(events.DescendantFocus)
def on_descendant_focus(self, event: events.DescendantFocus) -> None:
    """Announce privacy disclosure when focus lands on AI consent switch or privacy card."""
    widget_id = getattr(event.widget, "id", None)
    if widget_id == "switch-consent":
        self.announce(
            f"AI Consent switch focused. {PRIVACY_GUARANTEE_ANNOUNCEMENT}"
        )
    elif widget_id == "privacy-card":
        self.announce(
            f"Privacy disclosure card focused. {PRIVACY_GUARANTEE_ANNOUNCEMENT}"
        )
    elif widget_id == "input-dir":
        self.announce(
            "Workspace directory input focused. Enter path or choose a quick preset."
        )

on_input_changed(event)

Clear error banner when user changes directory path.

Source code in app/ui/modals/wizard.py
579
580
581
582
583
584
@on(Input.Changed, "#input-dir")
def on_input_changed(self, event: Input.Changed) -> None:
    """Clear error banner when user changes directory path."""
    banner = self.query("#lbl-error")
    if banner:
        banner.first(Static).update("")

on_input_submitted(event)

Finish wizard when Enter is pressed inside directory input.

Source code in app/ui/modals/wizard.py
586
587
588
589
@on(Input.Submitted, "#input-dir")
def on_input_submitted(self, event: Input.Submitted) -> None:
    """Finish wizard when Enter is pressed inside directory input."""
    self.action_finish()

on_mount()

Focus switch on mount, refresh model status, and emit screen reader announcement.

Source code in app/ui/modals/wizard.py
698
699
700
701
702
703
704
705
706
707
708
def on_mount(self) -> None:
    """Focus switch on mount, refresh model status, and emit screen reader announcement."""
    super().on_mount()
    self._refresh_model_status_label()
    self._refresh_rule_summary_label()
    self.set_interval(0.5, self._refresh_model_status_label)
    try:
        self.query_one("#switch-consent", Switch).focus()
    except Exception:
        pass
    self.announce("Opened model onboarding wizard dialog.")

on_switch_changed(event)

Announce switch state changes for screen reader accessibility.

Source code in app/ui/modals/wizard.py
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
@on(Switch.Changed)
def on_switch_changed(self, event: Switch.Changed) -> None:
    """Announce switch state changes for screen reader accessibility."""
    if self._should_skip_bubbled_toggle_event(event):
        return
    switch_id = (
        getattr(event.switch, "id", None)
        or getattr(event.control, "id", None)
        or ""
    )
    value = bool(event.value)
    if switch_id == "switch-consent":
        state = "enabled" if value else "disabled"
        self._refresh_model_status_label()
        self.announce(f"AI consent {state}.")
        self.announce(f"AI consent {state}. {PRIVACY_GUARANTEE_ANNOUNCEMENT}")
    elif switch_id == "switch-sample-corpus":
        state = "enabled" if value else "disabled"
        self.announce(f"Sample document corpus generation {state}.")
    elif switch_id == "switch-wizard-quarantine-critical":
        state = "enabled" if value else "disabled"
        self.announce(f"Automatic CRITICAL sensitivity quarantine {state}.")
    elif switch_id == "switch-wizard-quarantine-high":
        state = "enabled" if value else "disabled"
        self.announce(f"Automatic HIGH sensitivity quarantine {state}.")

app.ui.notifications

app.ui.notifications

Unified context-aware notification bus for Textual TUI and CLI runtime environments.

NotificationManager

Central dispatcher for environment-aware notifications.

Source code in app/ui/notifications.py
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
class NotificationManager:
    """Central dispatcher for environment-aware notifications."""

    _instance: "NotificationManager | None" = None
    _lock = threading.RLock()

    def __init__(self):
        self._mode: NotificationMode = NotificationMode.AUTO
        self._active_tui_app: Any | None = None
        self._output_stream = sys.stderr
        self._custom_handlers: list[Callable[..., Any]] = []

    @classmethod
    def get_instance(cls) -> "NotificationManager":
        """Retrieve the singleton NotificationManager instance."""
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = cls()
        return cls._instance

    @classmethod
    def reset_instance(cls):
        """Reset singleton instance (useful for unit tests)."""
        with cls._lock:
            cls._instance = None

    def set_mode(self, mode: NotificationMode | str) -> None:
        """Set active notification mode explicitly."""
        if isinstance(mode, str):
            mode = NotificationMode(mode.lower())
        self._mode = mode

    def get_mode(self) -> NotificationMode:
        """Get currently configured notification mode."""
        return self._mode

    def register_tui(self, app: Any) -> None:
        """Register active Textual TUI app instance."""
        self._active_tui_app = app

    def unregister_tui(self, app: Any = None) -> None:
        """Unregister active Textual TUI app instance."""
        if app is None or self._active_tui_app is app:
            self._active_tui_app = None

    def set_output_stream(self, stream: Any) -> None:
        """Set output stream for CLI/terminal notifications (defaults to sys.stderr)."""
        self._output_stream = stream

    def register_handler(self, handler: Callable[..., Any]) -> None:
        """Register a custom notification handler callback."""
        if handler not in self._custom_handlers:
            self._custom_handlers.append(handler)

    def detect_mode(self) -> NotificationMode:
        """Detect current active runtime environment mode."""
        if self._mode != NotificationMode.AUTO:
            return self._mode

        tui_app = self._get_active_tui_app()
        if tui_app is not None:
            return NotificationMode.TUI

        return NotificationMode.CLI

    def _get_active_tui_app(self) -> Any | None:
        if self._active_tui_app is not None:
            return self._active_tui_app
        try:
            from textual._context import active_app

            app = active_app.get(None)
            if app is not None:
                return app
        except ImportError:
            logger.debug("Textual active_app context unavailable", exc_info=True)
        return None

    def notify(
        self,
        message: Any,
        type: str = "info",
        caption: str | None = None,
        timeout: int | None = None,
        help_url: str | None = None,
        **kwargs: Any,
    ) -> dict[str, Any]:
        """Dispatch a notification based on the active runtime environment mode.

        Args:
            message: Message text or object to display.
            type: Notification type ('info', 'positive', 'negative', 'warning', 'error').
            caption: Optional subtitle or secondary text.
            timeout: Display timeout in milliseconds or seconds.
            help_url: Optional troubleshooting link for contextual help.
            **kwargs: Additional parameters passed to target UI handler.

        Returns
        -------
            Dict containing event summary details.
        """
        msg_str = _sanitize_notification_text(message) or ""
        caption_str = _sanitize_notification_text(caption)
        mode = self.detect_mode()

        event = {
            "message": msg_str,
            "type": type,
            "caption": caption_str,
            "timeout": timeout,
            "help_url": help_url,
            "mode": mode.value,
            "kwargs": kwargs,
        }

        # Dispatch to custom handlers first
        for handler in list(self._custom_handlers):
            try:
                handler(event)
            except Exception as e:
                logger.debug(
                    f"Error in custom notification handler: {e}", exc_info=True
                )

        if mode == NotificationMode.TUI:
            self._dispatch_tui(
                msg_str,
                type=type,
                caption=caption_str,
                timeout=timeout,
                help_url=help_url,
                **kwargs,
            )
        else:
            self._dispatch_cli(
                msg_str, type=type, caption=caption_str, help_url=help_url, **kwargs
            )

        return event

    def _dispatch_tui(
        self,
        message: str,
        type: str = "info",
        caption: str | None = None,
        timeout: int | None = None,
        help_url: str | None = None,
        **kwargs: Any,
    ) -> None:
        tui_app = self._get_active_tui_app()
        if tui_app is None:
            self._dispatch_cli(
                message, type=type, caption=caption, help_url=help_url, **kwargs
            )
            return

        type_lower = (type or "info").lower()
        if type_lower in ("positive", "success"):
            severity = "information"
        elif type_lower in ("negative", "error"):
            severity = "error"
        elif type_lower in ("warning", "warn"):
            severity = "warning"
        else:
            severity = "information"

        title = caption or "Notification"
        toast_timeout = (
            float(timeout / 1000.0) if timeout and timeout > 100 else (timeout or 5)
        )

        display_msg = (
            f"{message} [Help: {help_url}]"
            if help_url and help_url not in message
            else message
        )

        def _do_notify():
            toast_ok = False
            try:
                tui_app.notify(
                    display_msg,
                    title=title,
                    severity=severity,
                    timeout=toast_timeout,
                )
                toast_ok = True
            except Exception as ex:
                logger.debug(f"Textual toast notification failed: {ex}", exc_info=True)

            log_ok = False
            try:
                from textual.widgets import Log

                log_widget = tui_app.query_one("#tui-log", Log)
                log_widget.write_line(f"[{type.upper()}] {display_msg}")
                log_ok = True
            except Exception:
                logger.debug("TUI log widget dispatch failed", exc_info=True)

            if not toast_ok and not log_ok:
                raise RuntimeError("Both TUI toast and log widget dispatch failed")

        try:
            if threading.current_thread() is getattr(
                tui_app, "_thread", None
            ) or getattr(tui_app, "is_headless", False):
                _do_notify()
            elif hasattr(tui_app, "call_from_thread"):
                tui_app.call_from_thread(_do_notify)
            else:
                _do_notify()
        except Exception as ex:
            logger.debug(f"TUI dispatch failed: {ex}", exc_info=True)
            self._dispatch_cli(
                message, type=type, caption=caption, help_url=help_url, **kwargs
            )

    def _dispatch_cli(
        self,
        message: str,
        type: str = "info",
        caption: str | None = None,
        help_url: str | None = None,
        **kwargs: Any,
    ) -> None:
        clean_msg = sanitize_secret_patterns(scrub_user_home_paths(message))
        full_msg = f"{caption}: {clean_msg}" if caption else clean_msg
        if help_url and help_url not in full_msg:
            full_msg = f"{full_msg} [Help: {help_url}]"

        tag = (type or "info").upper()
        formatted = f"[NOTIFICATION] [{tag}] {full_msg}\n"

        if tag in ("NEGATIVE", "ERROR"):
            logger.error(full_msg)
        elif tag in ("WARNING", "WARN"):
            logger.warning(full_msg)
        else:
            logger.info(full_msg)

        try:
            if self._output_stream and hasattr(self._output_stream, "write"):
                self._output_stream.write(formatted)
                if hasattr(self._output_stream, "flush"):
                    self._output_stream.flush()
        except Exception as e:
            logger.debug(f"Failed writing notification to stream: {e}", exc_info=True)

detect_mode()

Detect current active runtime environment mode.

Source code in app/ui/notifications.py
103
104
105
106
107
108
109
110
111
112
def detect_mode(self) -> NotificationMode:
    """Detect current active runtime environment mode."""
    if self._mode != NotificationMode.AUTO:
        return self._mode

    tui_app = self._get_active_tui_app()
    if tui_app is not None:
        return NotificationMode.TUI

    return NotificationMode.CLI

get_instance() classmethod

Retrieve the singleton NotificationManager instance.

Source code in app/ui/notifications.py
60
61
62
63
64
65
66
67
@classmethod
def get_instance(cls) -> "NotificationManager":
    """Retrieve the singleton NotificationManager instance."""
    if cls._instance is None:
        with cls._lock:
            if cls._instance is None:
                cls._instance = cls()
    return cls._instance

get_mode()

Get currently configured notification mode.

Source code in app/ui/notifications.py
81
82
83
def get_mode(self) -> NotificationMode:
    """Get currently configured notification mode."""
    return self._mode

notify(message, type='info', caption=None, timeout=None, help_url=None, **kwargs)

Dispatch a notification based on the active runtime environment mode.

Args: message: Message text or object to display. type: Notification type ('info', 'positive', 'negative', 'warning', 'error'). caption: Optional subtitle or secondary text. timeout: Display timeout in milliseconds or seconds. help_url: Optional troubleshooting link for contextual help. **kwargs: Additional parameters passed to target UI handler.

Returns:

Type Description
Dict containing event summary details.
Source code in app/ui/notifications.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def notify(
    self,
    message: Any,
    type: str = "info",
    caption: str | None = None,
    timeout: int | None = None,
    help_url: str | None = None,
    **kwargs: Any,
) -> dict[str, Any]:
    """Dispatch a notification based on the active runtime environment mode.

    Args:
        message: Message text or object to display.
        type: Notification type ('info', 'positive', 'negative', 'warning', 'error').
        caption: Optional subtitle or secondary text.
        timeout: Display timeout in milliseconds or seconds.
        help_url: Optional troubleshooting link for contextual help.
        **kwargs: Additional parameters passed to target UI handler.

    Returns
    -------
        Dict containing event summary details.
    """
    msg_str = _sanitize_notification_text(message) or ""
    caption_str = _sanitize_notification_text(caption)
    mode = self.detect_mode()

    event = {
        "message": msg_str,
        "type": type,
        "caption": caption_str,
        "timeout": timeout,
        "help_url": help_url,
        "mode": mode.value,
        "kwargs": kwargs,
    }

    # Dispatch to custom handlers first
    for handler in list(self._custom_handlers):
        try:
            handler(event)
        except Exception as e:
            logger.debug(
                f"Error in custom notification handler: {e}", exc_info=True
            )

    if mode == NotificationMode.TUI:
        self._dispatch_tui(
            msg_str,
            type=type,
            caption=caption_str,
            timeout=timeout,
            help_url=help_url,
            **kwargs,
        )
    else:
        self._dispatch_cli(
            msg_str, type=type, caption=caption_str, help_url=help_url, **kwargs
        )

    return event

register_handler(handler)

Register a custom notification handler callback.

Source code in app/ui/notifications.py
 98
 99
100
101
def register_handler(self, handler: Callable[..., Any]) -> None:
    """Register a custom notification handler callback."""
    if handler not in self._custom_handlers:
        self._custom_handlers.append(handler)

register_tui(app)

Register active Textual TUI app instance.

Source code in app/ui/notifications.py
85
86
87
def register_tui(self, app: Any) -> None:
    """Register active Textual TUI app instance."""
    self._active_tui_app = app

reset_instance() classmethod

Reset singleton instance (useful for unit tests).

Source code in app/ui/notifications.py
69
70
71
72
73
@classmethod
def reset_instance(cls):
    """Reset singleton instance (useful for unit tests)."""
    with cls._lock:
        cls._instance = None

set_mode(mode)

Set active notification mode explicitly.

Source code in app/ui/notifications.py
75
76
77
78
79
def set_mode(self, mode: NotificationMode | str) -> None:
    """Set active notification mode explicitly."""
    if isinstance(mode, str):
        mode = NotificationMode(mode.lower())
    self._mode = mode

set_output_stream(stream)

Set output stream for CLI/terminal notifications (defaults to sys.stderr).

Source code in app/ui/notifications.py
94
95
96
def set_output_stream(self, stream: Any) -> None:
    """Set output stream for CLI/terminal notifications (defaults to sys.stderr)."""
    self._output_stream = stream

unregister_tui(app=None)

Unregister active Textual TUI app instance.

Source code in app/ui/notifications.py
89
90
91
92
def unregister_tui(self, app: Any = None) -> None:
    """Unregister active Textual TUI app instance."""
    if app is None or self._active_tui_app is app:
        self._active_tui_app = None

NotificationMode

Bases: StrEnum

Runtime environment modes for notification dispatching.

Source code in app/ui/notifications.py
22
23
24
25
26
27
class NotificationMode(StrEnum):
    """Runtime environment modes for notification dispatching."""

    AUTO = "auto"
    TUI = "tui"
    CLI = "cli"

notify(message, type='info', caption=None, timeout=None, help_url=None, **kwargs)

Top-level convenience function for sending notifications.

Source code in app/ui/notifications.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def notify(
    message: Any,
    type: str = "info",
    caption: str | None = None,
    timeout: int | None = None,
    help_url: str | None = None,
    **kwargs: Any,
) -> dict[str, Any]:
    """Top-level convenience function for sending notifications."""
    return NotificationManager.get_instance().notify(
        message,
        type=type,
        caption=caption,
        timeout=timeout,
        help_url=help_url,
        **kwargs,
    )

app.ui.protocols

app.ui.protocols

Structural host protocol shared by AutoSorterTUI and its UI behaviour mixins.

TUIHostProtocol

Bases: Protocol

Structural interface of AutoSorterTUI consumed by TUI behaviour mixins.

Source code in app/ui/protocols.py
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
class TUIHostProtocol(Protocol):
    """Structural interface of ``AutoSorterTUI`` consumed by TUI behaviour mixins."""

    settings: Any
    db: Any | None
    base_dir: str
    source_dirs: list[str]
    plan: dict[str, Any]
    locked_files: dict[str, str]
    _ratings_cache: dict[str, str]
    app_session: Any | None
    pipeline: Any | None
    active_tree_node: TreeNode[Any] | None
    selected_paths: set[str]
    excluded_paths: set[str]
    visual_select_active: bool
    visual_selected_nodes: list[TreeNode[Any]]
    _wizard_dismissed_this_session: bool
    verification_result: dict[str, Any]
    has_critical_errors: bool
    critical_error_paths: set[str]
    warning_paths: set[str]
    collision_paths: set[str]
    _daemon_state: str
    _daemon_is_moving: bool
    _tree_expansion_memory: dict[str, bool]
    _last_cursor_key: str | None
    _pending_flush_trash: bool
    initial_dest_dir: str | None
    _last_drop_session_id: str | None
    _manual_plan_edits: dict[str, dict[str, Any]]
    _manual_empty_folders: set[str]

    @overload
    def query_one(self, selector: str) -> Widget: ...

    @overload
    def query_one(self, selector: type[_QueryType]) -> _QueryType: ...

    @overload
    def query_one(self, selector: str, expect_type: type[_QueryType]) -> _QueryType: ...

    @overload
    def query(self, selector: str | None = None) -> DOMQuery[Widget]: ...

    @overload
    def query(self, selector: type[_QueryType]) -> DOMQuery[_QueryType]: ...

    @overload
    def push_screen(
        self,
        screen: Screen[ScreenResultType] | str,
        callback: ScreenResultCallbackType[ScreenResultType] | None = None,
        wait_for_dismiss: Literal[False] = False,
        *,
        mode: str | None = None,
    ) -> AwaitMount: ...

    @overload
    def push_screen(
        self,
        screen: Screen[ScreenResultType] | str,
        callback: ScreenResultCallbackType[ScreenResultType] | None = None,
        wait_for_dismiss: Literal[True] = True,
        *,
        mode: str | None = None,
    ) -> asyncio.Future[ScreenResultType]: ...

    def call_from_thread(
        self,
        callback: Callable[
            ..., _CallThreadReturnType | Awaitable[_CallThreadReturnType]
        ],
        *args: Any,
        **kwargs: Any,
    ) -> _CallThreadReturnType:
        """Schedule ``callback`` on the main Textual event loop from a worker thread."""
        ...

    def notify(
        self,
        message: str,
        *,
        title: str = "",
        severity: SeverityLevel = "information",
        timeout: float | None = None,
        markup: bool = True,
    ) -> None:
        """Display a transient notification toast in the TUI."""
        ...

    def announce(
        self,
        message: str,
        priority: str = "polite",
        help_url: str | None = None,
    ) -> str:
        """Emit screen reader announcement and write to the TUI execution log."""
        ...

    def update_status(self, text: str | None = None) -> None:
        """Update the TUI status bar text and badges."""
        ...

    def reset_progress_bar(self) -> None:
        """Reset and hide the main progress bar."""
        ...

    def _handle_progress_update(
        self,
        update_or_prog: Any = 0.0,
        stage: str | None = None,
        unit_count: int | None = None,
        unit_type: str | None = None,
        **kwargs: Any,
    ) -> None:
        """Dispatch worker progress updates onto the main UI progress widgets."""
        ...

    def _start_hint(self) -> str:
        """Return onboarding hint text when no plan is loaded."""
        ...

    def _update_onboarding_cta_visibility(self) -> None:
        """Toggle visibility between the onboarding CTA card and inspector pane."""
        ...

    def _get_active_node(self) -> TreeNode[Any] | None:
        """Return the currently highlighted or active plan tree node."""
        ...

    def _is_text_control_focused(self, allow_tree_search: bool = False) -> bool:
        """Return True if an Input or Select control holds active focus."""
        ...

    def _clear_manual_plan_edits(self) -> None:
        """Clear cached manual plan edits and manually created folders."""
        ...

    def _reapply_manual_plan_edits(self) -> None:
        """Reapply cached manual edits onto the active sorting plan after a rescan."""
        ...

    def _get_active_scan_diagnostics(self) -> dict[str, Any]:
        """Return structured scan exclusion diagnostics for the most recent workspace scan."""
        ...

    def action_select_dir(self) -> None:
        """Open the workspace directory selection modal."""
        ...

    def action_open_audit_report(
        self, audit_report: dict[str, Any] | None = None
    ) -> None:
        """Open the post-move audit report modal."""
        ...

    # --- SortPipelineMixin methods ---

    def action_scan_directory(self) -> None:
        """Validate workspace selection and trigger a directory scan."""
        ...

    def action_scan_subfolders(self, from_character: bool = False) -> None:
        """Promote Max Scan Depth for this session and rescan nested subfolders."""
        ...

    def _start_scan(self) -> None:
        """Announce and launch the background scan worker."""
        ...

    def _running_pipeline_worker(self) -> str | None:
        """Return the name of an active scan or execution worker, if any."""
        ...

    def _announce_if_busy(self, action: str) -> bool:
        """Announce and return True if a pipeline or daemon operation is active."""
        ...

    def _handle_pipeline_state_transition(
        self, old_state: Any, new_state: Any, context: dict[str, Any] | None = None
    ) -> None:
        """Record pipeline lifecycle state transitions."""
        ...

    def _handle_pipeline_telemetry(self, event: str, payload: dict[str, Any]) -> None:
        """Record telemetry events emitted by the sort pipeline."""
        ...

    def run_scan_worker(self) -> Any:
        """Launch background directory scan and plan generation worker."""
        ...

    def action_execute_sort(self) -> None:
        """Validate plan and execute scheduled file moves."""
        ...

    def _normalize_plan_for_verification(
        self, plan_dict: dict[str, Any], base_dir: str
    ) -> dict[str, Any]:
        """Populate source path fields across plan file entries before verification."""
        ...

    def run_validation_worker(self) -> Any:
        """Launch background plan integrity validation worker."""
        ...

    def _update_validation_state(self, result: dict[str, Any]) -> None:
        """Apply verification errors and warnings to UI banners and tree styles."""
        ...

    def run_execute_worker(
        self,
        exec_plan_override: dict[str, Any] | None = None,
        *,
        clear_manual_edits: bool = True,
    ) -> Any:
        """Launch background file relocation worker."""
        ...

    # --- SelectionActionsMixin methods ---

    def register_visual_selected_node(self, node: TreeNode[Any]) -> None:
        """Append ``node`` to the active visual selection range."""
        ...

    def extend_shift_range_selection(
        self,
        anchor_node: TreeNode[Any] | None,
        target_node: TreeNode[Any] | None,
    ) -> None:
        """Select scoped file items across ``anchor_node`` and ``target_node`` via Shift+Arrow."""
        ...

    def action_visual_range_select(self) -> None:
        """Toggle visual range selection mode."""
        ...

    def action_toggle_selection(self) -> None:
        """Toggle transient edit selection on the active node or visual selection."""
        ...

    def action_invert_selection(self) -> None:
        """Invert transient edit selection across visible file items."""
        ...

    def _get_target_file_infos(self) -> list[dict[str, Any]]:
        """Return selected file info dicts or fall back to the focused node."""
        ...

    def action_exclude_selected(self) -> None:
        """Exclude selected or focused file items from the sorting plan."""
        ...

    def action_include_selected(self) -> None:
        """Include selected or focused file items in the sorting plan."""
        ...

    def action_reassign_selected(self) -> None:
        """Open reassignment modal for selected or focused file items."""
        ...

    def action_toggle_select_all(self) -> None:
        """Select or deselect all visible file items in the sorting plan."""
        ...

    def _get_executable_plan(
        self,
        plan_dict: dict[str, Any] | None = None,
        _prefix: str = "",
        *,
        visible_only: bool = False,
    ) -> dict[str, Any]:
        """Filter ``plan_dict`` down to included, non-excluded file entries and manual folders."""
        ...

    def action_toggle_lock(self) -> None:
        """Lock or unlock the active file node's target folder assignment."""
        ...

    def _get_checked_file_keys(self) -> list[str]:
        """Return keys of all checked, non-excluded file nodes."""
        ...

    def _get_checked_file_entries(self) -> list[dict[str, Any]]:
        """Return metadata entries for all checked, non-excluded file nodes."""
        ...

    def action_rename_node(self) -> None:
        """Rename the active folder/file node or batch-rename checked files."""
        ...

    def action_new_folder(self) -> None:
        """Prompt to create a new folder category in the sorting plan."""
        ...

    def action_rate_positive(self) -> None:
        """Apply positive rating feedback to the active file node."""
        ...

    def action_rate_negative(self) -> None:
        """Apply negative rating feedback to the active file node."""
        ...

    def _set_rating_for_selected(self, rating: str) -> None:
        """Persist rating feedback for the active file node."""
        ...

    # --- TreeViewMixin methods ---

    def _build_path_lookup_index(self, paths: Any | None = None) -> PathLookupIndex:
        """Pre-index path and basename variants for O(1) membership checks."""
        ...

    def _capture_tree_state(self, tree: Tree[Any], search_query: str = "") -> None:
        """Capture folder expansion state and cursor location prior to tree reset."""
        ...

    def _restore_tree_state(self, tree: Tree[Any], search_query: str = "") -> None:
        """Restore folder expansion state and cursor location after tree render."""
        ...

    def _apply_tree_node_styles(self) -> None:
        """Refresh error, warning, and collision badges on rendered tree nodes."""
        ...

    def _has_file_nodes(self, plan_dict: dict[str, Any]) -> bool:
        """Return True if ``plan_dict`` contains at least one file entry."""
        ...

    def _has_folder_nodes(self, plan_dict: dict[str, Any]) -> bool:
        """Return True if ``plan_dict`` contains at least one folder category dictionary."""
        ...

    def _get_current_search_query(self) -> str:
        """Return the active lowercased search filter string."""
        ...

    def _build_matching_node_ids(
        self, plan_dict: dict[str, Any], query: str, current_folder: str = ""
    ) -> set[int]:
        """Collect object IDs of plan nodes matching ``query``."""
        ...

    def render_tree(self, search_query: str | None = None) -> None:
        """Render the plan tree widget without triggering background validation."""
        ...

    def rebuild_tree(
        self, search_query: str | None = None, run_validation: bool = True
    ) -> None:
        """Re-render the plan tree widget and optionally run integrity validation."""
        ...

    def _collect_file_nodes_from_dict(self, d: dict[str, Any]) -> list[dict[str, Any]]:
        """Recursively collect file info dicts under ``d``."""
        ...

    def _collect_visible_file_nodes_from_dict(
        self,
        node_dict: dict[str, Any],
        current_folder: str = "",
        query: str = "",
        parent_folder_matches: bool = False,
        matching_ids: set[int] | None = None,
    ) -> list[dict[str, Any]]:
        """Collect file info dicts visible under the active search query."""
        ...

    def _node_matches_query(
        self, key: str, val: dict[str, Any], current_folder: str, query: str
    ) -> bool:
        """Return True if ``val`` or any descendant matches ``query``."""
        ...

    def _build_tree_nodes(
        self,
        node_dict: dict[str, Any],
        parent_item: TreeNode[Any],
        current_folder: str,
        query: str = "",
        parent_folder_matches: bool = False,
        matching_ids: set[int] | None = None,
        crit_index: tuple[set[str], set[str]] | None = None,
        warn_index: tuple[set[str], set[str]] | None = None,
        collision_index: tuple[set[str], set[str]] | None = None,
    ) -> int:
        """Recursively populate ``parent_item`` from ``node_dict``."""
        ...

    def _update_inspector(self, node_or_data: Any = None, announce: bool = True) -> str:
        """Update the metadata inspector and side-by-side path comparison panes."""
        ...

    def _update_tree_summary_strip(self) -> None:
        """Refresh the selection and plan inclusion counts in the summary strip above the tree."""
        ...

    def refresh_tree_selection_markers(self) -> None:
        """Update tree row selection/inclusion markers and summary strip in place."""
        ...

    def action_collapse_all(self) -> None:
        """Collapse all destination folder nodes in the plan tree."""
        ...

    def action_expand_all(self) -> None:
        """Expand all destination folder nodes in the plan tree."""
        ...

action_collapse_all()

Collapse all destination folder nodes in the plan tree.

Source code in app/ui/protocols.py
426
427
428
def action_collapse_all(self) -> None:
    """Collapse all destination folder nodes in the plan tree."""
    ...

action_exclude_selected()

Exclude selected or focused file items from the sorting plan.

Source code in app/ui/protocols.py
274
275
276
def action_exclude_selected(self) -> None:
    """Exclude selected or focused file items from the sorting plan."""
    ...

action_execute_sort()

Validate plan and execute scheduled file moves.

Source code in app/ui/protocols.py
217
218
219
def action_execute_sort(self) -> None:
    """Validate plan and execute scheduled file moves."""
    ...

action_expand_all()

Expand all destination folder nodes in the plan tree.

Source code in app/ui/protocols.py
430
431
432
def action_expand_all(self) -> None:
    """Expand all destination folder nodes in the plan tree."""
    ...

action_include_selected()

Include selected or focused file items in the sorting plan.

Source code in app/ui/protocols.py
278
279
280
def action_include_selected(self) -> None:
    """Include selected or focused file items in the sorting plan."""
    ...

action_invert_selection()

Invert transient edit selection across visible file items.

Source code in app/ui/protocols.py
266
267
268
def action_invert_selection(self) -> None:
    """Invert transient edit selection across visible file items."""
    ...

action_new_folder()

Prompt to create a new folder category in the sorting plan.

Source code in app/ui/protocols.py
316
317
318
def action_new_folder(self) -> None:
    """Prompt to create a new folder category in the sorting plan."""
    ...

action_open_audit_report(audit_report=None)

Open the post-move audit report modal.

Source code in app/ui/protocols.py
175
176
177
178
179
def action_open_audit_report(
    self, audit_report: dict[str, Any] | None = None
) -> None:
    """Open the post-move audit report modal."""
    ...

action_rate_negative()

Apply negative rating feedback to the active file node.

Source code in app/ui/protocols.py
324
325
326
def action_rate_negative(self) -> None:
    """Apply negative rating feedback to the active file node."""
    ...

action_rate_positive()

Apply positive rating feedback to the active file node.

Source code in app/ui/protocols.py
320
321
322
def action_rate_positive(self) -> None:
    """Apply positive rating feedback to the active file node."""
    ...

action_reassign_selected()

Open reassignment modal for selected or focused file items.

Source code in app/ui/protocols.py
282
283
284
def action_reassign_selected(self) -> None:
    """Open reassignment modal for selected or focused file items."""
    ...

action_rename_node()

Rename the active folder/file node or batch-rename checked files.

Source code in app/ui/protocols.py
312
313
314
def action_rename_node(self) -> None:
    """Rename the active folder/file node or batch-rename checked files."""
    ...

action_scan_directory()

Validate workspace selection and trigger a directory scan.

Source code in app/ui/protocols.py
183
184
185
def action_scan_directory(self) -> None:
    """Validate workspace selection and trigger a directory scan."""
    ...

action_scan_subfolders(from_character=False)

Promote Max Scan Depth for this session and rescan nested subfolders.

Source code in app/ui/protocols.py
187
188
189
def action_scan_subfolders(self, from_character: bool = False) -> None:
    """Promote Max Scan Depth for this session and rescan nested subfolders."""
    ...

action_select_dir()

Open the workspace directory selection modal.

Source code in app/ui/protocols.py
171
172
173
def action_select_dir(self) -> None:
    """Open the workspace directory selection modal."""
    ...

action_toggle_lock()

Lock or unlock the active file node's target folder assignment.

Source code in app/ui/protocols.py
300
301
302
def action_toggle_lock(self) -> None:
    """Lock or unlock the active file node's target folder assignment."""
    ...

action_toggle_select_all()

Select or deselect all visible file items in the sorting plan.

Source code in app/ui/protocols.py
286
287
288
def action_toggle_select_all(self) -> None:
    """Select or deselect all visible file items in the sorting plan."""
    ...

action_toggle_selection()

Toggle transient edit selection on the active node or visual selection.

Source code in app/ui/protocols.py
262
263
264
def action_toggle_selection(self) -> None:
    """Toggle transient edit selection on the active node or visual selection."""
    ...

action_visual_range_select()

Toggle visual range selection mode.

Source code in app/ui/protocols.py
258
259
260
def action_visual_range_select(self) -> None:
    """Toggle visual range selection mode."""
    ...

announce(message, priority='polite', help_url=None)

Emit screen reader announcement and write to the TUI execution log.

Source code in app/ui/protocols.py
115
116
117
118
119
120
121
122
def announce(
    self,
    message: str,
    priority: str = "polite",
    help_url: str | None = None,
) -> str:
    """Emit screen reader announcement and write to the TUI execution log."""
    ...

call_from_thread(callback, *args, **kwargs)

Schedule callback on the main Textual event loop from a worker thread.

Source code in app/ui/protocols.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def call_from_thread(
    self,
    callback: Callable[
        ..., _CallThreadReturnType | Awaitable[_CallThreadReturnType]
    ],
    *args: Any,
    **kwargs: Any,
) -> _CallThreadReturnType:
    """Schedule ``callback`` on the main Textual event loop from a worker thread."""
    ...

extend_shift_range_selection(anchor_node, target_node)

Select scoped file items across anchor_node and target_node via Shift+Arrow.

Source code in app/ui/protocols.py
250
251
252
253
254
255
256
def extend_shift_range_selection(
    self,
    anchor_node: TreeNode[Any] | None,
    target_node: TreeNode[Any] | None,
) -> None:
    """Select scoped file items across ``anchor_node`` and ``target_node`` via Shift+Arrow."""
    ...

notify(message, *, title='', severity='information', timeout=None, markup=True)

Display a transient notification toast in the TUI.

Source code in app/ui/protocols.py
103
104
105
106
107
108
109
110
111
112
113
def notify(
    self,
    message: str,
    *,
    title: str = "",
    severity: SeverityLevel = "information",
    timeout: float | None = None,
    markup: bool = True,
) -> None:
    """Display a transient notification toast in the TUI."""
    ...

rebuild_tree(search_query=None, run_validation=True)

Re-render the plan tree widget and optionally run integrity validation.

Source code in app/ui/protocols.py
372
373
374
375
376
def rebuild_tree(
    self, search_query: str | None = None, run_validation: bool = True
) -> None:
    """Re-render the plan tree widget and optionally run integrity validation."""
    ...

refresh_tree_selection_markers()

Update tree row selection/inclusion markers and summary strip in place.

Source code in app/ui/protocols.py
422
423
424
def refresh_tree_selection_markers(self) -> None:
    """Update tree row selection/inclusion markers and summary strip in place."""
    ...

register_visual_selected_node(node)

Append node to the active visual selection range.

Source code in app/ui/protocols.py
246
247
248
def register_visual_selected_node(self, node: TreeNode[Any]) -> None:
    """Append ``node`` to the active visual selection range."""
    ...

render_tree(search_query=None)

Render the plan tree widget without triggering background validation.

Source code in app/ui/protocols.py
368
369
370
def render_tree(self, search_query: str | None = None) -> None:
    """Render the plan tree widget without triggering background validation."""
    ...

reset_progress_bar()

Reset and hide the main progress bar.

Source code in app/ui/protocols.py
128
129
130
def reset_progress_bar(self) -> None:
    """Reset and hide the main progress bar."""
    ...

run_execute_worker(exec_plan_override=None, *, clear_manual_edits=True)

Launch background file relocation worker.

Source code in app/ui/protocols.py
235
236
237
238
239
240
241
242
def run_execute_worker(
    self,
    exec_plan_override: dict[str, Any] | None = None,
    *,
    clear_manual_edits: bool = True,
) -> Any:
    """Launch background file relocation worker."""
    ...

run_scan_worker()

Launch background directory scan and plan generation worker.

Source code in app/ui/protocols.py
213
214
215
def run_scan_worker(self) -> Any:
    """Launch background directory scan and plan generation worker."""
    ...

run_validation_worker()

Launch background plan integrity validation worker.

Source code in app/ui/protocols.py
227
228
229
def run_validation_worker(self) -> Any:
    """Launch background plan integrity validation worker."""
    ...

update_status(text=None)

Update the TUI status bar text and badges.

Source code in app/ui/protocols.py
124
125
126
def update_status(self, text: str | None = None) -> None:
    """Update the TUI status bar text and badges."""
    ...

Debounced tree search filtering, focus handoff, and search-scoped node selection helpers.

collect_scoped_file_nodes(host, node_dict, *, current_folder='', query='')

Collect file info dicts under node_dict, respecting active query filters.

Source code in app/ui/tree_search.py
17
18
19
20
21
22
23
24
25
26
27
28
29
def collect_scoped_file_nodes(
    host: "TUIHostProtocol",
    node_dict: dict[str, Any],
    *,
    current_folder: str = "",
    query: str = "",
) -> list[dict[str, Any]]:
    """Collect file info dicts under ``node_dict``, respecting active ``query`` filters."""
    return host._collect_visible_file_nodes_from_dict(
        node_dict,
        current_folder=current_folder,
        query=query,
    )

find_first_selectable_tree_node(root)

Return the first visible file node (or non-empty-state folder node) under root.

Source code in app/ui/tree_search.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def find_first_selectable_tree_node(root: TreeNode[Any]) -> TreeNode[Any] | None:
    """Return the first visible file node (or non-empty-state folder node) under ``root``."""
    first_folder: TreeNode[Any] | None = None

    def _walk(node: TreeNode[Any]) -> TreeNode[Any] | None:
        nonlocal first_folder
        for child in node.children:
            cdata = getattr(child, "data", None)
            if isinstance(cdata, dict) and not cdata.get("is_empty_state"):
                if cdata.get("is_file"):
                    return child
                if first_folder is None:
                    first_folder = child
            found = _walk(child)
            if found is not None:
                return found
        return None

    return _walk(root) or first_folder

flush_tree_search_filter(host)

Flush any pending debounced tree filter timer and render the current search query immediately.

Source code in app/ui/tree_search.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def flush_tree_search_filter(host: Any) -> None:
    """Flush any pending debounced tree filter timer and render the current search query immediately."""
    inp_matches = host.query("#tree-search-input")
    if not inp_matches:
        return
    inp = inp_matches.first(Input)
    timer = getattr(host, "_tree_filter_timer", None)
    pending = bool(getattr(host, "_tree_filter_pending", False))
    if timer is not None:
        timer.stop()
        host._tree_filter_timer = None
    host._tree_filter_pending = False
    current_val = inp.value
    normalized_val = current_val.strip().lower()
    last_rendered = getattr(host, "_last_rendered_search_query", None)
    if pending or last_rendered != normalized_val:
        host._flushed_search_value = current_val
        host.render_tree(search_query=current_val)

handle_search_and_tree_key(host, event)

Handle search-to-tree focus handoff keys and second-step Escape filter clearing.

Source code in app/ui/tree_search.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def handle_search_and_tree_key(host: Any, event: events.Key) -> bool:
    """Handle search-to-tree focus handoff keys and second-step ``Escape`` filter clearing."""
    if isinstance(host.screen, ModalScreen):
        return False

    inp_matches = host.query("#tree-search-input")
    if not inp_matches:
        return False
    inp = inp_matches.first(Input)

    if inp.has_focus and event.key in HANDOFF_KEYS:
        handoff_search_to_tree(host)
        event.stop()
        event.prevent_default()
        return True

    if event.key in ESCAPE_KEYS:
        tree_matches = host.query("#plan-tree")
        if not tree_matches:
            return False
        tree = tree_matches.first(Tree)
        has_pending = bool(getattr(host, "_tree_filter_pending", False))
        if (
            tree.has_focus
            and not getattr(host, "visual_select_active", False)
            and (bool(inp.value) or has_pending)
        ):
            timer = getattr(host, "_tree_filter_timer", None)
            if timer is not None:
                timer.stop()
                host._tree_filter_timer = None
            host._tree_filter_pending = False
            host._flushed_search_value = ""
            inp.value = ""
            host.render_tree(search_query="")
            event.stop()
            event.prevent_default()
            return True

    return False

handoff_search_to_tree(host)

Flush pending filter updates and move focus from #tree-search-input to #plan-tree.

Source code in app/ui/tree_search.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def handoff_search_to_tree(host: Any) -> None:
    """Flush pending filter updates and move focus from ``#tree-search-input`` to ``#plan-tree``."""
    flush_tree_search_filter(host)
    tree_matches = host.query("#plan-tree")
    if not tree_matches:
        return
    tree = tree_matches.first(Tree)
    cursor_data = getattr(tree.cursor_node, "data", None) if tree.cursor_node else None
    if not (isinstance(cursor_data, dict) and not cursor_data.get("is_empty_state")):
        first_node = find_first_selectable_tree_node(tree.root)
        if first_node is not None:
            tree.select_node(first_node)
            host.active_tree_node = first_node
    tree.focus()

schedule_tree_search_filter(host, value, *, delay=0.15)

Debounce real-time #tree-search-input changes while skipping already-flushed queries.

Source code in app/ui/tree_search.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def schedule_tree_search_filter(host: Any, value: str, *, delay: float = 0.15) -> None:
    """Debounce real-time ``#tree-search-input`` changes while skipping already-flushed queries."""
    if getattr(host, "_flushed_search_value", None) == value:
        host._flushed_search_value = None
        return
    host._flushed_search_value = None
    timer = getattr(host, "_tree_filter_timer", None)
    if timer is not None:
        timer.stop()
    host._tree_filter_pending = True

    def _apply_filter() -> None:
        host._tree_filter_pending = False
        host._tree_filter_timer = None
        host.render_tree(search_query=value)

    host._tree_filter_timer = host.set_timer(delay, _apply_filter)

app.ui.tui

app.ui.tui

Textual full-screen terminal interface with interactive tree and modal dialogs.

AutoSorterTUI

Bases: ResponsiveLayoutMixin, A11yMixin, SortPipelineMixin, SelectionActionsMixin, TreeViewMixin, App

Textual full-screen interactive TUI application for Sortify AI Pro.

Source code in app/ui/tui.py
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
class AutoSorterTUI(
    ResponsiveLayoutMixin,
    A11yMixin,
    SortPipelineMixin,
    SelectionActionsMixin,
    TreeViewMixin,
    App,
):
    """Textual full-screen interactive TUI application for Sortify AI Pro."""

    TITLE = "Sortify AI Pro - Terminal UI"
    SUB_TITLE = "Interactive Tree & Modal Controls"
    ENABLE_COMMAND_PALETTE = False

    BINDINGS = [
        Binding("space", "toggle_selection", "Toggle Selection", show=True),
        Binding("x", "exclude_selected", "Exclude", show=False),
        Binding("i", "include_selected", "Include", show=False),
        Binding("r", "reassign_selected", "Reassign", show=False),
        Binding("v", "visual_range_select", "Range Select", show=False),
        Binding("a", "toggle_select_all", "Select/Deselect All", show=False),
        Binding("ctrl+l", "toggle_lock", "Lock/Unlock", show=False),
        Binding("ctrl+r", "open_active_rules", "Rule Manager", show=False),
        Binding("f2", "rename_node", "Rename Node", show=False),
        Binding("ctrl+n", "new_folder", "New Folder", show=False),
        Binding("plus", "rate_positive", "Rating (+)", show=False),
        Binding("minus", "rate_negative", "Rating (-)", show=False),
        Binding("ctrl+o", "open_settings", "Settings", show=False),
        Binding("ctrl+g", "open_model_manager", "Model Manager", show=False),
        Binding(
            "ctrl+k",
            "open_command_palette",
            "Command Palette",
            show=True,
            priority=True,
        ),
        Binding("ctrl+w", "open_wizard", "Wizard", show=False),
        Binding("ctrl+d", "open_dropzone", "DropZone", show=False),
        Binding("ctrl+t", "toggle_daemon(False)", "Toggle Daemon", show=False),
        Binding("p", "toggle_daemon(True)", "Toggle Daemon", show=False),
        Binding("ctrl+s", "scan_directory", "Scan", show=True),
        Binding("ctrl+y", "open_history", "History View", show=False),
        Binding("ctrl+u", "open_quarantine_vault", "Quarantine Vault", show=False),
        Binding("ctrl+e", "execute_sort", "Execute Plan", show=True),
        Binding("ctrl+z", "undo_last_sort", "Undo Sort", show=True),
        Binding("ctrl+a", "open_audit_report", "Audit Report", show=False),
        Binding("ctrl+x", "open_extraction_preview", "Extraction Preview", show=False),
        Binding("ctrl+b", "select_dir", "Browse Dir", show=True),
        Binding("ctrl+f", "focus_search", "Search Tree", show=True),
        Binding("g", "generate_sample_corpus(True)", "Sample Dataset", show=False),
        Binding("G", "generate_sample_corpus(True)", "Sample Dataset", show=False),
        Binding(
            "shift+g", "generate_sample_corpus(True)", "Sample Dataset", show=False
        ),
        Binding("d", "scan_subfolders(True)", "Scan Subfolders", show=False),
        Binding("D", "scan_subfolders(True)", "Scan Subfolders", show=False),
        Binding("question_mark", "open_cheat_sheet(True)", "Help", show=True),
        Binding("f1", "open_cheat_sheet(False)", "Help (F1)", show=False),
        Binding(
            "ctrl+alt+k",
            "toggle_character_shortcuts",
            "Toggle Shortcuts",
            show=False,
        ),
        Binding("ctrl+q", "quit", "Quit", show=True),
    ]

    CSS = """
    Screen {
        layout: vertical;
        background: $surface;
    }
    #app-title-heading {
        display: none;
    }
    #main-dual-pane {
        layout: horizontal;
        height: 1fr;
        width: 100%;
    }
    #main-dual-pane.narrow {
        layout: vertical;
    }
    #left-tree-pane {
        width: 50%;
        height: 100%;
        border: solid $primary;
        padding: 0;
    }
    #main-dual-pane.narrow #left-tree-pane {
        width: 100%;
        height: 9;
        min-height: 8;
    }
    #tree-search-input {
        width: 100%;
        height: auto;
        border: none;
        border-bottom: solid $primary;
        margin: 0;
    }
    #main-dual-pane.narrow #tree-search-input {
        height: 1;
        border: none;
        background: $boost;
    }
    #tree-summary-strip {
        layout: vertical;
        width: 100%;
        height: auto;
        background: $boost;
        border-bottom: solid $primary-darken-2;
        padding: 0 1;
        margin: 0;
    }
    #tree-summary-strip.wide-summary {
        layout: horizontal;
        height: 1;
    }
    #main-dual-pane.narrow #tree-summary-strip {
        layout: horizontal;
        height: 1;
        border-bottom: none;
        padding: 0;
    }
    #tree-summary-label {
        width: 100%;
        height: 1;
        color: $text-muted;
        content-align: left middle;
    }
    #tree-summary-strip.wide-summary #tree-summary-label,
    #main-dual-pane.narrow #tree-summary-label {
        width: 1fr;
    }
    #tree-summary-actions {
        layout: horizontal;
        width: 100%;
        height: 1;
    }
    #tree-summary-strip.wide-summary #tree-summary-actions,
    #main-dual-pane.narrow #tree-summary-actions {
        width: auto;
    }
    .tree-strip-btn {
        height: 1;
        min-height: 1;
        border: none;
        padding: 0 1;
        margin: 0 1 0 0;
        background: $surface-lighten-1;
        color: $text;
    }
    #btn-tree-invert-selection {
        min-width: 8;
    }
    #btn-tree-collapse-all {
        min-width: 14;
    }
    #btn-tree-expand-all {
        min-width: 12;
        margin-right: 0;
    }
    #main-dual-pane.narrow .tree-strip-btn {
        padding: 0;
        margin: 0 0 0 1;
    }
    #main-dual-pane.narrow #btn-tree-invert-selection {
        min-width: 6;
    }
    #main-dual-pane.narrow #btn-tree-collapse-all {
        min-width: 12;
    }
    #main-dual-pane.narrow #btn-tree-expand-all {
        min-width: 10;
    }
    #plan-tree {
        width: 100%;
        height: 1fr;
        min-height: 4;
        border: none;
        padding: 0;
    }
    #right-meta-pane {
        layout: vertical;
        width: 50%;
        height: 100%;
        border: solid $secondary;
        padding: 1 2;
        overflow-y: hidden;
    }
    .compact #right-meta-pane {
        padding: 0 1;
    }
    #main-dual-pane.narrow #right-meta-pane {
        width: 100%;
        height: 1fr;
        min-height: 9;
        padding: 0 1;
    }
    #right-meta-scroll {
        width: 100%;
        height: 1fr;
        overflow-y: auto;
    }
    .tui-log-area {
        height: auto;
        max-height: 10;
        min-height: 3;
        margin-top: 1;
        border: solid $secondary;
    }
    .compact .tui-log-area {
        margin-top: 0;
        max-height: 6;
    }
    #main-progress-bar {
        width: 100%;
        height: 1;
        margin: 0;
        padding: 0;
    }
    #status-bar {
        height: 1;
        background: $primary-darken-2;
        color: $text;
        padding: 0 1;
    }
    .meta-header {
        text-style: bold;
        color: $accent;
        margin-bottom: 1;
    }
    .meta-line {
        margin-bottom: 1;
    }
    Tree:focus, Static:focus, Log:focus, Input:focus {
        border: heavy $accent;
        text-style: bold;
    }
    #alert-banner {
        width: 100%;
        height: auto;
        min-height: 1;
        max-height: 4;
        overflow-y: auto;
        padding: 0 1;
        margin: 0;
        display: none;
    }
    .compact #alert-banner {
        max-height: 3;
    }
    #alert-banner.alert-critical {
        background: $error-darken-2;
        color: $text;
        border: solid $error;
        text-style: bold;
        display: block;
    }
    #alert-banner.alert-warning {
        background: $warning-darken-2;
        color: $text;
        border: solid $warning;
        display: block;
    }
    #btn-execute {
        margin-top: 1;
        width: 100%;
    }
    .compact #btn-execute {
        margin-top: 0;
    }
    #main-dual-pane.narrow #btn-execute {
        height: 1;
        min-height: 1;
        border: none;
        margin-top: 0;
    }
    #onboarding-cta-card {
        border: solid $accent;
        padding: 1 2;
        margin-bottom: 1;
        background: $surface;
        height: auto;
    }
    .compact #onboarding-cta-card {
        padding: 0 1;
        margin-bottom: 0;
    }
    .compact .meta-header {
        margin-bottom: 0;
    }
    #onboarding-guide-text {
        margin-bottom: 1;
    }
    .compact #onboarding-guide-text {
        margin-bottom: 0;
    }
    #onboarding-workspace-state {
        margin-bottom: 1;
        color: $accent;
        text-style: bold;
    }
    .compact #onboarding-workspace-state {
        margin-bottom: 0;
    }
    #onboarding-cta-buttons {
        layout: vertical;
        height: auto;
    }
    #onboarding-cta-buttons Button {
        width: 100%;
        margin-bottom: 1;
    }
    .compact #onboarding-cta-buttons Button {
        margin-bottom: 0;
    }
    #main-dual-pane.narrow #onboarding-cta-buttons Button {
        height: 1;
        min-height: 1;
        border: none;
        margin-bottom: 0;
    }
    #inspector-container {
        height: auto;
    }
    """

    def __init__(
        self,
        settings,
        base_dir: str | None = None,
        source_dirs: list[str] | None = None,
        skip_wizard: bool = False,
        non_interactive: bool = False,
        db: Any | None = None,
        open_dropzone: bool = False,
        initial_drop_paths: list[str] | None = None,
        initial_dest_dir: str | None = None,
    ):
        super().__init__()
        self.settings = settings
        self.db = db
        if source_dirs:
            self.source_dirs = [
                d if str(d).startswith("/") else os.path.abspath(d)
                for d in source_dirs
                if d
            ]
            self.base_dir = self.source_dirs[0] if self.source_dirs else ""
        elif base_dir and str(base_dir).startswith("/"):
            self.base_dir = str(base_dir)
            self.source_dirs = [self.base_dir]
        elif base_dir:
            self.base_dir = os.path.abspath(base_dir)
            self.source_dirs = [self.base_dir]
        else:
            self.base_dir = ""
            self.source_dirs = []
        self._active_folder_settings: Any = self.get_active_settings()
        self.skip_wizard = skip_wizard
        self.non_interactive = non_interactive
        self.open_dropzone = bool(open_dropzone)
        self.initial_drop_paths: list[str] = (
            list(initial_drop_paths) if initial_drop_paths else []
        )
        self.initial_dest_dir: str | None = initial_dest_dir
        self._last_drop_session_id: str | None = None
        self.plan: dict[str, Any] = {}
        self.locked_files: dict[str, str] = {}
        self._ratings_cache: dict[str, str] = {}
        self.app_session: Any | None = None
        self.pipeline: Any | None = None
        self.active_tree_node: TreeNode[Any] | None = None
        self.visual_select_active: bool = False
        self.visual_selected_nodes: list[TreeNode[Any]] = []
        self.selected_paths: set[str] = set()
        self.excluded_paths: set[str] = set()
        self._tree_expansion_memory: dict[str, bool] = {}
        self._last_rendered_expansion_snapshot: dict[str, bool] = {}
        self._wizard_dismissed_this_session: bool = False
        self.verification_result: dict[str, Any] = {}
        self.has_critical_errors: bool = False
        self.critical_error_paths: set[str] = set()
        self.warning_paths: set[str] = set()
        self.collision_paths: set[str] = set()
        self._daemon_state: str = "idle"
        self._daemon_is_moving: bool = False
        self._pending_flush_trash: bool = False
        self._pending_ai_active_rescan: bool = False
        self._last_ai_poll_token: tuple[Any, ...] | None = None
        self._manual_plan_edits: dict[str, dict[str, Any]] = {}
        self._manual_empty_folders: set[str] = set()
        self._tree_filter_timer: Any = None
        self._tree_filter_pending: bool = False
        self._flushed_search_value: str | None = None

    def compose(self) -> ComposeResult:
        """Compose main dual-pane TUI layout."""
        yield Heading(self.TITLE or "", level=1, id="app-title-heading")
        yield Header(show_clock=True)
        with Horizontal(id="main-dual-pane"):
            with Vertical(id="left-tree-pane"):
                search_input = Input(
                    placeholder="Search tree nodes...",
                    id="tree-search-input",
                )
                search_input.tooltip = (
                    "Real-time search input field to filter preview tree nodes"
                )
                yield search_input
                with Horizontal(id="tree-summary-strip"):
                    summary_lbl = Static(
                        "Selection: 0 selected · Plan: 0 of 0 included",
                        id="tree-summary-label",
                        markup=False,
                    )
                    summary_lbl.tooltip = "Summary of transient edit selection count and included plan items"
                    yield summary_lbl
                    with Horizontal(id="tree-summary-actions"):
                        btn_invert = Button(
                            "Invert",
                            id="btn-tree-invert-selection",
                            classes="tree-strip-btn",
                        )
                        btn_invert.tooltip = (
                            "Invert transient edit selection across visible files"
                        )
                        yield btn_invert

                        btn_collapse = Button(
                            "Collapse All",
                            id="btn-tree-collapse-all",
                            classes="tree-strip-btn",
                        )
                        btn_collapse.tooltip = (
                            "Collapse all destination folders in the plan tree"
                        )
                        yield btn_collapse

                        btn_expand = Button(
                            "Expand All",
                            id="btn-tree-expand-all",
                            classes="tree-strip-btn",
                        )
                        btn_expand.tooltip = (
                            "Expand all destination folders in the plan tree"
                        )
                        yield btn_expand
                tree = VimTree("Proposed Organization Plan", id="plan-tree")
                tree.tooltip = (
                    "Interactive tree view of proposed file organization plan"
                )
                yield tree
            with Vertical(id="right-meta-pane"):
                with Vertical(id="right-meta-scroll"):
                    with Vertical(id="onboarding-cta-card"):
                        yield Heading(
                            "Workspace Setup & Quick Actions",
                            level=2,
                            classes="meta-header",
                        )
                        yield Static(
                            "Welcome to Sortify AI Pro. Select a workspace directory, run a scan, or load a sample dataset to get started.",
                            id="onboarding-guide-text",
                        )
                        initial_workspace_state = (
                            f"Active Workspace: {self.base_dir}"
                            if self.base_dir
                            else "Active Workspace: No directory selected"
                        )
                        yield Static(
                            initial_workspace_state, id="onboarding-workspace-state"
                        )
                        with Vertical(id="onboarding-cta-buttons"):
                            btn_select_dir = Button(
                                "Choose Directory [Ctrl+B]",
                                id="btn-cta-select-dir",
                                variant="primary",
                            )
                            btn_select_dir.tooltip = "Open directory selection dialog to choose workspace folder [Ctrl+B]"
                            yield btn_select_dir

                            btn_scan_dir = Button(
                                "Scan Directory [Ctrl+S]",
                                id="btn-cta-scan-dir",
                                variant="success",
                            )
                            btn_scan_dir.tooltip = "Initiate workspace scan to generate organization plan [Ctrl+S]"
                            yield btn_scan_dir

                            btn_sample_data = Button(
                                "Load Sample Dataset \\[G]",
                                id="btn-cta-sample-data",
                                variant="default",
                            )
                            btn_sample_data.tooltip = (
                                "Generate interactive sample dataset in workspace [G]"
                            )
                            yield btn_sample_data
                    with Vertical(id="inspector-container"):
                        yield Heading(
                            "Side-by-Side Path Comparison",
                            level=2,
                            classes="meta-header",
                        )
                        path_comp = Static(
                            "Select a file or folder in the tree to compare source and target paths.",
                            id="path-comparison",
                        )
                        path_comp.tooltip = "Side-by-side split column view comparing source and destination target paths"
                        yield path_comp
                        yield Heading(
                            "Node Metadata Inspector", level=2, classes="meta-header"
                        )
                        meta_widget = Static(
                            "Select a node in the tree to inspect details.",
                            id="meta-details",
                        )
                        meta_widget.tooltip = "Metadata inspector panel displaying attributes of selected file or folder"
                        yield meta_widget
                    yield Heading("Live Execution Log", level=2, classes="meta-header")
                    tui_log = Log(id="tui-log", classes="tui-log-area")
                    tui_log.tooltip = "Live operation execution log output feed"
                    yield tui_log
                btn_exec = Button(
                    "Execute Plan [Ctrl+E]",
                    id="btn-execute",
                    variant="primary",
                    disabled=True,
                )
                btn_exec.tooltip = EXECUTE_NEEDS_SCAN_TOOLTIP
                yield btn_exec
        alert_banner = Static("", id="alert-banner")
        alert_banner.tooltip = (
            "Validation alert banner displaying blocking errors or warnings"
        )
        yield alert_banner
        pb = ProgressBar(total=100, show_percentage=True, id="main-progress-bar")
        pb.tooltip = "Active operation background progress indicator"
        pb.display = False
        yield pb
        initial_status = f"{self._get_ai_status_badge()} {self._get_daemon_status_badge()} Ready. Press [Ctrl+S] to Scan or [Ctrl+B] to select Directory."
        sb = Static(
            initial_status,
            id="status-bar",
            markup=False,
        )
        sb.tooltip = "Application status and screen reader announcement bar"
        yield sb
        yield _StableFooter()

    def announce(
        self,
        message: str,
        priority: str = "polite",
        help_url: str | None = None,
    ) -> str:
        """Emit screen reader announcement and log to live execution log feed."""
        res = super().announce(message, priority=priority, help_url=help_url)
        try:
            log_w = self.query_one("#tui-log", Log)
            display_msg = (
                f"{res} [Help: {help_url}]" if help_url and help_url not in res else res
            )
            log_w.write_line(display_msg)
        except Exception:
            pass
        return res

    def _handle_progress_update(
        self,
        update_or_prog: Any = 0.0,
        stage: str | None = None,
        unit_count: int | None = None,
        unit_type: str | None = None,
        **kwargs: Any,
    ) -> None:
        """Handle progress updates dispatched from worker threads to main UI thread."""
        try:
            pb = self.query_one("#main-progress-bar", ProgressBar)
            pb.display = True

            progress_val = 0.0
            stage_text = stage
            count_val = unit_count

            if hasattr(update_or_prog, "progress"):
                progress_val = getattr(update_or_prog, "progress", 0.0)
                if stage_text is None:
                    stage_text = getattr(update_or_prog, "stage", None)
                if count_val is None:
                    count_val = getattr(update_or_prog, "unit_count", None)
                if unit_type is None:
                    unit_type = getattr(update_or_prog, "unit_type", None)
            elif isinstance(update_or_prog, (int, float)):
                progress_val = float(update_or_prog)
            elif isinstance(update_or_prog, str):
                stage_text = update_or_prog

            # Convert 0.0-1.0 ratio to percentage (0.0-100.0) if needed
            if 0.0 <= progress_val <= 1.0:
                pct = progress_val * 100.0
            else:
                pct = progress_val

            pct = min(100.0, max(0.0, pct))
            pb.progress = pct

            if stage_text:
                status_msg = f"[{pct:.0f}%] {stage_text}"
                if count_val is not None:
                    u_type = unit_type or "items"
                    status_msg = f"[{pct:.0f}%] ({count_val} {u_type}) {stage_text}"
                self.update_status(status_msg)
                try:
                    log_w = self.query_one("#tui-log", Log)
                    log_w.write_line(status_msg)
                except Exception:
                    pass
        except Exception as e:
            logger.debug(f"Error handling progress update: {e}")

    def reset_progress_bar(self) -> None:
        """Reset progress bar to idle state and hide component."""
        try:
            pb = self.query_one("#main-progress-bar", ProgressBar)
            pb.progress = 0.0
            pb.total = 100
            pb.display = False
        except Exception:
            pass

    def _update_layout(self, width: int, height: int | None = None) -> None:
        """Update container CSS classes based on viewport width and height breakpoints."""
        effective_height = self._resolve_viewport_height(height)
        is_compact = width <= 100 or effective_height <= 30
        if is_compact:
            self.add_class("compact")
        else:
            self.remove_class("compact")
        try:
            dual_pane = self.query_one("#main-dual-pane")
            if width < 100:
                dual_pane.add_class("narrow")
            else:
                dual_pane.remove_class("narrow")
            if is_compact:
                dual_pane.add_class("compact")
            else:
                dual_pane.remove_class("compact")
            strip_matches = self.query("#tree-summary-strip")
            if strip_matches:
                strip_w = strip_matches.first()
                if width >= 176:
                    strip_w.add_class("wide-summary")
                else:
                    strip_w.remove_class("wide-summary")
        except Exception:
            pass

    def _start_hint(self) -> str:
        """Tell a user with no plan yet which key starts the workflow."""
        if self.base_dir:
            return f"No plan yet. Press Ctrl+S to scan {self.base_dir}, or Ctrl+B to choose another folder."
        return "No plan yet. Press Ctrl+B to choose a folder to sort."

    def on_mount(self) -> None:
        """Mount event handler."""
        self._update_layout(self.size.width, self.size.height)
        try:
            from app.ui.notifications import NotificationManager

            NotificationManager.get_instance().register_tui(self)
        except Exception:
            pass
        try:
            from app.config import AppSettings

            AppSettings.add_observer("AI_CONSENT_GRANTED", self._on_ai_consent_changed)
            AppSettings.add_observer(
                "ENABLE_CHARACTER_KEY_SHORTCUTS",
                self._on_character_shortcuts_changed,
            )
        except Exception:
            pass
        try:
            tree = self.query_one("#plan-tree", Tree)
            tree.show_root = True
            tree.root.expand()
            tree.focus()
        except Exception:
            pass
        self._update_tree_summary_strip()
        self.announce(f"Ready. {self._start_hint()}")
        self._update_onboarding_cta_visibility()
        self.check_abandoned_sessions()
        self.set_interval(1.0, self._poll_daemon_status)
        self.set_interval(0.5, self._poll_ai_provisioning_status)
        self.run_worker(self._poll_daemon_status(), name="poll_daemon_startup")

        if self.open_dropzone or self.initial_drop_paths:
            launch_dest = self.initial_dest_dir
            self.initial_dest_dir = None
            self.action_open_dropzone(
                initial_paths=self.initial_drop_paths,
                initial_dest_dir=launch_dest,
                force=True,
            )

        env_non_interactive = os.environ.get("NON_INTERACTIVE")
        is_non_interactive_env = bool(
            env_non_interactive
            and env_non_interactive.strip().lower() in ("1", "true", "yes", "on")
        )
        env_consent = os.environ.get("SORTIFY_AI_CONSENT")
        if env_consent is not None:
            env_consent_clean = env_consent.strip().lower()
            if env_consent_clean in ("1", "true", "yes", "on"):
                self.settings.AI_CONSENT_GRANTED = True
            elif env_consent_clean in ("0", "false", "no", "off"):
                self.settings.AI_CONSENT_GRANTED = False

        is_bypass = (
            self.skip_wizard
            or self.non_interactive
            or getattr(self.settings, "_skip_wizard", False)
            or getattr(self.settings, "_non_interactive", False)
            or is_non_interactive_env
        )

        _unset = object()
        if getattr(self.settings, "AI_CONSENT_GRANTED", _unset) is None:
            if is_bypass:
                self.settings.AI_CONSENT_GRANTED = False
                if hasattr(self.settings, "_save"):
                    try:
                        self.settings._save()
                    except Exception:
                        pass
            elif not getattr(
                self, "_wizard_dismissed_this_session", False
            ) and not self._has_file_nodes(self.plan):

                def _auto_open_wizard() -> None:
                    if (
                        isinstance(self.screen, ModalScreen)
                        or len(self.screen_stack) > 1
                        or self._has_file_nodes(self.plan)
                    ):
                        return
                    self.action_open_wizard()

                self.call_after_refresh(_auto_open_wizard)

    def on_unmount(self) -> None:
        """Lifecycle hook called when application is unmounted."""
        try:
            from app.ui.notifications import NotificationManager

            NotificationManager.get_instance().unregister_tui(self)
        except Exception:
            pass
        try:
            from app.config import AppSettings

            AppSettings.remove_observer(
                "AI_CONSENT_GRANTED", self._on_ai_consent_changed
            )
        except Exception:
            pass

    @work
    async def check_abandoned_sessions(self) -> None:
        """Scan for abandoned sessions on startup and prompt for recovery if detected."""
        try:
            import asyncio

            from app.core.session_catalog import find_abandoned_sessions

            abandoned = await asyncio.to_thread(find_abandoned_sessions)
            if not abandoned:
                return

            if len(abandoned) == 1:
                session_info = abandoned[0]

                def on_recovery_choice(choice: str | None) -> None:
                    if not choice:
                        return
                    if choice == "resume":
                        self._do_recovery_resume(session_info)
                    elif choice == "rollback":
                        self._do_recovery_rollback(session_info)
                    elif choice == "clean":
                        self._do_recovery_clean(session_info)

                self.push_screen(SessionRecoveryModal(session_info), on_recovery_choice)
            else:

                def on_multi_recovery_choice(choice: Any) -> None:
                    if not choice:
                        return
                    action = getattr(choice, "action", choice)
                    target_session = getattr(choice, "session", None)
                    if isinstance(choice, dict):
                        action = choice.get("action")
                        target_session = choice.get("session")

                    if action == "clean_all":
                        sessions_to_clean = getattr(choice, "sessions", abandoned)
                        for sess in sessions_to_clean:
                            self._do_recovery_clean(sess)
                    elif action == "rollback_all":
                        sessions_to_rollback = getattr(choice, "sessions", abandoned)
                        for sess in sessions_to_rollback:
                            self._do_recovery_rollback(sess)
                        if self.base_dir:
                            self.action_scan_directory()
                            self.rebuild_tree()
                    elif action == "resume" and target_session:
                        self._do_recovery_resume(target_session)
                    elif action == "rollback" and target_session:
                        self._do_recovery_rollback(target_session)
                    elif action == "clean" and target_session:
                        self._do_recovery_clean(target_session)

                self.push_screen(
                    MultiSessionRecoveryModal(abandoned, settings=self.settings),
                    on_multi_recovery_choice,
                )
        except Exception as e:
            logger.error(f"Error checking abandoned sessions: {e}")

    def _do_recovery_resume(self, session_info: dict[str, Any]) -> None:
        """Resume interrupted sorting operation under the original session_id."""
        import json

        from app.core.session import AppSession

        if (
            session_info.get("can_resume") is False
            or session_info.get("recovery_kind") == "incomplete_undo"
        ):
            conflict_note = session_info.get("conflict_summary") or (
                "Incomplete undo left conflicted or modified files in place."
            )
            self.announce(
                f"Cannot resume session '{session_info.get('session_id')}': {conflict_note} "
                "Choose Rollback or Clean instead."
            )
            return

        base_dir = session_info.get("base_dir") or self.base_dir
        if base_dir:
            self.base_dir = base_dir
            if not getattr(self, "source_dirs", None):
                self.source_dirs = [base_dir]

        self.app_session = AppSession(
            self.settings, self.base_dir, session_id=session_info.get("session_id")
        )

        plan_path = session_info.get("plan_path")
        if not plan_path and session_info.get("session_dir"):
            candidate = os.path.join(str(session_info["session_dir"]), "plan.json")
            if os.path.exists(candidate):
                plan_path = candidate

        if plan_path and os.path.exists(plan_path):
            try:
                with open(plan_path, encoding="utf-8") as f:
                    self.plan = json.load(f)
            except Exception:
                self.plan = self.app_session.generate_sorting_plan()
        else:
            self.plan = self.app_session.generate_sorting_plan()

        self.rebuild_tree()
        self.announce(
            f"Resuming session '{session_info.get('session_id')}'. Executing pending moves..."
        )
        self._pending_resume = True
        self.action_execute_sort()

    def _do_recovery_rollback(self, session_info: dict[str, Any]) -> bool:
        """Rollback interrupted sorting operation."""
        from app.core.session_catalog import roll_back_abandoned_session

        session_id = session_info.get("session_id")
        info = {
            **session_info,
            "base_dir": session_info.get("base_dir") or self.base_dir,
        }
        succeeded = bool(roll_back_abandoned_session(self.settings, info))
        if succeeded:
            self.announce(f"Rolled back session '{session_id}'.")
        else:
            self.announce(
                f"Session recovery failed for '{session_id}': write/permission error. Session files and safety storage preserved."
            )

        if self.base_dir:
            self.action_scan_directory()
        return succeeded

    def _do_recovery_clean(self, session_info: dict[str, Any]) -> None:
        """Leave an abandoned session as it is and stop offering to recover it."""
        from app.core.session_catalog import forget_abandoned_session

        forget_abandoned_session(session_info)
        self.announce(f"Cleaned session files for '{session_info.get('session_id')}'.")

    def _get_daemon_status_badge(self) -> str:
        """Return visual watchdog daemon status badge string."""
        state = getattr(self, "_daemon_state", "idle")
        if state == "active":
            return "[Daemon: Active]"
        elif state == "paused":
            return "[Daemon: Paused]"
        return "[Daemon: Idle]"

    async def _poll_daemon_status(self) -> None:
        """Asynchronously poll background daemon lockfile and query IPC status."""
        base_dir = getattr(self, "base_dir", None)
        new_state = "idle"
        is_moving = False
        if base_dir and os.path.exists(base_dir):
            try:
                import asyncio

                from app.core.ipc import (
                    DaemonIPCClient,
                    is_process_alive,
                    read_pid_file,
                )

                pid_info = await asyncio.to_thread(read_pid_file, base_dir)
                if pid_info and is_process_alive(pid_info.get("pid", 0)):
                    client = DaemonIPCClient(base_dir)
                    res = await client.send_command("status", timeout=1.0)
                    if res.get("is_paused") is True or res.get("status") == "paused":
                        new_state = "paused"
                    elif (
                        res.get("is_running") is True or res.get("status") == "running"
                    ):
                        new_state = "active"
                    else:
                        new_state = "idle"
                    is_moving = bool(res.get("is_moving", False))
            except Exception as e:
                logger.debug(f"Daemon IPC polling error: {e}")
                new_state = "idle"
                is_moving = False

        self._daemon_is_moving = is_moving
        prev_state = getattr(self, "_daemon_state", "idle")
        self._daemon_state = new_state

        if not getattr(self, "_daemon_initialized", False):
            self._daemon_initialized = True
            self.update_status()
            if new_state == "active":
                self.announce("Watchdog daemon active.", priority="assertive")
            elif new_state == "paused":
                self.announce("Watchdog daemon paused.", priority="assertive")
        elif prev_state != new_state:
            self.update_status()
            if new_state == "active":
                self.announce("Watchdog daemon resumed.", priority="assertive")
            elif new_state == "paused":
                self.announce("Watchdog daemon paused.", priority="assertive")
            elif new_state == "idle":
                self.announce("Watchdog daemon idle.", priority="assertive")

    def _compute_ai_poll_token(self) -> tuple[Any, ...]:
        """Build an in-memory token of consent, ONNX readiness, and DownloadManager state without disk stat calls."""
        from app.ui.ai_runtime import compute_ai_poll_token

        return compute_ai_poll_token(self)

    def _should_auto_rescan_mock_session(self) -> bool:
        """Return True if an unedited mock/fallback plan can be safely upgraded with active AI embeddings."""
        from app.ui.ai_runtime import should_auto_rescan_mock_session

        return should_auto_rescan_mock_session(self)

    def _trigger_ai_active_rescan_if_eligible(self) -> None:
        """Re-scan an unedited mock session when verified AI weights and ONNX Runtime are active."""
        from app.ui.ai_runtime import trigger_ai_active_rescan_if_eligible

        trigger_ai_active_rescan_if_eligible(self)

    def _get_ai_status_badge(self) -> str:
        """Return visual AI runtime status badge distinguishing active, downloading, fallback, and disabled."""
        from app.core.downloader import get_ai_runtime_state

        runtime_state = get_ai_runtime_state(self.settings)
        badge = str(runtime_state["badge"])
        self._last_ai_state = str(runtime_state["state"])
        self._last_ai_badge = badge
        self._last_ai_poll_token = self._compute_ai_poll_token()
        return badge

    def _poll_ai_provisioning_status(self) -> None:
        """Poll background model download and verification state to refresh status bar badges."""
        try:
            from app.ui.ai_runtime import poll_ai_provisioning_status

            poll_ai_provisioning_status(self)
        except Exception as exc:
            logger.debug(f"AI provisioning status poll error: {exc}")

    def _on_ai_consent_changed(self, value: Any = None) -> None:
        """Handle AI_CONSENT_GRANTED setting change notification."""
        self.update_status()
        consent_val = (
            value
            if value is not None
            else getattr(self.settings, "AI_CONSENT_GRANTED", None)
        )
        if consent_val is False or consent_val is None:
            try:
                from app.core.shared_registry import SharedModelRegistry

                SharedModelRegistry.get_instance().unload_all_models()
            except Exception as exc:
                logger.warning(
                    "Failed to unload in-memory AI models after consent revocation: %s",
                    exc,
                    exc_info=True,
                )
                err_msg = (
                    "AI processing disabled, but failed to unload in-memory AI models: "
                    f"{exc}"
                )
                self.announce(err_msg, priority="assertive")
                if hasattr(self, "notify"):
                    self.notify(err_msg, severity="error")
            else:
                self.announce(
                    "AI processing disabled. In-memory AI models unloaded instantly.",
                    priority="high",
                )
        elif consent_val is True:
            self.announce("AI processing enabled.", priority="high")

    def _on_character_shortcuts_changed(self, value: Any = None) -> None:
        """Handle ENABLE_CHARACTER_KEY_SHORTCUTS setting change notification."""
        self.update_status()
        try:
            self.refresh_bindings()
        except Exception:
            pass

    def update_status(self, text: str | None = None) -> None:
        """Update status bar label with current message, truthful AI badge, and daemon badge."""
        try:
            if text is not None:
                import re

                clean_text = str(text)
                clean_text = re.sub(r"^\[AI:[^\]]+\]\s*", "", clean_text)
                for badge_str in (
                    "[Daemon: Active]",
                    "[Daemon: Paused]",
                    "[Daemon: Idle]",
                ):
                    if clean_text.startswith(badge_str):
                        clean_text = clean_text[len(badge_str) :].lstrip()
                self._current_status_text = clean_text
            elif not hasattr(self, "_current_status_text"):
                self._current_status_text = (
                    "Ready. Press [Ctrl+S] to Scan or [Ctrl+B] to select Directory."
                )

            ai_badge = self._get_ai_status_badge()
            self._last_ai_badge = ai_badge
            daemon_badge = self._get_daemon_status_badge()
            badges = f"{ai_badge} {daemon_badge}"
            full_text = (
                f"{badges} {self._current_status_text}"
                if getattr(self, "_current_status_text", "")
                else badges
            )
            sb = self.query_one("#status-bar", Static)
            sb.update(full_text)
        except Exception:
            pass

    def _update_onboarding_cta_visibility(self) -> None:
        """Update visibility of onboarding CTA card vs metadata inspectors based on workspace state."""
        try:
            cta_card = self.query_one("#onboarding-cta-card")
            inspector = self.query_one("#inspector-container")
            ws_state = self.query_one("#onboarding-workspace-state", Static)

            base_dir = getattr(self, "base_dir", "")
            base_dir_text = base_dir if base_dir else "No directory selected"
            ws_state.update(f"Active Workspace: {base_dir_text}")

            current_plan = getattr(self, "plan", {})
            has_plan_files = self._has_file_nodes(
                current_plan
            ) or self._has_folder_nodes(current_plan)
            active_node = getattr(self, "active_tree_node", None)
            has_selected_real_node = False
            if active_node and getattr(active_node, "data", None):
                data = active_node.data
                if isinstance(data, dict) and not data.get("is_empty_state"):
                    has_selected_real_node = True

            show_cta = not has_plan_files and not has_selected_real_node
            cta_card.display = show_cta
            inspector.display = not show_cta
        except Exception as e:
            logger.debug(f"Error updating onboarding CTA visibility: {e}")

    def _get_active_node(self) -> TreeNode[Any] | None:
        try:
            tree = self.query_one("#plan-tree", Tree)
            if tree.cursor_node and tree.cursor_node.data:
                return tree.cursor_node
            active_node = getattr(self, "active_tree_node", None)
            if active_node is not None and active_node.data:
                return active_node
        except Exception:
            pass
        return None

    def _clear_manual_plan_edits(self) -> None:
        """Clear cached manual plan edits across workspace switches, sorts, and rollbacks."""
        self._manual_plan_edits.clear()
        self._manual_empty_folders.clear()
        self.selected_paths.clear()
        self.excluded_paths.clear()

    def _is_text_control_focused(self, allow_tree_search: bool = False) -> bool:
        """Check if a text input or selection control currently holds focus."""
        _ = allow_tree_search
        focused = self.focused
        if focused is None or not isinstance(focused, (Input, Select)):
            return False
        if getattr(focused, "id", None) == "palette-input":
            return False
        return True

    def _tree_has_focus(self) -> bool:
        """Return True if the plan tree widget currently holds active focus."""
        try:
            tree = self.query_one("#plan-tree", Tree)
            return bool(tree.has_focus)
        except Exception:
            return False

    def check_action(self, action: str, parameters: tuple[object, ...]) -> bool | None:
        """Check whether an action is enabled before dispatching key bindings."""
        focused = self.focused
        if action == "open_command_palette":
            if isinstance(self.screen, CommandPaletteModal):
                return False
            if (
                getattr(focused, "id", None) != "tree-search-input"
                and self._is_text_control_focused()
            ):
                return False

        if getattr(focused, "id", None) == "tree-search-input":
            if action in {
                "open_command_palette",
                "toggle_character_shortcuts",
                "focus_search",
                "quit",
            }:
                return super().check_action(action, parameters)
            if action == "open_cheat_sheet" and not (
                parameters and parameters[0] is True
            ):
                return super().check_action(action, parameters)
            return False

        is_char_action = action in {
            "toggle_selection",
            "exclude_selected",
            "include_selected",
            "reassign_selected",
            "visual_range_select",
            "toggle_select_all",
            "rate_positive",
            "rate_negative",
            "generate_sample_corpus",
        }
        if action in {"toggle_daemon", "scan_subfolders"} and (
            parameters and parameters[0] is True
        ):
            is_char_action = True

        if is_char_action:
            if not self._tree_has_focus() or not self._character_shortcuts_enabled():
                return False

        if action == "open_cheat_sheet" and parameters and parameters[0] is True:
            if not self._character_shortcuts_enabled():
                return False

        return super().check_action(action, parameters)

    # --- Actions ---

    def get_active_settings(self, *, fallback_to_global: bool = True) -> Any:
        """Return a folder-scoped settings view for ``base_dir`` when selected."""
        from app.config import resolve_scoped_settings

        if getattr(self, "base_dir", None):
            return resolve_scoped_settings(
                self.settings,
                self.base_dir,
                fallback_to_global=fallback_to_global,
            )
        return self.settings

    def _describe_manual_modifications(self) -> str:
        """Build a short human-readable summary of unsaved manual edits, folders, or locks."""
        parts: list[str] = []
        n_locks = len(getattr(self, "locked_files", {}) or {})
        if n_locks:
            parts.append(f"{n_locks} locked {'file' if n_locks == 1 else 'files'}")
        n_edits = len(getattr(self, "_manual_plan_edits", {}) or {})
        if n_edits:
            parts.append(f"{n_edits} manual plan {'edit' if n_edits == 1 else 'edits'}")
        n_folders = len(getattr(self, "_manual_empty_folders", set()) or set())
        if n_folders:
            parts.append(
                f"{n_folders} manual {'folder' if n_folders == 1 else 'folders'}"
            )
        if not parts:
            return "unsaved manual plan modifications"
        return ", ".join(parts)

    def _apply_selected_workspace(
        self, valid_paths: list[str], prev_sources: list[str]
    ) -> None:
        """Apply confirmed workspace roots, resetting per-workspace state when roots change."""
        if valid_paths != prev_sources:
            self.locked_files.clear()
            self._ratings_cache.clear()
            self._clear_manual_plan_edits()
            self.has_critical_errors = False
            self.verification_result = {}
            self.critical_error_paths.clear()
            self.warning_paths.clear()
            self.collision_paths.clear()
        self.source_dirs = valid_paths
        self.base_dir = valid_paths[0]
        self._active_folder_settings = self.get_active_settings()
        self._update_onboarding_cta_visibility()
        self.update_status()
        self.run_worker(self._poll_daemon_status(), name="poll_daemon_on_dir_select")
        msg = f"Selected directory: {', '.join(self.source_dirs)}"
        self.announce(msg)
        self.action_scan_directory()

    def action_select_dir(self) -> None:
        """Open directory selection modal."""
        if self._is_text_control_focused(allow_tree_search=True):
            return

        def on_selected(path: str | list[str] | None) -> None:
            if not path:
                return
            paths = [path] if isinstance(path, str) else list(path)
            valid_paths = [os.path.abspath(p) for p in paths if p and os.path.exists(p)]
            if valid_paths:
                from app.ui.ai_runtime import plan_has_manual_modifications

                prev_sources = [
                    os.path.abspath(p) for p in getattr(self, "source_dirs", []) if p
                ]
                if (
                    valid_paths != prev_sources
                    and not getattr(self, "non_interactive", False)
                    and plan_has_manual_modifications(self)
                ):
                    summary = self._describe_manual_modifications()

                    def _on_confirm_switch(confirmed: bool | None) -> None:
                        if confirmed is True:
                            self._apply_selected_workspace(valid_paths, prev_sources)

                    self.push_screen(
                        UnsavedWorkspaceSwitchModal(
                            new_sources=valid_paths,
                            modification_summary=summary,
                        ),
                        _on_confirm_switch,
                    )
                    return

                self._apply_selected_workspace(valid_paths, prev_sources)
            else:
                from app.ui.notifications import notify

                err_msg = f"Target directory does not exist: {path}"
                self.announce(err_msg, priority="assertive")
                notify(err_msg, type="error")

        self.push_screen(
            DirectorySelectModal(
                current_dir=self.base_dir,
                source_dirs=getattr(self, "source_dirs", None),
                settings=self.settings,
            ),
            on_selected,
        )

    async def action_toggle_daemon(self, from_character: bool = False) -> None:
        """Toggle watchdog daemon pause / resume state."""
        if from_character:
            if not self._tree_has_focus() or not self._character_shortcuts_enabled():
                return
        if self._is_text_control_focused(allow_tree_search=True):
            return

        base_dir = getattr(self, "base_dir", None)
        if not base_dir or not os.path.exists(base_dir):
            msg = "No workspace folder selected for daemon monitoring."
            self.announce(msg, priority="assertive")
            if hasattr(self, "notify"):
                self.notify(msg, severity="warning")
            return

        from app.core.ipc import DaemonIPCClient, is_process_alive, read_pid_file

        pid_info = await asyncio.to_thread(read_pid_file, base_dir)
        if not pid_info or not is_process_alive(pid_info.get("pid", 0)):
            self._daemon_state = "idle"
            self.update_status()
            msg = "No background watchdog daemon is running for this workspace."
            self.announce(msg, priority="assertive")
            if hasattr(self, "notify"):
                self.notify(msg, severity="warning")
            return

        client = DaemonIPCClient(base_dir)
        try:
            current_state = getattr(self, "_daemon_state", "idle")
            if current_state == "paused":
                await client.send_command("resume", timeout=2.0)
                self._daemon_state = "active"
                self.update_status()
                msg = "Watchdog daemon resumed."
                self.announce(msg, priority="assertive")
                if hasattr(self, "notify"):
                    self.notify(msg)
            elif current_state == "active":
                await client.send_command("pause", timeout=2.0)
                self._daemon_state = "paused"
                self.update_status()
                msg = "Watchdog daemon paused."
                self.announce(msg, priority="assertive")
                if hasattr(self, "notify"):
                    self.notify(msg)
            else:
                status_res = await client.send_command("status", timeout=2.0)
                if (
                    status_res.get("is_paused") is True
                    or status_res.get("status") == "paused"
                ):
                    await client.send_command("resume", timeout=2.0)
                    self._daemon_state = "active"
                    self.update_status()
                    msg = "Watchdog daemon resumed."
                    self.announce(msg, priority="assertive")
                    if hasattr(self, "notify"):
                        self.notify(msg)
                else:
                    await client.send_command("pause", timeout=2.0)
                    self._daemon_state = "paused"
                    self.update_status()
                    msg = "Watchdog daemon paused."
                    self.announce(msg, priority="assertive")
                    if hasattr(self, "notify"):
                        self.notify(msg)
        except Exception as e:
            logger.warning(f"Failed to communicate with daemon: {e}")
            err_msg = f"Failed to communicate with daemon: {e}"
            self.announce(err_msg, priority="assertive")
            if hasattr(self, "notify"):
                self.notify(err_msg, severity="error")

    def action_generate_sample_corpus(self, open_modal: bool = False) -> None:
        """Generate sample document corpus in active workspace directory, or launch interactive playground modal."""
        if self._is_text_control_focused():
            return

        target_dir = self._sample_dataset_dir(self.base_dir or os.getcwd())

        if open_modal:
            from app.ui.modals.sample_playground import SamplePlaygroundModal

            self.push_screen(
                SamplePlaygroundModal(self.settings, target_dir=target_dir)
            )
            return

        from app.core.sample_corpus import generate_sample_corpus

        try:
            try:
                generate_sample_corpus(target_dir, overwrite=False)
                self.announce(f"Generated sample dataset in {target_dir}.")
            except FileExistsError:
                self.announce(f"Using the existing sample dataset in {target_dir}.")
        except Exception as exc:
            logger.error(f"Error generating sample dataset: {exc}")
            self.announce(f"Failed to generate sample dataset: {exc}")
            return
        if os.path.abspath(target_dir) != os.path.abspath(self.base_dir or ""):
            self._clear_manual_plan_edits()
        self.base_dir = target_dir
        self.source_dirs = [target_dir]
        self.action_scan_directory()

    SAMPLE_DATASET_DIRNAME = "sortify-sample-dataset"

    def _sample_dataset_dir(self, folder: str) -> str:
        """Pick where [G] writes sample files without mixing them into user files.

        An empty folder (or the sample folder itself) is used as is; any other
        folder gets a dedicated ``sortify-sample-dataset`` subfolder.
        """
        if os.path.basename(os.path.normpath(folder)) == self.SAMPLE_DATASET_DIRNAME:
            return folder
        try:
            with os.scandir(folder) as entries:
                is_empty = not any(entries)
        except FileNotFoundError:
            is_empty = True
        return folder if is_empty else os.path.join(folder, self.SAMPLE_DATASET_DIRNAME)

    def action_open_settings(self) -> None:
        """Open settings modal screen."""
        if self._is_text_control_focused(allow_tree_search=True):
            return

        def on_saved(res: dict[str, Any] | None) -> None:
            if not res:
                return
            import copy

            from pydantic import ValidationError

            settings_keys = (
                "PROTECTED_PATHS",
                "IGNORED_EXTENSIONS",
                "MAX_WORKERS",
                "MAX_FOLDERS",
                "SORTING_STRATEGY",
                "AI_ASSISTED_NAMING",
                "CLINICAL_SMART_RENAMING",
                "CONTEXTUAL_RENAMING",
                "SPEAK_ANNOUNCEMENTS",
                "ENABLE_CHARACTER_KEY_SHORTCUTS",
                "PDF_TEXT_DENSITY_THRESHOLD",
                "CONFLICT_POLICY",
                "DUPLICATE_ACTION",
                "DETECT_ORIGINAL_BY",
                "CLEANUP_EMPTY_FOLDERS",
                "PRESERVE_HIERARCHY",
                "SCAN_MAX_DEPTH",
                "AUTO_QUARANTINE_RATINGS",
                "QUARANTINE_DIR_NAME",
                "RENAME_PATTERN",
                "AI_CONSENT_GRANTED",
            )
            settings_obj: Any = self.settings
            prior_values: dict[str, Any] = {
                key: copy.deepcopy(getattr(settings_obj, key))
                for key in settings_keys
                if key in res and hasattr(settings_obj, key)
            }
            had_save_timer = getattr(settings_obj, "_save_timer", None) is not None
            prior_transient = copy.deepcopy(
                getattr(settings_obj, "_transient_values", None)
            )
            prior_env_keys = (
                set(getattr(settings_obj, "_env_sourced_keys", ()))
                if hasattr(settings_obj, "_env_sourced_keys")
                else None
            )
            prior_has_val_errors = getattr(
                settings_obj, "_has_validation_errors", False
            )
            prior_val_errors = copy.deepcopy(
                getattr(settings_obj, "_validation_errors", None)
            )

            validation_errors: list[str] = []
            model_obj = getattr(settings_obj, "_settings_model", None)
            if model_obj is not None and hasattr(model_obj, "model_copy"):
                candidate_model = model_obj.model_copy(deep=True)
                for key in settings_keys:
                    if key not in res or not hasattr(candidate_model, key):
                        continue
                    try:
                        setattr(candidate_model, key, res[key])
                    except ValidationError as exc:
                        logger.warning(
                            "Settings validation failed for %s: %s",
                            key,
                            exc,
                            exc_info=True,
                        )
                        first_err = (
                            exc.errors()[0].get("msg", str(exc))
                            if exc.errors()
                            else str(exc)
                        )
                        validation_errors.append(f"{key}: {first_err}")
                    except ValueError as exc:
                        logger.warning(
                            "Settings validation failed for %s: %s",
                            key,
                            exc,
                            exc_info=True,
                        )
                        validation_errors.append(f"{key}: {exc}")

            applied_keys: list[str] = []
            if not validation_errors:
                for key in settings_keys:
                    if key not in res:
                        continue
                    if (
                        key == "AI_CONSENT_GRANTED"
                        and validation_errors
                        and isinstance(res[key], bool)
                    ):
                        continue
                    try:
                        setattr(self.settings, key, res[key])
                        applied_keys.append(key)
                    except ValidationError as exc:
                        logger.warning(
                            "Settings validation failed for %s: %s",
                            key,
                            exc,
                            exc_info=True,
                        )
                        first_err = (
                            exc.errors()[0].get("msg", str(exc))
                            if exc.errors()
                            else str(exc)
                        )
                        validation_errors.append(f"{key}: {first_err}")
                    except ValueError as exc:
                        logger.warning(
                            "Settings validation failed for %s: %s",
                            key,
                            exc,
                            exc_info=True,
                        )
                        validation_errors.append(f"{key}: {exc}")

            if validation_errors:
                notify_fn = getattr(settings_obj, "_notify_observers", None)
                for key in reversed(applied_keys):
                    if key not in prior_values:
                        continue
                    if model_obj is not None and hasattr(model_obj, key):
                        cur_val = getattr(model_obj, key, None)
                        setattr(model_obj, key, prior_values[key])
                        if cur_val != prior_values[key] and callable(notify_fn):
                            notify_fn(key, prior_values[key])
                    else:
                        setattr(self.settings, key, prior_values[key])

                if prior_transient is not None and hasattr(
                    settings_obj, "_transient_values"
                ):
                    settings_obj._transient_values = prior_transient
                if prior_env_keys is not None and hasattr(
                    settings_obj, "_env_sourced_keys"
                ):
                    settings_obj._env_sourced_keys = prior_env_keys
                if hasattr(settings_obj, "_has_validation_errors"):
                    settings_obj._has_validation_errors = prior_has_val_errors
                if prior_val_errors is not None and hasattr(
                    settings_obj, "_validation_errors"
                ):
                    settings_obj._validation_errors = prior_val_errors
                if not had_save_timer:
                    pending_timer = getattr(settings_obj, "_save_timer", None)
                    if pending_timer is not None:
                        pending_timer.cancel()
                        settings_obj._save_timer = None
                    cancel_fn = getattr(settings_obj, "_cancel_file_timer", None)
                    filepath_val = getattr(settings_obj, "_filepath", None)
                    if callable(cancel_fn) and isinstance(filepath_val, str):
                        cancel_fn(filepath_val)

                err_msg = f"Settings error: Failed to save settings ({'; '.join(validation_errors)})."
                self.update_status()
                self.announce(err_msg, priority="assertive")
                if hasattr(self, "notify"):
                    self.notify(err_msg, severity="error")
                return

            if hasattr(self.settings, "_save"):
                self.settings._save()
            self.update_status()
            self.announce("Settings updated and saved.")
            if self.base_dir:
                self.action_scan_directory()

        self.push_screen(SettingsModal(self.settings), on_saved)

    def action_open_extraction_preview(self) -> None:
        """Open document extraction preview modal for active or selected supported file [Ctrl+X]."""
        if self._is_text_control_focused(allow_tree_search=True):
            return

        from app.core.extractor_strategies import registry

        def _resolve_supported_path(
            raw_fp: Any, src_root: str | None = None
        ) -> str | None:
            if not raw_fp:
                return None
            fp_str = str(raw_fp)
            if "::" in fp_str and not os.path.exists(fp_str):
                s_root, rel_part = fp_str.split("::", 1)
                fp_str = os.path.join(s_root, rel_part)
            ext = os.path.splitext(fp_str)[1].lower()
            if not ext or not registry.is_supported(ext):
                return None
            if not os.path.isabs(fp_str):
                eff_root = src_root or self.base_dir
                if eff_root:
                    cand = os.path.join(eff_root, fp_str)
                    if os.path.exists(cand):
                        return cand
            return fp_str

        preview_path: str | None = None

        active_node = self._get_active_node()
        if active_node and active_node.data:
            data = active_node.data
            if data.get("is_file"):
                info_dict = (
                    data.get("info") if isinstance(data.get("info"), dict) else {}
                )
                fp = (
                    data.get("filepath")
                    or info_dict.get("src_path")
                    or info_dict.get("path")
                    or info_dict.get("source_path")
                    or data.get("key")
                )
                preview_path = _resolve_supported_path(
                    fp, src_root=info_dict.get("source_root")
                )

        if not preview_path:
            target_files = self._get_target_file_infos()
            for tf in target_files:
                fp = (
                    tf.get("src_path")
                    or tf.get("path")
                    or tf.get("filepath")
                    or tf.get("source_path")
                )
                resolved = _resolve_supported_path(fp, src_root=tf.get("source_root"))
                if resolved:
                    preview_path = resolved
                    break

        if not preview_path:
            self.announce(
                "Please select a supported document to preview extracted text [Ctrl+X]."
            )
            return

        def on_preview_closed(saved_val: int | None) -> None:
            if saved_val is not None:
                self.announce(f"Updated extraction density threshold to {saved_val}.")

        self.push_screen(
            ExtractionPreviewModal(
                preview_path,
                self.settings,
                db=self.db,
                base_dir=self.base_dir,
            ),
            on_preview_closed,
        )

    def action_open_command_palette(self) -> None:
        """Open command palette overlay modal [Ctrl+K]."""
        focused_id = getattr(self.focused, "id", None)
        if focused_id != "tree-search-input" and self._is_text_control_focused():
            return

        def on_command_selected(cmd: PaletteCommand | None) -> None:
            try:
                self.query_one("#plan-tree", Tree).focus()
            except Exception:
                pass
            if not cmd or not cmd.action_name:
                return
            handler = getattr(self, cmd.action_name, None)
            if callable(handler):
                if inspect.iscoroutinefunction(handler):
                    self.run_worker(handler())
                else:
                    res = handler()
                    if inspect.iscoroutine(res):
                        self.run_worker(res)
            else:
                self.announce(
                    f"Action '{cmd.action_name}' is not supported.",
                    priority="assertive",
                )

        self.push_screen(CommandPaletteModal(), on_command_selected)

    def action_open_active_rules(self) -> None:
        """Open active rule manager modal screen [Ctrl+R]."""
        if self._is_text_control_focused(allow_tree_search=True):
            return

        def on_rules_closed(mutated: bool | None = None) -> None:
            try:
                self.query_one("#plan-tree", Tree).focus()
            except Exception:
                pass
            if mutated:
                self.update_status()
                if self.base_dir:
                    self.action_scan_directory()

        self.push_screen(
            ActiveRuleManagerModal(self.get_active_settings()), on_rules_closed
        )

    def action_open_template_gallery(self) -> None:
        """Open starter rule template gallery modal screen."""
        if self._is_text_control_focused(allow_tree_search=True):
            return

        def on_gallery_closed(_res: Any = None) -> None:
            try:
                self.query_one("#plan-tree", Tree).focus()
            except Exception:
                pass

        self.push_screen(
            TemplateGalleryModal(self.get_active_settings()), on_gallery_closed
        )

    def action_export_rules(self) -> None:
        """Open active rule export modal screen."""
        if self._is_text_control_focused(allow_tree_search=True):
            return

        def on_export_closed(_res: Any = None) -> None:
            try:
                self.query_one("#plan-tree", Tree).focus()
            except Exception:
                pass

        self.push_screen(ExportRulesModal(self.get_active_settings()), on_export_closed)

    def action_import_rules(self) -> None:
        """Open external rule import modal screen."""
        if self._is_text_control_focused(allow_tree_search=True):
            return

        def on_import_closed(result: Any = None) -> None:
            if result is not None:
                self.update_status()
                if self.base_dir:
                    self.action_scan_directory()
            try:
                self.query_one("#plan-tree", Tree).focus()
            except Exception:
                pass

        self.push_screen(RuleImportModal(self.get_active_settings()), on_import_closed)

    action_browse_rule_templates = action_open_template_gallery
    action_open_export_rules = action_export_rules
    action_open_rule_import = action_import_rules
    action_open_import_rules = action_import_rules

    def action_open_model_manager(self) -> None:
        """Open model manager modal screen."""
        if self._is_text_control_focused(allow_tree_search=True):
            return
        self.push_screen(ModelManagerModal(self.settings))

    def action_open_wizard(self) -> None:
        """Open model onboarding wizard modal screen."""
        if self._is_text_control_focused(allow_tree_search=True):
            return
        if isinstance(self.screen, WizardModal):
            return
        self.push_screen(WizardModal(self.settings, current_dir=self.base_dir))

    def action_open_cro_forensic(self) -> None:
        """Open CRO multi-study forensic ingestion modal screen."""
        if self._is_text_control_focused(allow_tree_search=True):
            return
        from app.core.plugin_registry import PluginRegistry

        reg = PluginRegistry.get_instance()
        reg.load_plugins_from_settings(self.settings)
        view_cls = reg.get_tui_view("cro_forensic")
        if view_cls:
            self.push_screen(view_cls(self.settings, base_dir=self.base_dir))
        else:
            self.announce("CRO Forensic ingestion plugin is not enabled.")

    def action_open_cheat_sheet(self, from_character: bool | None = None) -> None:
        """Open keyboard shortcut cheat sheet modal screen."""
        if from_character is True:
            if (
                self._is_character_input_focused()
                or not self._character_shortcuts_enabled()
            ):
                return
        elif from_character is None:
            if self._is_text_control_focused(allow_tree_search=True):
                return
        if isinstance(self.screen, ShortcutCheatSheetModal):
            return
        self.push_screen(ShortcutCheatSheetModal())

    def action_toggle_character_shortcuts(self) -> None:
        """Toggle single-character keyboard shortcuts preference [Ctrl+Alt+K]."""
        current = self._character_shortcuts_enabled()
        new_val = not current
        self.settings.ENABLE_CHARACTER_KEY_SHORTCUTS = new_val
        if hasattr(self.settings, "_save"):
            self.settings._save()
        state_str = "enabled" if new_val else "disabled"
        self.announce(f"Character key shortcuts {state_str}.", priority="polite")
        self.update_status()
        try:
            self.refresh_bindings()
        except Exception:
            pass

    def action_open_dropzone(
        self,
        initial_paths: list[str] | None = None,
        force: bool = False,
        initial_dest_dir: str | None = None,
    ) -> None:
        """Open floating dropzone overlay modal screen."""
        if not force and self._is_text_control_focused(allow_tree_search=True):
            return

        def on_drop_done(res: dict[str, Any] | None) -> None:
            if res:
                if res.get("session_id"):
                    self._last_drop_session_id = str(res["session_id"])
                cnt = res.get("processed_count", 0)
                dest_used = res.get("destination_dir")
                if dest_used and not self.base_dir and os.path.isdir(dest_used):
                    self.base_dir = dest_used
                    if not self.source_dirs:
                        self.source_dirs = [dest_used]
                self.announce(f"DropZone triage finished: {cnt} item(s) organized.")
                scan_dir = dest_used or self.base_dir
                if scan_dir and os.path.exists(scan_dir) and self.base_dir:
                    if os.path.normcase(os.path.abspath(scan_dir)) == os.path.normcase(
                        os.path.abspath(self.base_dir)
                    ):
                        self.action_scan_directory()

        self.push_screen(
            DropZoneModal(
                settings=self.settings,
                base_dir=self.base_dir,
                initial_paths=initial_paths,
                initial_dest_dir=initial_dest_dir,
            ),
            on_drop_done,
        )

    def action_export_simulation_report(self) -> None:
        """Trigger dry-run simulation report export modal screen."""
        if self._is_text_control_focused(allow_tree_search=True):
            return
        if not self.plan or not self.base_dir:
            self.announce("No plan available to export. Run [Ctrl+S] Scan first.")
            return

        default_out = str(Path(self.base_dir) / "simulation_report.html")

        def handle_export_modal_result(result: tuple[str, str] | None) -> None:
            if not result:
                return
            export_path, report_format = result
            try:
                from app.core.simulation_exporter import SimulationExporter

                conflict_pol = str(
                    getattr(self.settings, "CONFLICT_POLICY", "skip") or "skip"
                )
                exporter = SimulationExporter(
                    self.plan,
                    self.base_dir,
                    conflict_policy=conflict_pol,
                )
                if report_format == "json":
                    exporter.export_json(export_path)
                else:
                    exporter.export_html(export_path)

                self.announce(f"Simulation report exported to '{export_path}'.")
            except Exception as e:
                logger.error(f"Error exporting simulation report: {e}")
                self.announce(f"Export error: {e}")

        self.push_screen(
            ExportReportModal(default_path=default_out, default_format="html"),
            handle_export_modal_result,
        )

    def action_export_report(self) -> None:
        """Alias for action_export_simulation_report."""
        self.action_export_simulation_report()

    def action_open_history(self) -> None:
        """Trigger session history view and audit log export modal screen."""
        if self._is_text_control_focused(allow_tree_search=True):
            return
        from app.core.session_catalog import list_sessions

        sessions = list_sessions()

        def handle_history_modal_result(result: dict[str, Any] | None) -> None:
            if not result:
                return
            session_id = result["session_id"]
            fmt = str(result.get("format") or "csv")
            output_path = str(result.get("output_path") or "").strip()
            if not output_path:
                from app.config import get_app_dir

                output_path = str(
                    Path(get_app_dir()) / "exports" / f"audit_log.{fmt.lower()}"
                )

            selected_base_dir: str | None = self.base_dir or None
            if not selected_base_dir and session_id not in ("none", "all"):
                for sess_item in sessions:
                    if sess_item.get("session_id") == session_id:
                        raw_bdir = sess_item.get("base_dir")
                        if raw_bdir:
                            selected_base_dir = str(raw_bdir)
                        break

            try:
                from app.core.services import acquire_services

                with acquire_services() as services:
                    export_res = services.history.export_audit_log(
                        output_path=output_path,
                        session_id=session_id
                        if session_id not in ("none", "all")
                        else None,
                        format=fmt,
                        base_dir=selected_base_dir,
                    )
                cnt = export_res.get("count", 0)
                out_p = export_res.get("output_path", output_path)
                msg = (
                    f"Audit log exported ({fmt.upper()}) to '{out_p}' ({cnt} records)."
                )
                self.announce(msg)
                from app.ui.notifications import notify

                notify(msg, type="info")
            except Exception as e:
                logger.error(f"Error exporting audit log from TUI: {e}")
                self.announce(f"Export error: {e}")
                from app.ui.notifications import notify

                notify(f"Export error: {e}", type="error")

        self.push_screen(
            HistoryModal(sessions=sessions, base_dir=self.base_dir),
            handle_history_modal_result,
        )

    def action_undo_last_sort(self) -> None:
        """Trigger instant undo rollback for the most recent completed sorting session."""
        if self._is_text_control_focused(allow_tree_search=True):
            return
        from app.core.session_catalog import has_remaining_undo_moves, list_sessions

        sessions = list_sessions()
        active_base = (
            os.path.normcase(os.path.normpath(os.path.abspath(self.base_dir)))
            if self.base_dir
            else ""
        )
        target_sess = None
        last_drop_sid = getattr(self, "_last_drop_session_id", None)
        for s in sessions:
            is_trash_only_completed = (
                str(s.get("status", "")).lower() == "completed"
                and int(s.get("step_count") or 0) <= 0
                and int(s.get("trashed_count") or 0) > 0
            )
            if not has_remaining_undo_moves(s) and not is_trash_only_completed:
                continue
            if last_drop_sid and s.get("session_id") == last_drop_sid:
                target_sess = s
                break
            if active_base:
                sess_base_raw = str(s.get("base_dir", "") or "")
                if not sess_base_raw:
                    continue
                sess_base = os.path.normcase(
                    os.path.normpath(os.path.abspath(sess_base_raw))
                )
                if sess_base != active_base:
                    continue
            target_sess = s
            break

        if not target_sess:
            self.announce("No completed sorting session available to undo.")
            return

        if (
            int(target_sess.get("step_count") or 0) <= 0
            and int(target_sess.get("trashed_count") or 0) > 0
        ):
            self.run_undo_worker(target_sess["session_id"])
            return

        def handle_confirm_result(result: dict[str, Any] | None) -> None:
            if not result or not result.get("confirmed"):
                return
            sid = result["session_id"]
            allow_missing = bool(
                result.get("allow_missing") or result.get("ignore_missing")
            )
            selected_step_ids = result.get("selected_step_ids")
            self.run_undo_worker(
                sid,
                ignore_missing=allow_missing,
                allow_missing=allow_missing,
                selected_step_ids=selected_step_ids,
            )

        self.push_screen(
            RollbackConfirmModal(session_info=target_sess),
            handle_confirm_result,
        )

    @work(thread=True, group="undo")
    def run_undo_worker(
        self,
        session_id: str,
        ignore_missing: bool = False,
        selected_step_ids: list[Any] | None = None,
        *,
        allow_missing: bool = False,
    ) -> None:
        """Execute session rollback restoration asynchronously in background worker thread."""
        try:
            from app.core.pipeline import SortPipeline

            effective_allow_missing = bool(allow_missing or ignore_missing)
            pipeline = self.pipeline
            if pipeline is None or pipeline.state.is_active:
                pipeline = SortPipeline(
                    self.app_session,
                    base_dir=self.base_dir,
                    settings=self.settings,
                )
                pipeline.add_state_change_hook(self._handle_pipeline_state_transition)
                pipeline.add_telemetry_hook(self._handle_pipeline_telemetry)
                self.pipeline = pipeline

            undo_result = pipeline.undo(
                session_id,
                ignore_missing=effective_allow_missing,
                allow_missing=effective_allow_missing,
                selected_step_ids=selected_step_ids,
            )
            if "error" in undo_result.summary:
                raise RuntimeError(str(undo_result.summary["error"]))
            restored_count = int(
                undo_result.summary.get("restored", len(undo_result.moved))
            )
            trashed_remaining = int(
                undo_result.summary.get("trashed_unrestorable")
                or len(undo_result.trashed)
                or 0
            )
            missing_count = (
                0
                if undo_result.rollback_completed
                else int(undo_result.summary.get("missing_count") or 0)
            )

            if hasattr(self, "call_from_thread"):
                self.call_from_thread(
                    self._on_undo_success,
                    session_id,
                    restored_count,
                    trashed_remaining,
                    missing_count,
                )
            else:
                self._on_undo_success(
                    session_id, restored_count, trashed_remaining, missing_count
                )
        except Exception as err:
            logger.error(f"Error rolling back session {session_id}: {err}")
            if hasattr(self, "call_from_thread"):
                self.call_from_thread(self._on_undo_failure, session_id, err)
            else:
                self._on_undo_failure(session_id, err)

    def _on_undo_success(
        self,
        session_id: str,
        restored_count: int,
        trashed_remaining: int = 0,
        missing_count: int = 0,
    ) -> None:
        """Handle successful session rollback completion on main thread."""
        from app.core.plan_format import format_session_rollback_outcome

        msg, notif_type = format_session_rollback_outcome(
            session_id,
            restored_count,
            trashed_remaining,
            missing_count=missing_count,
        )
        self.announce(msg)
        try:
            from app.ui.notifications import notify

            notify(msg, type=notif_type)
        except Exception:
            pass
        self._clear_manual_plan_edits()
        if not getattr(self, "source_dirs", None) and self.base_dir:
            self.source_dirs = [self.base_dir]
        if getattr(self, "source_dirs", None) and any(
            os.path.isdir(d) for d in self.source_dirs
        ):
            self._start_scan()

    def _on_undo_failure(self, session_id: str, err: Exception) -> None:
        """Handle session undo failure on main thread."""
        msg = f"Undo failed for session {session_id[:8]}...: {err}"
        self.announce(msg)
        try:
            from app.ui.notifications import notify

            notify(msg, type="error")
        except Exception:
            pass

        self.push_screen(
            RollbackErrorModal(
                title="Undo Failed",
                error_message=str(err),
                settings=self.settings,
            )
        )

    @on(Button.Pressed, "#btn-execute")
    def on_btn_execute_pressed(self) -> None:
        """Handle Execute Plan button press."""
        self.action_execute_sort()

    def action_open_audit_report(
        self, audit_report: dict[str, Any] | None = None
    ) -> None:
        """Open the Audit Report Modal Screen."""
        if not audit_report and self.app_session and self.plan:
            from app.core.audit_reporter import resolve_audit_report

            audit_report = resolve_audit_report(
                audit_report,
                self.app_session.base_dir or ".",
                self.plan,
            )

        if audit_report:
            self.push_screen(AuditReportModal(audit_report, session=self.app_session))
        else:
            self.announce(
                "No audit report available. Execute a sorting operation first."
            )

    def action_open_quarantine_vault(self) -> None:
        """Open the Quarantine Vault Modal Screen."""
        db = self.app_session.db if self.app_session else None
        base_dir = self.base_dir
        policies = (
            getattr(self.settings, "POLICIES", [])
            if hasattr(self, "settings") and self.settings
            else []
        )
        self.push_screen(
            QuarantineVaultModal(db=db, base_dir=base_dir, policies=policies)
        )

    @on(Button.Pressed, "#btn-cta-select-dir")
    def on_btn_cta_select_dir_pressed(self) -> None:
        """Handle Choose Directory CTA button press."""
        self.action_select_dir()

    @on(Button.Pressed, "#btn-cta-scan-dir")
    def on_btn_cta_scan_dir_pressed(self) -> None:
        """Handle Scan Directory CTA button press."""
        self.action_scan_directory()

    @on(Button.Pressed, "#btn-cta-sample-data")
    def on_btn_cta_sample_data_pressed(self) -> None:
        """Handle Load Sample Dataset CTA button press."""
        self.action_generate_sample_corpus()

    @on(Button.Pressed, "#btn-tree-invert-selection")
    def on_btn_tree_invert_selection_pressed(self) -> None:
        """Handle Invert Selection summary strip button press."""
        self.action_invert_selection()
        tree_matches = self.query("#plan-tree")
        if tree_matches:
            tree_matches.first(Tree).focus()

    @on(Button.Pressed, "#btn-tree-collapse-all")
    def on_btn_tree_collapse_all_pressed(self) -> None:
        """Handle Collapse All summary strip button press."""
        self.action_collapse_all()
        tree_matches = self.query("#plan-tree")
        if tree_matches:
            tree_matches.first(Tree).focus()

    @on(Button.Pressed, "#btn-tree-expand-all")
    def on_btn_tree_expand_all_pressed(self) -> None:
        """Handle Expand All summary strip button press."""
        self.action_expand_all()
        tree_matches = self.query("#plan-tree")
        if tree_matches:
            tree_matches.first(Tree).focus()

    # --- Tree Management & Event Handlers ---

    @on(Tree.NodeHighlighted, "#plan-tree")
    @on(Tree.NodeSelected, "#plan-tree")
    def on_node_selected(self, event: Tree.NodeSelected | Tree.NodeHighlighted) -> None:
        """Handle tree node selection or highlight to update metadata pane and screen reader announcement."""
        self.active_tree_node = event.node
        if event.node and getattr(event.node, "data", None):
            cdata = event.node.data
            if isinstance(cdata, dict):
                key = cdata.get("filepath") or cdata.get("folder") or cdata.get("key")
                if key:
                    self._last_cursor_key = key
        self._update_inspector(event.node)
        self._update_onboarding_cta_visibility()
        if isinstance(event, Tree.NodeSelected) and event.node and event.node.data:
            if event.node.data.get("is_empty_state"):
                action = event.node.data.get("action")
                if action == "generate_sample_corpus":
                    self.action_generate_sample_corpus()
                elif action == "scan_subfolders":
                    self.action_scan_subfolders()
                elif action == "open_settings":
                    self.action_open_settings()
                elif action == "select_dir":
                    self.action_select_dir()

    @on(Tree.NodeExpanded, "#plan-tree")
    @on(Tree.NodeCollapsed, "#plan-tree")
    def on_tree_node_expansion_changed(
        self, event: Tree.NodeExpanded | Tree.NodeCollapsed
    ) -> None:
        """Handle tree node expand/collapse to keep expansion state memory synchronized."""
        search_query = self._get_current_search_query()
        if not search_query and event.node and getattr(event.node, "data", None):
            cdata = event.node.data
            if isinstance(cdata, dict) and not cdata.get("is_file"):
                key = cdata.get("filepath") or cdata.get("folder") or cdata.get("key")
                if key:
                    if (
                        not hasattr(self, "_tree_expansion_memory")
                        or self._tree_expansion_memory is None
                    ):
                        self._tree_expansion_memory = {}
                    is_exp = isinstance(event, Tree.NodeExpanded)
                    self._tree_expansion_memory[key] = is_exp
                    if hasattr(
                        self, "_last_rendered_expansion_snapshot"
                    ) and isinstance(self._last_rendered_expansion_snapshot, dict):
                        self._last_rendered_expansion_snapshot[key] = is_exp

    @on(Input.Changed, "#tree-search-input")
    def on_tree_search_changed(self, event: Input.Changed) -> None:
        """Handle real-time search input field change to dynamically filter preview tree nodes."""
        schedule_tree_search_filter(self, event.value)

    @on(Input.Submitted, "#tree-search-input")
    def on_tree_search_submitted(self, event: Input.Submitted) -> None:
        """Move focus from ``#tree-search-input`` to ``#plan-tree`` on Enter while preserving filter."""
        event.stop()
        handoff_search_to_tree(self)

    def on_key(self, event: events.Key) -> None:
        """Handle global application key events."""
        try:
            if isinstance(self.screen, ModalScreen):
                return
            handle_search_and_tree_key(self, event)
        except Exception:
            pass

    def action_focus_search(self) -> None:
        """Focus the real-time tree filter search input bar."""
        try:
            inp = self.query_one("#tree-search-input", Input)
            inp.focus()
            inp.select_all()
            self.announce("Focused tree search input bar.")
        except Exception:
            pass

    # --- Checkbox Selection & Bulk Action Handlers ---

    # --- Keyboard Action Hotkeys ---

    async def action_quit(self) -> None:
        """Quit application [Ctrl+Q], from any focused widget."""
        await super().action_quit()

action_export_report()

Alias for action_export_simulation_report.

Source code in app/ui/tui.py
2186
2187
2188
def action_export_report(self) -> None:
    """Alias for action_export_simulation_report."""
    self.action_export_simulation_report()

action_export_rules()

Open active rule export modal screen.

Source code in app/ui/tui.py
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
def action_export_rules(self) -> None:
    """Open active rule export modal screen."""
    if self._is_text_control_focused(allow_tree_search=True):
        return

    def on_export_closed(_res: Any = None) -> None:
        try:
            self.query_one("#plan-tree", Tree).focus()
        except Exception:
            pass

    self.push_screen(ExportRulesModal(self.get_active_settings()), on_export_closed)

action_export_simulation_report()

Trigger dry-run simulation report export modal screen.

Source code in app/ui/tui.py
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
def action_export_simulation_report(self) -> None:
    """Trigger dry-run simulation report export modal screen."""
    if self._is_text_control_focused(allow_tree_search=True):
        return
    if not self.plan or not self.base_dir:
        self.announce("No plan available to export. Run [Ctrl+S] Scan first.")
        return

    default_out = str(Path(self.base_dir) / "simulation_report.html")

    def handle_export_modal_result(result: tuple[str, str] | None) -> None:
        if not result:
            return
        export_path, report_format = result
        try:
            from app.core.simulation_exporter import SimulationExporter

            conflict_pol = str(
                getattr(self.settings, "CONFLICT_POLICY", "skip") or "skip"
            )
            exporter = SimulationExporter(
                self.plan,
                self.base_dir,
                conflict_policy=conflict_pol,
            )
            if report_format == "json":
                exporter.export_json(export_path)
            else:
                exporter.export_html(export_path)

            self.announce(f"Simulation report exported to '{export_path}'.")
        except Exception as e:
            logger.error(f"Error exporting simulation report: {e}")
            self.announce(f"Export error: {e}")

    self.push_screen(
        ExportReportModal(default_path=default_out, default_format="html"),
        handle_export_modal_result,
    )

Focus the real-time tree filter search input bar.

Source code in app/ui/tui.py
2585
2586
2587
2588
2589
2590
2591
2592
2593
def action_focus_search(self) -> None:
    """Focus the real-time tree filter search input bar."""
    try:
        inp = self.query_one("#tree-search-input", Input)
        inp.focus()
        inp.select_all()
        self.announce("Focused tree search input bar.")
    except Exception:
        pass

action_generate_sample_corpus(open_modal=False)

Generate sample document corpus in active workspace directory, or launch interactive playground modal.

Source code in app/ui/tui.py
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
def action_generate_sample_corpus(self, open_modal: bool = False) -> None:
    """Generate sample document corpus in active workspace directory, or launch interactive playground modal."""
    if self._is_text_control_focused():
        return

    target_dir = self._sample_dataset_dir(self.base_dir or os.getcwd())

    if open_modal:
        from app.ui.modals.sample_playground import SamplePlaygroundModal

        self.push_screen(
            SamplePlaygroundModal(self.settings, target_dir=target_dir)
        )
        return

    from app.core.sample_corpus import generate_sample_corpus

    try:
        try:
            generate_sample_corpus(target_dir, overwrite=False)
            self.announce(f"Generated sample dataset in {target_dir}.")
        except FileExistsError:
            self.announce(f"Using the existing sample dataset in {target_dir}.")
    except Exception as exc:
        logger.error(f"Error generating sample dataset: {exc}")
        self.announce(f"Failed to generate sample dataset: {exc}")
        return
    if os.path.abspath(target_dir) != os.path.abspath(self.base_dir or ""):
        self._clear_manual_plan_edits()
    self.base_dir = target_dir
    self.source_dirs = [target_dir]
    self.action_scan_directory()

action_import_rules()

Open external rule import modal screen.

Source code in app/ui/tui.py
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
def action_import_rules(self) -> None:
    """Open external rule import modal screen."""
    if self._is_text_control_focused(allow_tree_search=True):
        return

    def on_import_closed(result: Any = None) -> None:
        if result is not None:
            self.update_status()
            if self.base_dir:
                self.action_scan_directory()
        try:
            self.query_one("#plan-tree", Tree).focus()
        except Exception:
            pass

    self.push_screen(RuleImportModal(self.get_active_settings()), on_import_closed)

action_open_active_rules()

Open active rule manager modal screen [Ctrl+R].

Source code in app/ui/tui.py
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
def action_open_active_rules(self) -> None:
    """Open active rule manager modal screen [Ctrl+R]."""
    if self._is_text_control_focused(allow_tree_search=True):
        return

    def on_rules_closed(mutated: bool | None = None) -> None:
        try:
            self.query_one("#plan-tree", Tree).focus()
        except Exception:
            pass
        if mutated:
            self.update_status()
            if self.base_dir:
                self.action_scan_directory()

    self.push_screen(
        ActiveRuleManagerModal(self.get_active_settings()), on_rules_closed
    )

action_open_audit_report(audit_report=None)

Open the Audit Report Modal Screen.

Source code in app/ui/tui.py
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
def action_open_audit_report(
    self, audit_report: dict[str, Any] | None = None
) -> None:
    """Open the Audit Report Modal Screen."""
    if not audit_report and self.app_session and self.plan:
        from app.core.audit_reporter import resolve_audit_report

        audit_report = resolve_audit_report(
            audit_report,
            self.app_session.base_dir or ".",
            self.plan,
        )

    if audit_report:
        self.push_screen(AuditReportModal(audit_report, session=self.app_session))
    else:
        self.announce(
            "No audit report available. Execute a sorting operation first."
        )

action_open_cheat_sheet(from_character=None)

Open keyboard shortcut cheat sheet modal screen.

Source code in app/ui/tui.py
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
def action_open_cheat_sheet(self, from_character: bool | None = None) -> None:
    """Open keyboard shortcut cheat sheet modal screen."""
    if from_character is True:
        if (
            self._is_character_input_focused()
            or not self._character_shortcuts_enabled()
        ):
            return
    elif from_character is None:
        if self._is_text_control_focused(allow_tree_search=True):
            return
    if isinstance(self.screen, ShortcutCheatSheetModal):
        return
    self.push_screen(ShortcutCheatSheetModal())

action_open_command_palette()

Open command palette overlay modal [Ctrl+K].

Source code in app/ui/tui.py
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
def action_open_command_palette(self) -> None:
    """Open command palette overlay modal [Ctrl+K]."""
    focused_id = getattr(self.focused, "id", None)
    if focused_id != "tree-search-input" and self._is_text_control_focused():
        return

    def on_command_selected(cmd: PaletteCommand | None) -> None:
        try:
            self.query_one("#plan-tree", Tree).focus()
        except Exception:
            pass
        if not cmd or not cmd.action_name:
            return
        handler = getattr(self, cmd.action_name, None)
        if callable(handler):
            if inspect.iscoroutinefunction(handler):
                self.run_worker(handler())
            else:
                res = handler()
                if inspect.iscoroutine(res):
                    self.run_worker(res)
        else:
            self.announce(
                f"Action '{cmd.action_name}' is not supported.",
                priority="assertive",
            )

    self.push_screen(CommandPaletteModal(), on_command_selected)

action_open_cro_forensic()

Open CRO multi-study forensic ingestion modal screen.

Source code in app/ui/tui.py
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
def action_open_cro_forensic(self) -> None:
    """Open CRO multi-study forensic ingestion modal screen."""
    if self._is_text_control_focused(allow_tree_search=True):
        return
    from app.core.plugin_registry import PluginRegistry

    reg = PluginRegistry.get_instance()
    reg.load_plugins_from_settings(self.settings)
    view_cls = reg.get_tui_view("cro_forensic")
    if view_cls:
        self.push_screen(view_cls(self.settings, base_dir=self.base_dir))
    else:
        self.announce("CRO Forensic ingestion plugin is not enabled.")

action_open_dropzone(initial_paths=None, force=False, initial_dest_dir=None)

Open floating dropzone overlay modal screen.

Source code in app/ui/tui.py
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
def action_open_dropzone(
    self,
    initial_paths: list[str] | None = None,
    force: bool = False,
    initial_dest_dir: str | None = None,
) -> None:
    """Open floating dropzone overlay modal screen."""
    if not force and self._is_text_control_focused(allow_tree_search=True):
        return

    def on_drop_done(res: dict[str, Any] | None) -> None:
        if res:
            if res.get("session_id"):
                self._last_drop_session_id = str(res["session_id"])
            cnt = res.get("processed_count", 0)
            dest_used = res.get("destination_dir")
            if dest_used and not self.base_dir and os.path.isdir(dest_used):
                self.base_dir = dest_used
                if not self.source_dirs:
                    self.source_dirs = [dest_used]
            self.announce(f"DropZone triage finished: {cnt} item(s) organized.")
            scan_dir = dest_used or self.base_dir
            if scan_dir and os.path.exists(scan_dir) and self.base_dir:
                if os.path.normcase(os.path.abspath(scan_dir)) == os.path.normcase(
                    os.path.abspath(self.base_dir)
                ):
                    self.action_scan_directory()

    self.push_screen(
        DropZoneModal(
            settings=self.settings,
            base_dir=self.base_dir,
            initial_paths=initial_paths,
            initial_dest_dir=initial_dest_dir,
        ),
        on_drop_done,
    )

action_open_extraction_preview()

Open document extraction preview modal for active or selected supported file [Ctrl+X].

Source code in app/ui/tui.py
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
def action_open_extraction_preview(self) -> None:
    """Open document extraction preview modal for active or selected supported file [Ctrl+X]."""
    if self._is_text_control_focused(allow_tree_search=True):
        return

    from app.core.extractor_strategies import registry

    def _resolve_supported_path(
        raw_fp: Any, src_root: str | None = None
    ) -> str | None:
        if not raw_fp:
            return None
        fp_str = str(raw_fp)
        if "::" in fp_str and not os.path.exists(fp_str):
            s_root, rel_part = fp_str.split("::", 1)
            fp_str = os.path.join(s_root, rel_part)
        ext = os.path.splitext(fp_str)[1].lower()
        if not ext or not registry.is_supported(ext):
            return None
        if not os.path.isabs(fp_str):
            eff_root = src_root or self.base_dir
            if eff_root:
                cand = os.path.join(eff_root, fp_str)
                if os.path.exists(cand):
                    return cand
        return fp_str

    preview_path: str | None = None

    active_node = self._get_active_node()
    if active_node and active_node.data:
        data = active_node.data
        if data.get("is_file"):
            info_dict = (
                data.get("info") if isinstance(data.get("info"), dict) else {}
            )
            fp = (
                data.get("filepath")
                or info_dict.get("src_path")
                or info_dict.get("path")
                or info_dict.get("source_path")
                or data.get("key")
            )
            preview_path = _resolve_supported_path(
                fp, src_root=info_dict.get("source_root")
            )

    if not preview_path:
        target_files = self._get_target_file_infos()
        for tf in target_files:
            fp = (
                tf.get("src_path")
                or tf.get("path")
                or tf.get("filepath")
                or tf.get("source_path")
            )
            resolved = _resolve_supported_path(fp, src_root=tf.get("source_root"))
            if resolved:
                preview_path = resolved
                break

    if not preview_path:
        self.announce(
            "Please select a supported document to preview extracted text [Ctrl+X]."
        )
        return

    def on_preview_closed(saved_val: int | None) -> None:
        if saved_val is not None:
            self.announce(f"Updated extraction density threshold to {saved_val}.")

    self.push_screen(
        ExtractionPreviewModal(
            preview_path,
            self.settings,
            db=self.db,
            base_dir=self.base_dir,
        ),
        on_preview_closed,
    )

action_open_history()

Trigger session history view and audit log export modal screen.

Source code in app/ui/tui.py
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
def action_open_history(self) -> None:
    """Trigger session history view and audit log export modal screen."""
    if self._is_text_control_focused(allow_tree_search=True):
        return
    from app.core.session_catalog import list_sessions

    sessions = list_sessions()

    def handle_history_modal_result(result: dict[str, Any] | None) -> None:
        if not result:
            return
        session_id = result["session_id"]
        fmt = str(result.get("format") or "csv")
        output_path = str(result.get("output_path") or "").strip()
        if not output_path:
            from app.config import get_app_dir

            output_path = str(
                Path(get_app_dir()) / "exports" / f"audit_log.{fmt.lower()}"
            )

        selected_base_dir: str | None = self.base_dir or None
        if not selected_base_dir and session_id not in ("none", "all"):
            for sess_item in sessions:
                if sess_item.get("session_id") == session_id:
                    raw_bdir = sess_item.get("base_dir")
                    if raw_bdir:
                        selected_base_dir = str(raw_bdir)
                    break

        try:
            from app.core.services import acquire_services

            with acquire_services() as services:
                export_res = services.history.export_audit_log(
                    output_path=output_path,
                    session_id=session_id
                    if session_id not in ("none", "all")
                    else None,
                    format=fmt,
                    base_dir=selected_base_dir,
                )
            cnt = export_res.get("count", 0)
            out_p = export_res.get("output_path", output_path)
            msg = (
                f"Audit log exported ({fmt.upper()}) to '{out_p}' ({cnt} records)."
            )
            self.announce(msg)
            from app.ui.notifications import notify

            notify(msg, type="info")
        except Exception as e:
            logger.error(f"Error exporting audit log from TUI: {e}")
            self.announce(f"Export error: {e}")
            from app.ui.notifications import notify

            notify(f"Export error: {e}", type="error")

    self.push_screen(
        HistoryModal(sessions=sessions, base_dir=self.base_dir),
        handle_history_modal_result,
    )

action_open_model_manager()

Open model manager modal screen.

Source code in app/ui/tui.py
2050
2051
2052
2053
2054
def action_open_model_manager(self) -> None:
    """Open model manager modal screen."""
    if self._is_text_control_focused(allow_tree_search=True):
        return
    self.push_screen(ModelManagerModal(self.settings))

action_open_quarantine_vault()

Open the Quarantine Vault Modal Screen.

Source code in app/ui/tui.py
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
def action_open_quarantine_vault(self) -> None:
    """Open the Quarantine Vault Modal Screen."""
    db = self.app_session.db if self.app_session else None
    base_dir = self.base_dir
    policies = (
        getattr(self.settings, "POLICIES", [])
        if hasattr(self, "settings") and self.settings
        else []
    )
    self.push_screen(
        QuarantineVaultModal(db=db, base_dir=base_dir, policies=policies)
    )

action_open_settings()

Open settings modal screen.

Source code in app/ui/tui.py
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
def action_open_settings(self) -> None:
    """Open settings modal screen."""
    if self._is_text_control_focused(allow_tree_search=True):
        return

    def on_saved(res: dict[str, Any] | None) -> None:
        if not res:
            return
        import copy

        from pydantic import ValidationError

        settings_keys = (
            "PROTECTED_PATHS",
            "IGNORED_EXTENSIONS",
            "MAX_WORKERS",
            "MAX_FOLDERS",
            "SORTING_STRATEGY",
            "AI_ASSISTED_NAMING",
            "CLINICAL_SMART_RENAMING",
            "CONTEXTUAL_RENAMING",
            "SPEAK_ANNOUNCEMENTS",
            "ENABLE_CHARACTER_KEY_SHORTCUTS",
            "PDF_TEXT_DENSITY_THRESHOLD",
            "CONFLICT_POLICY",
            "DUPLICATE_ACTION",
            "DETECT_ORIGINAL_BY",
            "CLEANUP_EMPTY_FOLDERS",
            "PRESERVE_HIERARCHY",
            "SCAN_MAX_DEPTH",
            "AUTO_QUARANTINE_RATINGS",
            "QUARANTINE_DIR_NAME",
            "RENAME_PATTERN",
            "AI_CONSENT_GRANTED",
        )
        settings_obj: Any = self.settings
        prior_values: dict[str, Any] = {
            key: copy.deepcopy(getattr(settings_obj, key))
            for key in settings_keys
            if key in res and hasattr(settings_obj, key)
        }
        had_save_timer = getattr(settings_obj, "_save_timer", None) is not None
        prior_transient = copy.deepcopy(
            getattr(settings_obj, "_transient_values", None)
        )
        prior_env_keys = (
            set(getattr(settings_obj, "_env_sourced_keys", ()))
            if hasattr(settings_obj, "_env_sourced_keys")
            else None
        )
        prior_has_val_errors = getattr(
            settings_obj, "_has_validation_errors", False
        )
        prior_val_errors = copy.deepcopy(
            getattr(settings_obj, "_validation_errors", None)
        )

        validation_errors: list[str] = []
        model_obj = getattr(settings_obj, "_settings_model", None)
        if model_obj is not None and hasattr(model_obj, "model_copy"):
            candidate_model = model_obj.model_copy(deep=True)
            for key in settings_keys:
                if key not in res or not hasattr(candidate_model, key):
                    continue
                try:
                    setattr(candidate_model, key, res[key])
                except ValidationError as exc:
                    logger.warning(
                        "Settings validation failed for %s: %s",
                        key,
                        exc,
                        exc_info=True,
                    )
                    first_err = (
                        exc.errors()[0].get("msg", str(exc))
                        if exc.errors()
                        else str(exc)
                    )
                    validation_errors.append(f"{key}: {first_err}")
                except ValueError as exc:
                    logger.warning(
                        "Settings validation failed for %s: %s",
                        key,
                        exc,
                        exc_info=True,
                    )
                    validation_errors.append(f"{key}: {exc}")

        applied_keys: list[str] = []
        if not validation_errors:
            for key in settings_keys:
                if key not in res:
                    continue
                if (
                    key == "AI_CONSENT_GRANTED"
                    and validation_errors
                    and isinstance(res[key], bool)
                ):
                    continue
                try:
                    setattr(self.settings, key, res[key])
                    applied_keys.append(key)
                except ValidationError as exc:
                    logger.warning(
                        "Settings validation failed for %s: %s",
                        key,
                        exc,
                        exc_info=True,
                    )
                    first_err = (
                        exc.errors()[0].get("msg", str(exc))
                        if exc.errors()
                        else str(exc)
                    )
                    validation_errors.append(f"{key}: {first_err}")
                except ValueError as exc:
                    logger.warning(
                        "Settings validation failed for %s: %s",
                        key,
                        exc,
                        exc_info=True,
                    )
                    validation_errors.append(f"{key}: {exc}")

        if validation_errors:
            notify_fn = getattr(settings_obj, "_notify_observers", None)
            for key in reversed(applied_keys):
                if key not in prior_values:
                    continue
                if model_obj is not None and hasattr(model_obj, key):
                    cur_val = getattr(model_obj, key, None)
                    setattr(model_obj, key, prior_values[key])
                    if cur_val != prior_values[key] and callable(notify_fn):
                        notify_fn(key, prior_values[key])
                else:
                    setattr(self.settings, key, prior_values[key])

            if prior_transient is not None and hasattr(
                settings_obj, "_transient_values"
            ):
                settings_obj._transient_values = prior_transient
            if prior_env_keys is not None and hasattr(
                settings_obj, "_env_sourced_keys"
            ):
                settings_obj._env_sourced_keys = prior_env_keys
            if hasattr(settings_obj, "_has_validation_errors"):
                settings_obj._has_validation_errors = prior_has_val_errors
            if prior_val_errors is not None and hasattr(
                settings_obj, "_validation_errors"
            ):
                settings_obj._validation_errors = prior_val_errors
            if not had_save_timer:
                pending_timer = getattr(settings_obj, "_save_timer", None)
                if pending_timer is not None:
                    pending_timer.cancel()
                    settings_obj._save_timer = None
                cancel_fn = getattr(settings_obj, "_cancel_file_timer", None)
                filepath_val = getattr(settings_obj, "_filepath", None)
                if callable(cancel_fn) and isinstance(filepath_val, str):
                    cancel_fn(filepath_val)

            err_msg = f"Settings error: Failed to save settings ({'; '.join(validation_errors)})."
            self.update_status()
            self.announce(err_msg, priority="assertive")
            if hasattr(self, "notify"):
                self.notify(err_msg, severity="error")
            return

        if hasattr(self.settings, "_save"):
            self.settings._save()
        self.update_status()
        self.announce("Settings updated and saved.")
        if self.base_dir:
            self.action_scan_directory()

    self.push_screen(SettingsModal(self.settings), on_saved)

Open starter rule template gallery modal screen.

Source code in app/ui/tui.py
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
def action_open_template_gallery(self) -> None:
    """Open starter rule template gallery modal screen."""
    if self._is_text_control_focused(allow_tree_search=True):
        return

    def on_gallery_closed(_res: Any = None) -> None:
        try:
            self.query_one("#plan-tree", Tree).focus()
        except Exception:
            pass

    self.push_screen(
        TemplateGalleryModal(self.get_active_settings()), on_gallery_closed
    )

action_open_wizard()

Open model onboarding wizard modal screen.

Source code in app/ui/tui.py
2056
2057
2058
2059
2060
2061
2062
def action_open_wizard(self) -> None:
    """Open model onboarding wizard modal screen."""
    if self._is_text_control_focused(allow_tree_search=True):
        return
    if isinstance(self.screen, WizardModal):
        return
    self.push_screen(WizardModal(self.settings, current_dir=self.base_dir))

action_quit() async

Quit application [Ctrl+Q], from any focused widget.

Source code in app/ui/tui.py
2599
2600
2601
async def action_quit(self) -> None:
    """Quit application [Ctrl+Q], from any focused widget."""
    await super().action_quit()

action_select_dir()

Open directory selection modal.

Source code in app/ui/tui.py
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
def action_select_dir(self) -> None:
    """Open directory selection modal."""
    if self._is_text_control_focused(allow_tree_search=True):
        return

    def on_selected(path: str | list[str] | None) -> None:
        if not path:
            return
        paths = [path] if isinstance(path, str) else list(path)
        valid_paths = [os.path.abspath(p) for p in paths if p and os.path.exists(p)]
        if valid_paths:
            from app.ui.ai_runtime import plan_has_manual_modifications

            prev_sources = [
                os.path.abspath(p) for p in getattr(self, "source_dirs", []) if p
            ]
            if (
                valid_paths != prev_sources
                and not getattr(self, "non_interactive", False)
                and plan_has_manual_modifications(self)
            ):
                summary = self._describe_manual_modifications()

                def _on_confirm_switch(confirmed: bool | None) -> None:
                    if confirmed is True:
                        self._apply_selected_workspace(valid_paths, prev_sources)

                self.push_screen(
                    UnsavedWorkspaceSwitchModal(
                        new_sources=valid_paths,
                        modification_summary=summary,
                    ),
                    _on_confirm_switch,
                )
                return

            self._apply_selected_workspace(valid_paths, prev_sources)
        else:
            from app.ui.notifications import notify

            err_msg = f"Target directory does not exist: {path}"
            self.announce(err_msg, priority="assertive")
            notify(err_msg, type="error")

    self.push_screen(
        DirectorySelectModal(
            current_dir=self.base_dir,
            source_dirs=getattr(self, "source_dirs", None),
            settings=self.settings,
        ),
        on_selected,
    )

action_toggle_character_shortcuts()

Toggle single-character keyboard shortcuts preference [Ctrl+Alt+K].

Source code in app/ui/tui.py
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
def action_toggle_character_shortcuts(self) -> None:
    """Toggle single-character keyboard shortcuts preference [Ctrl+Alt+K]."""
    current = self._character_shortcuts_enabled()
    new_val = not current
    self.settings.ENABLE_CHARACTER_KEY_SHORTCUTS = new_val
    if hasattr(self.settings, "_save"):
        self.settings._save()
    state_str = "enabled" if new_val else "disabled"
    self.announce(f"Character key shortcuts {state_str}.", priority="polite")
    self.update_status()
    try:
        self.refresh_bindings()
    except Exception:
        pass

action_toggle_daemon(from_character=False) async

Toggle watchdog daemon pause / resume state.

Source code in app/ui/tui.py
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
async def action_toggle_daemon(self, from_character: bool = False) -> None:
    """Toggle watchdog daemon pause / resume state."""
    if from_character:
        if not self._tree_has_focus() or not self._character_shortcuts_enabled():
            return
    if self._is_text_control_focused(allow_tree_search=True):
        return

    base_dir = getattr(self, "base_dir", None)
    if not base_dir or not os.path.exists(base_dir):
        msg = "No workspace folder selected for daemon monitoring."
        self.announce(msg, priority="assertive")
        if hasattr(self, "notify"):
            self.notify(msg, severity="warning")
        return

    from app.core.ipc import DaemonIPCClient, is_process_alive, read_pid_file

    pid_info = await asyncio.to_thread(read_pid_file, base_dir)
    if not pid_info or not is_process_alive(pid_info.get("pid", 0)):
        self._daemon_state = "idle"
        self.update_status()
        msg = "No background watchdog daemon is running for this workspace."
        self.announce(msg, priority="assertive")
        if hasattr(self, "notify"):
            self.notify(msg, severity="warning")
        return

    client = DaemonIPCClient(base_dir)
    try:
        current_state = getattr(self, "_daemon_state", "idle")
        if current_state == "paused":
            await client.send_command("resume", timeout=2.0)
            self._daemon_state = "active"
            self.update_status()
            msg = "Watchdog daemon resumed."
            self.announce(msg, priority="assertive")
            if hasattr(self, "notify"):
                self.notify(msg)
        elif current_state == "active":
            await client.send_command("pause", timeout=2.0)
            self._daemon_state = "paused"
            self.update_status()
            msg = "Watchdog daemon paused."
            self.announce(msg, priority="assertive")
            if hasattr(self, "notify"):
                self.notify(msg)
        else:
            status_res = await client.send_command("status", timeout=2.0)
            if (
                status_res.get("is_paused") is True
                or status_res.get("status") == "paused"
            ):
                await client.send_command("resume", timeout=2.0)
                self._daemon_state = "active"
                self.update_status()
                msg = "Watchdog daemon resumed."
                self.announce(msg, priority="assertive")
                if hasattr(self, "notify"):
                    self.notify(msg)
            else:
                await client.send_command("pause", timeout=2.0)
                self._daemon_state = "paused"
                self.update_status()
                msg = "Watchdog daemon paused."
                self.announce(msg, priority="assertive")
                if hasattr(self, "notify"):
                    self.notify(msg)
    except Exception as e:
        logger.warning(f"Failed to communicate with daemon: {e}")
        err_msg = f"Failed to communicate with daemon: {e}"
        self.announce(err_msg, priority="assertive")
        if hasattr(self, "notify"):
            self.notify(err_msg, severity="error")

action_undo_last_sort()

Trigger instant undo rollback for the most recent completed sorting session.

Source code in app/ui/tui.py
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
def action_undo_last_sort(self) -> None:
    """Trigger instant undo rollback for the most recent completed sorting session."""
    if self._is_text_control_focused(allow_tree_search=True):
        return
    from app.core.session_catalog import has_remaining_undo_moves, list_sessions

    sessions = list_sessions()
    active_base = (
        os.path.normcase(os.path.normpath(os.path.abspath(self.base_dir)))
        if self.base_dir
        else ""
    )
    target_sess = None
    last_drop_sid = getattr(self, "_last_drop_session_id", None)
    for s in sessions:
        is_trash_only_completed = (
            str(s.get("status", "")).lower() == "completed"
            and int(s.get("step_count") or 0) <= 0
            and int(s.get("trashed_count") or 0) > 0
        )
        if not has_remaining_undo_moves(s) and not is_trash_only_completed:
            continue
        if last_drop_sid and s.get("session_id") == last_drop_sid:
            target_sess = s
            break
        if active_base:
            sess_base_raw = str(s.get("base_dir", "") or "")
            if not sess_base_raw:
                continue
            sess_base = os.path.normcase(
                os.path.normpath(os.path.abspath(sess_base_raw))
            )
            if sess_base != active_base:
                continue
        target_sess = s
        break

    if not target_sess:
        self.announce("No completed sorting session available to undo.")
        return

    if (
        int(target_sess.get("step_count") or 0) <= 0
        and int(target_sess.get("trashed_count") or 0) > 0
    ):
        self.run_undo_worker(target_sess["session_id"])
        return

    def handle_confirm_result(result: dict[str, Any] | None) -> None:
        if not result or not result.get("confirmed"):
            return
        sid = result["session_id"]
        allow_missing = bool(
            result.get("allow_missing") or result.get("ignore_missing")
        )
        selected_step_ids = result.get("selected_step_ids")
        self.run_undo_worker(
            sid,
            ignore_missing=allow_missing,
            allow_missing=allow_missing,
            selected_step_ids=selected_step_ids,
        )

    self.push_screen(
        RollbackConfirmModal(session_info=target_sess),
        handle_confirm_result,
    )

announce(message, priority='polite', help_url=None)

Emit screen reader announcement and log to live execution log feed.

Source code in app/ui/tui.py
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
def announce(
    self,
    message: str,
    priority: str = "polite",
    help_url: str | None = None,
) -> str:
    """Emit screen reader announcement and log to live execution log feed."""
    res = super().announce(message, priority=priority, help_url=help_url)
    try:
        log_w = self.query_one("#tui-log", Log)
        display_msg = (
            f"{res} [Help: {help_url}]" if help_url and help_url not in res else res
        )
        log_w.write_line(display_msg)
    except Exception:
        pass
    return res

check_abandoned_sessions() async

Scan for abandoned sessions on startup and prompt for recovery if detected.

Source code in app/ui/tui.py
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
@work
async def check_abandoned_sessions(self) -> None:
    """Scan for abandoned sessions on startup and prompt for recovery if detected."""
    try:
        import asyncio

        from app.core.session_catalog import find_abandoned_sessions

        abandoned = await asyncio.to_thread(find_abandoned_sessions)
        if not abandoned:
            return

        if len(abandoned) == 1:
            session_info = abandoned[0]

            def on_recovery_choice(choice: str | None) -> None:
                if not choice:
                    return
                if choice == "resume":
                    self._do_recovery_resume(session_info)
                elif choice == "rollback":
                    self._do_recovery_rollback(session_info)
                elif choice == "clean":
                    self._do_recovery_clean(session_info)

            self.push_screen(SessionRecoveryModal(session_info), on_recovery_choice)
        else:

            def on_multi_recovery_choice(choice: Any) -> None:
                if not choice:
                    return
                action = getattr(choice, "action", choice)
                target_session = getattr(choice, "session", None)
                if isinstance(choice, dict):
                    action = choice.get("action")
                    target_session = choice.get("session")

                if action == "clean_all":
                    sessions_to_clean = getattr(choice, "sessions", abandoned)
                    for sess in sessions_to_clean:
                        self._do_recovery_clean(sess)
                elif action == "rollback_all":
                    sessions_to_rollback = getattr(choice, "sessions", abandoned)
                    for sess in sessions_to_rollback:
                        self._do_recovery_rollback(sess)
                    if self.base_dir:
                        self.action_scan_directory()
                        self.rebuild_tree()
                elif action == "resume" and target_session:
                    self._do_recovery_resume(target_session)
                elif action == "rollback" and target_session:
                    self._do_recovery_rollback(target_session)
                elif action == "clean" and target_session:
                    self._do_recovery_clean(target_session)

            self.push_screen(
                MultiSessionRecoveryModal(abandoned, settings=self.settings),
                on_multi_recovery_choice,
            )
    except Exception as e:
        logger.error(f"Error checking abandoned sessions: {e}")

check_action(action, parameters)

Check whether an action is enabled before dispatching key bindings.

Source code in app/ui/tui.py
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
def check_action(self, action: str, parameters: tuple[object, ...]) -> bool | None:
    """Check whether an action is enabled before dispatching key bindings."""
    focused = self.focused
    if action == "open_command_palette":
        if isinstance(self.screen, CommandPaletteModal):
            return False
        if (
            getattr(focused, "id", None) != "tree-search-input"
            and self._is_text_control_focused()
        ):
            return False

    if getattr(focused, "id", None) == "tree-search-input":
        if action in {
            "open_command_palette",
            "toggle_character_shortcuts",
            "focus_search",
            "quit",
        }:
            return super().check_action(action, parameters)
        if action == "open_cheat_sheet" and not (
            parameters and parameters[0] is True
        ):
            return super().check_action(action, parameters)
        return False

    is_char_action = action in {
        "toggle_selection",
        "exclude_selected",
        "include_selected",
        "reassign_selected",
        "visual_range_select",
        "toggle_select_all",
        "rate_positive",
        "rate_negative",
        "generate_sample_corpus",
    }
    if action in {"toggle_daemon", "scan_subfolders"} and (
        parameters and parameters[0] is True
    ):
        is_char_action = True

    if is_char_action:
        if not self._tree_has_focus() or not self._character_shortcuts_enabled():
            return False

    if action == "open_cheat_sheet" and parameters and parameters[0] is True:
        if not self._character_shortcuts_enabled():
            return False

    return super().check_action(action, parameters)

compose()

Compose main dual-pane TUI layout.

Source code in app/ui/tui.py
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
def compose(self) -> ComposeResult:
    """Compose main dual-pane TUI layout."""
    yield Heading(self.TITLE or "", level=1, id="app-title-heading")
    yield Header(show_clock=True)
    with Horizontal(id="main-dual-pane"):
        with Vertical(id="left-tree-pane"):
            search_input = Input(
                placeholder="Search tree nodes...",
                id="tree-search-input",
            )
            search_input.tooltip = (
                "Real-time search input field to filter preview tree nodes"
            )
            yield search_input
            with Horizontal(id="tree-summary-strip"):
                summary_lbl = Static(
                    "Selection: 0 selected · Plan: 0 of 0 included",
                    id="tree-summary-label",
                    markup=False,
                )
                summary_lbl.tooltip = "Summary of transient edit selection count and included plan items"
                yield summary_lbl
                with Horizontal(id="tree-summary-actions"):
                    btn_invert = Button(
                        "Invert",
                        id="btn-tree-invert-selection",
                        classes="tree-strip-btn",
                    )
                    btn_invert.tooltip = (
                        "Invert transient edit selection across visible files"
                    )
                    yield btn_invert

                    btn_collapse = Button(
                        "Collapse All",
                        id="btn-tree-collapse-all",
                        classes="tree-strip-btn",
                    )
                    btn_collapse.tooltip = (
                        "Collapse all destination folders in the plan tree"
                    )
                    yield btn_collapse

                    btn_expand = Button(
                        "Expand All",
                        id="btn-tree-expand-all",
                        classes="tree-strip-btn",
                    )
                    btn_expand.tooltip = (
                        "Expand all destination folders in the plan tree"
                    )
                    yield btn_expand
            tree = VimTree("Proposed Organization Plan", id="plan-tree")
            tree.tooltip = (
                "Interactive tree view of proposed file organization plan"
            )
            yield tree
        with Vertical(id="right-meta-pane"):
            with Vertical(id="right-meta-scroll"):
                with Vertical(id="onboarding-cta-card"):
                    yield Heading(
                        "Workspace Setup & Quick Actions",
                        level=2,
                        classes="meta-header",
                    )
                    yield Static(
                        "Welcome to Sortify AI Pro. Select a workspace directory, run a scan, or load a sample dataset to get started.",
                        id="onboarding-guide-text",
                    )
                    initial_workspace_state = (
                        f"Active Workspace: {self.base_dir}"
                        if self.base_dir
                        else "Active Workspace: No directory selected"
                    )
                    yield Static(
                        initial_workspace_state, id="onboarding-workspace-state"
                    )
                    with Vertical(id="onboarding-cta-buttons"):
                        btn_select_dir = Button(
                            "Choose Directory [Ctrl+B]",
                            id="btn-cta-select-dir",
                            variant="primary",
                        )
                        btn_select_dir.tooltip = "Open directory selection dialog to choose workspace folder [Ctrl+B]"
                        yield btn_select_dir

                        btn_scan_dir = Button(
                            "Scan Directory [Ctrl+S]",
                            id="btn-cta-scan-dir",
                            variant="success",
                        )
                        btn_scan_dir.tooltip = "Initiate workspace scan to generate organization plan [Ctrl+S]"
                        yield btn_scan_dir

                        btn_sample_data = Button(
                            "Load Sample Dataset \\[G]",
                            id="btn-cta-sample-data",
                            variant="default",
                        )
                        btn_sample_data.tooltip = (
                            "Generate interactive sample dataset in workspace [G]"
                        )
                        yield btn_sample_data
                with Vertical(id="inspector-container"):
                    yield Heading(
                        "Side-by-Side Path Comparison",
                        level=2,
                        classes="meta-header",
                    )
                    path_comp = Static(
                        "Select a file or folder in the tree to compare source and target paths.",
                        id="path-comparison",
                    )
                    path_comp.tooltip = "Side-by-side split column view comparing source and destination target paths"
                    yield path_comp
                    yield Heading(
                        "Node Metadata Inspector", level=2, classes="meta-header"
                    )
                    meta_widget = Static(
                        "Select a node in the tree to inspect details.",
                        id="meta-details",
                    )
                    meta_widget.tooltip = "Metadata inspector panel displaying attributes of selected file or folder"
                    yield meta_widget
                yield Heading("Live Execution Log", level=2, classes="meta-header")
                tui_log = Log(id="tui-log", classes="tui-log-area")
                tui_log.tooltip = "Live operation execution log output feed"
                yield tui_log
            btn_exec = Button(
                "Execute Plan [Ctrl+E]",
                id="btn-execute",
                variant="primary",
                disabled=True,
            )
            btn_exec.tooltip = EXECUTE_NEEDS_SCAN_TOOLTIP
            yield btn_exec
    alert_banner = Static("", id="alert-banner")
    alert_banner.tooltip = (
        "Validation alert banner displaying blocking errors or warnings"
    )
    yield alert_banner
    pb = ProgressBar(total=100, show_percentage=True, id="main-progress-bar")
    pb.tooltip = "Active operation background progress indicator"
    pb.display = False
    yield pb
    initial_status = f"{self._get_ai_status_badge()} {self._get_daemon_status_badge()} Ready. Press [Ctrl+S] to Scan or [Ctrl+B] to select Directory."
    sb = Static(
        initial_status,
        id="status-bar",
        markup=False,
    )
    sb.tooltip = "Application status and screen reader announcement bar"
    yield sb
    yield _StableFooter()

get_active_settings(*, fallback_to_global=True)

Return a folder-scoped settings view for base_dir when selected.

Source code in app/ui/tui.py
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
def get_active_settings(self, *, fallback_to_global: bool = True) -> Any:
    """Return a folder-scoped settings view for ``base_dir`` when selected."""
    from app.config import resolve_scoped_settings

    if getattr(self, "base_dir", None):
        return resolve_scoped_settings(
            self.settings,
            self.base_dir,
            fallback_to_global=fallback_to_global,
        )
    return self.settings

on_btn_cta_sample_data_pressed()

Handle Load Sample Dataset CTA button press.

Source code in app/ui/tui.py
2485
2486
2487
2488
@on(Button.Pressed, "#btn-cta-sample-data")
def on_btn_cta_sample_data_pressed(self) -> None:
    """Handle Load Sample Dataset CTA button press."""
    self.action_generate_sample_corpus()

on_btn_cta_scan_dir_pressed()

Handle Scan Directory CTA button press.

Source code in app/ui/tui.py
2480
2481
2482
2483
@on(Button.Pressed, "#btn-cta-scan-dir")
def on_btn_cta_scan_dir_pressed(self) -> None:
    """Handle Scan Directory CTA button press."""
    self.action_scan_directory()

on_btn_cta_select_dir_pressed()

Handle Choose Directory CTA button press.

Source code in app/ui/tui.py
2475
2476
2477
2478
@on(Button.Pressed, "#btn-cta-select-dir")
def on_btn_cta_select_dir_pressed(self) -> None:
    """Handle Choose Directory CTA button press."""
    self.action_select_dir()

on_btn_execute_pressed()

Handle Execute Plan button press.

Source code in app/ui/tui.py
2437
2438
2439
2440
@on(Button.Pressed, "#btn-execute")
def on_btn_execute_pressed(self) -> None:
    """Handle Execute Plan button press."""
    self.action_execute_sort()

on_btn_tree_collapse_all_pressed()

Handle Collapse All summary strip button press.

Source code in app/ui/tui.py
2498
2499
2500
2501
2502
2503
2504
@on(Button.Pressed, "#btn-tree-collapse-all")
def on_btn_tree_collapse_all_pressed(self) -> None:
    """Handle Collapse All summary strip button press."""
    self.action_collapse_all()
    tree_matches = self.query("#plan-tree")
    if tree_matches:
        tree_matches.first(Tree).focus()

on_btn_tree_expand_all_pressed()

Handle Expand All summary strip button press.

Source code in app/ui/tui.py
2506
2507
2508
2509
2510
2511
2512
@on(Button.Pressed, "#btn-tree-expand-all")
def on_btn_tree_expand_all_pressed(self) -> None:
    """Handle Expand All summary strip button press."""
    self.action_expand_all()
    tree_matches = self.query("#plan-tree")
    if tree_matches:
        tree_matches.first(Tree).focus()

on_btn_tree_invert_selection_pressed()

Handle Invert Selection summary strip button press.

Source code in app/ui/tui.py
2490
2491
2492
2493
2494
2495
2496
@on(Button.Pressed, "#btn-tree-invert-selection")
def on_btn_tree_invert_selection_pressed(self) -> None:
    """Handle Invert Selection summary strip button press."""
    self.action_invert_selection()
    tree_matches = self.query("#plan-tree")
    if tree_matches:
        tree_matches.first(Tree).focus()

on_key(event)

Handle global application key events.

Source code in app/ui/tui.py
2576
2577
2578
2579
2580
2581
2582
2583
def on_key(self, event: events.Key) -> None:
    """Handle global application key events."""
    try:
        if isinstance(self.screen, ModalScreen):
            return
        handle_search_and_tree_key(self, event)
    except Exception:
        pass

on_mount()

Mount event handler.

Source code in app/ui/tui.py
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
def on_mount(self) -> None:
    """Mount event handler."""
    self._update_layout(self.size.width, self.size.height)
    try:
        from app.ui.notifications import NotificationManager

        NotificationManager.get_instance().register_tui(self)
    except Exception:
        pass
    try:
        from app.config import AppSettings

        AppSettings.add_observer("AI_CONSENT_GRANTED", self._on_ai_consent_changed)
        AppSettings.add_observer(
            "ENABLE_CHARACTER_KEY_SHORTCUTS",
            self._on_character_shortcuts_changed,
        )
    except Exception:
        pass
    try:
        tree = self.query_one("#plan-tree", Tree)
        tree.show_root = True
        tree.root.expand()
        tree.focus()
    except Exception:
        pass
    self._update_tree_summary_strip()
    self.announce(f"Ready. {self._start_hint()}")
    self._update_onboarding_cta_visibility()
    self.check_abandoned_sessions()
    self.set_interval(1.0, self._poll_daemon_status)
    self.set_interval(0.5, self._poll_ai_provisioning_status)
    self.run_worker(self._poll_daemon_status(), name="poll_daemon_startup")

    if self.open_dropzone or self.initial_drop_paths:
        launch_dest = self.initial_dest_dir
        self.initial_dest_dir = None
        self.action_open_dropzone(
            initial_paths=self.initial_drop_paths,
            initial_dest_dir=launch_dest,
            force=True,
        )

    env_non_interactive = os.environ.get("NON_INTERACTIVE")
    is_non_interactive_env = bool(
        env_non_interactive
        and env_non_interactive.strip().lower() in ("1", "true", "yes", "on")
    )
    env_consent = os.environ.get("SORTIFY_AI_CONSENT")
    if env_consent is not None:
        env_consent_clean = env_consent.strip().lower()
        if env_consent_clean in ("1", "true", "yes", "on"):
            self.settings.AI_CONSENT_GRANTED = True
        elif env_consent_clean in ("0", "false", "no", "off"):
            self.settings.AI_CONSENT_GRANTED = False

    is_bypass = (
        self.skip_wizard
        or self.non_interactive
        or getattr(self.settings, "_skip_wizard", False)
        or getattr(self.settings, "_non_interactive", False)
        or is_non_interactive_env
    )

    _unset = object()
    if getattr(self.settings, "AI_CONSENT_GRANTED", _unset) is None:
        if is_bypass:
            self.settings.AI_CONSENT_GRANTED = False
            if hasattr(self.settings, "_save"):
                try:
                    self.settings._save()
                except Exception:
                    pass
        elif not getattr(
            self, "_wizard_dismissed_this_session", False
        ) and not self._has_file_nodes(self.plan):

            def _auto_open_wizard() -> None:
                if (
                    isinstance(self.screen, ModalScreen)
                    or len(self.screen_stack) > 1
                    or self._has_file_nodes(self.plan)
                ):
                    return
                self.action_open_wizard()

            self.call_after_refresh(_auto_open_wizard)

on_node_selected(event)

Handle tree node selection or highlight to update metadata pane and screen reader announcement.

Source code in app/ui/tui.py
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
@on(Tree.NodeHighlighted, "#plan-tree")
@on(Tree.NodeSelected, "#plan-tree")
def on_node_selected(self, event: Tree.NodeSelected | Tree.NodeHighlighted) -> None:
    """Handle tree node selection or highlight to update metadata pane and screen reader announcement."""
    self.active_tree_node = event.node
    if event.node and getattr(event.node, "data", None):
        cdata = event.node.data
        if isinstance(cdata, dict):
            key = cdata.get("filepath") or cdata.get("folder") or cdata.get("key")
            if key:
                self._last_cursor_key = key
    self._update_inspector(event.node)
    self._update_onboarding_cta_visibility()
    if isinstance(event, Tree.NodeSelected) and event.node and event.node.data:
        if event.node.data.get("is_empty_state"):
            action = event.node.data.get("action")
            if action == "generate_sample_corpus":
                self.action_generate_sample_corpus()
            elif action == "scan_subfolders":
                self.action_scan_subfolders()
            elif action == "open_settings":
                self.action_open_settings()
            elif action == "select_dir":
                self.action_select_dir()

on_tree_node_expansion_changed(event)

Handle tree node expand/collapse to keep expansion state memory synchronized.

Source code in app/ui/tui.py
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
@on(Tree.NodeExpanded, "#plan-tree")
@on(Tree.NodeCollapsed, "#plan-tree")
def on_tree_node_expansion_changed(
    self, event: Tree.NodeExpanded | Tree.NodeCollapsed
) -> None:
    """Handle tree node expand/collapse to keep expansion state memory synchronized."""
    search_query = self._get_current_search_query()
    if not search_query and event.node and getattr(event.node, "data", None):
        cdata = event.node.data
        if isinstance(cdata, dict) and not cdata.get("is_file"):
            key = cdata.get("filepath") or cdata.get("folder") or cdata.get("key")
            if key:
                if (
                    not hasattr(self, "_tree_expansion_memory")
                    or self._tree_expansion_memory is None
                ):
                    self._tree_expansion_memory = {}
                is_exp = isinstance(event, Tree.NodeExpanded)
                self._tree_expansion_memory[key] = is_exp
                if hasattr(
                    self, "_last_rendered_expansion_snapshot"
                ) and isinstance(self._last_rendered_expansion_snapshot, dict):
                    self._last_rendered_expansion_snapshot[key] = is_exp

on_tree_search_changed(event)

Handle real-time search input field change to dynamically filter preview tree nodes.

Source code in app/ui/tui.py
2565
2566
2567
2568
@on(Input.Changed, "#tree-search-input")
def on_tree_search_changed(self, event: Input.Changed) -> None:
    """Handle real-time search input field change to dynamically filter preview tree nodes."""
    schedule_tree_search_filter(self, event.value)

on_tree_search_submitted(event)

Move focus from #tree-search-input to #plan-tree on Enter while preserving filter.

Source code in app/ui/tui.py
2570
2571
2572
2573
2574
@on(Input.Submitted, "#tree-search-input")
def on_tree_search_submitted(self, event: Input.Submitted) -> None:
    """Move focus from ``#tree-search-input`` to ``#plan-tree`` on Enter while preserving filter."""
    event.stop()
    handoff_search_to_tree(self)

on_unmount()

Lifecycle hook called when application is unmounted.

Source code in app/ui/tui.py
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
def on_unmount(self) -> None:
    """Lifecycle hook called when application is unmounted."""
    try:
        from app.ui.notifications import NotificationManager

        NotificationManager.get_instance().unregister_tui(self)
    except Exception:
        pass
    try:
        from app.config import AppSettings

        AppSettings.remove_observer(
            "AI_CONSENT_GRANTED", self._on_ai_consent_changed
        )
    except Exception:
        pass

reset_progress_bar()

Reset progress bar to idle state and hide component.

Source code in app/ui/tui.py
877
878
879
880
881
882
883
884
885
def reset_progress_bar(self) -> None:
    """Reset progress bar to idle state and hide component."""
    try:
        pb = self.query_one("#main-progress-bar", ProgressBar)
        pb.progress = 0.0
        pb.total = 100
        pb.display = False
    except Exception:
        pass

run_undo_worker(session_id, ignore_missing=False, selected_step_ids=None, *, allow_missing=False)

Execute session rollback restoration asynchronously in background worker thread.

Source code in app/ui/tui.py
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
@work(thread=True, group="undo")
def run_undo_worker(
    self,
    session_id: str,
    ignore_missing: bool = False,
    selected_step_ids: list[Any] | None = None,
    *,
    allow_missing: bool = False,
) -> None:
    """Execute session rollback restoration asynchronously in background worker thread."""
    try:
        from app.core.pipeline import SortPipeline

        effective_allow_missing = bool(allow_missing or ignore_missing)
        pipeline = self.pipeline
        if pipeline is None or pipeline.state.is_active:
            pipeline = SortPipeline(
                self.app_session,
                base_dir=self.base_dir,
                settings=self.settings,
            )
            pipeline.add_state_change_hook(self._handle_pipeline_state_transition)
            pipeline.add_telemetry_hook(self._handle_pipeline_telemetry)
            self.pipeline = pipeline

        undo_result = pipeline.undo(
            session_id,
            ignore_missing=effective_allow_missing,
            allow_missing=effective_allow_missing,
            selected_step_ids=selected_step_ids,
        )
        if "error" in undo_result.summary:
            raise RuntimeError(str(undo_result.summary["error"]))
        restored_count = int(
            undo_result.summary.get("restored", len(undo_result.moved))
        )
        trashed_remaining = int(
            undo_result.summary.get("trashed_unrestorable")
            or len(undo_result.trashed)
            or 0
        )
        missing_count = (
            0
            if undo_result.rollback_completed
            else int(undo_result.summary.get("missing_count") or 0)
        )

        if hasattr(self, "call_from_thread"):
            self.call_from_thread(
                self._on_undo_success,
                session_id,
                restored_count,
                trashed_remaining,
                missing_count,
            )
        else:
            self._on_undo_success(
                session_id, restored_count, trashed_remaining, missing_count
            )
    except Exception as err:
        logger.error(f"Error rolling back session {session_id}: {err}")
        if hasattr(self, "call_from_thread"):
            self.call_from_thread(self._on_undo_failure, session_id, err)
        else:
            self._on_undo_failure(session_id, err)

update_status(text=None)

Update status bar label with current message, truthful AI badge, and daemon badge.

Source code in app/ui/tui.py
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
def update_status(self, text: str | None = None) -> None:
    """Update status bar label with current message, truthful AI badge, and daemon badge."""
    try:
        if text is not None:
            import re

            clean_text = str(text)
            clean_text = re.sub(r"^\[AI:[^\]]+\]\s*", "", clean_text)
            for badge_str in (
                "[Daemon: Active]",
                "[Daemon: Paused]",
                "[Daemon: Idle]",
            ):
                if clean_text.startswith(badge_str):
                    clean_text = clean_text[len(badge_str) :].lstrip()
            self._current_status_text = clean_text
        elif not hasattr(self, "_current_status_text"):
            self._current_status_text = (
                "Ready. Press [Ctrl+S] to Scan or [Ctrl+B] to select Directory."
            )

        ai_badge = self._get_ai_status_badge()
        self._last_ai_badge = ai_badge
        daemon_badge = self._get_daemon_status_badge()
        badges = f"{ai_badge} {daemon_badge}"
        full_text = (
            f"{badges} {self._current_status_text}"
            if getattr(self, "_current_status_text", "")
            else badges
        )
        sb = self.query_one("#status-bar", Static)
        sb.update(full_text)
    except Exception:
        pass

run_tui(settings, base_dir=None, skip_wizard=False, non_interactive=False, open_dropzone=False, initial_drop_paths=None, initial_dest_dir=None)

Run the Textual full-screen terminal interface.

Source code in app/ui/tui.py
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
def run_tui(
    settings,
    base_dir: str | None = None,
    skip_wizard: bool = False,
    non_interactive: bool = False,
    open_dropzone: bool = False,
    initial_drop_paths: list[str] | None = None,
    initial_dest_dir: str | None = None,
) -> None:
    """Run the Textual full-screen terminal interface."""
    import shutil

    from app.core.path_utils import is_packaged

    if sys.platform == "win32" and is_packaged():
        if (
            sys.stdin is None
            or not hasattr(sys.stdin, "isatty")
            or not sys.stdin.isatty()
        ):
            from app.frozen_runtime import attach_console

            attach_console()

    if (
        sys.stdin is None
        or not hasattr(sys.stdin, "isatty")
        or not sys.stdin.isatty()
        or (hasattr(sys.stdout, "isatty") and not sys.stdout.isatty())
    ):
        if not os.environ.get("FORCE_TUI"):
            print(
                "Error: Textual TUI requires an interactive TTY terminal environment.",
                file=sys.stderr,
            )
            sys.exit(1)

    cols, lines = shutil.get_terminal_size((80, 24))
    if (cols < 80 or lines < 24) and not os.environ.get("IGNORE_TERMINAL_SIZE"):
        print(
            f"Error: Terminal dimensions ({cols}x{lines}) are below minimum requirement (80x24). "
            "Please resize your terminal window.",
            file=sys.stderr,
        )
        sys.exit(1)

    _start_multiprocessing_resource_tracker()

    app = AutoSorterTUI(
        settings=settings,
        base_dir=base_dir,
        skip_wizard=skip_wizard,
        non_interactive=non_interactive,
        open_dropzone=open_dropzone,
        initial_drop_paths=initial_drop_paths,
        initial_dest_dir=initial_dest_dir,
    )
    app.run()

app.ui.widgets.density_slider

app.ui.widgets.density_slider

Keyboard slider for choosing the layout density.

DensitySlider

Bases: A11yMixin, Widget

Interactive slider widget for text density threshold adjustment.

Source code in app/ui/widgets/density_slider.py
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
class DensitySlider(A11yMixin, Widget):
    """Interactive slider widget for text density threshold adjustment."""

    can_focus = True
    value = reactive(50)

    DEFAULT_CSS = """
    DensitySlider {
        width: 100%;
        height: 1;
        margin-top: 1;
        margin-bottom: 1;
    }
    DensitySlider:focus {
        color: $accent;
        text-style: bold;
    }
    """

    class Changed(Message):
        """Event posted when slider value changes."""

        def __init__(self, slider: "DensitySlider", value: int) -> None:
            self.slider = slider
            self.value = value
            super().__init__()

        @property
        def control(self) -> Widget:
            """Return control widget associated with this message."""
            return self.slider

    def __init__(
        self,
        value: int = 50,
        min_value: int = 0,
        max_value: int = 500,
        step: int = 5,
        announce_formatter: Callable[[int], str] | None = None,
        *,
        name: str | None = None,
        id: str | None = None,
        classes: str | None = None,
        disabled: bool = False,
    ) -> None:
        super().__init__(name=name, id=id, classes=classes, disabled=disabled)
        self.min_value = min_value
        self.max_value = max_value
        self.step = step
        self.announce_formatter = announce_formatter
        self._last_announce_time: float = 0.0
        self.tooltip = "Adjust PDF text density threshold slider"
        # set_reactive avoids a pre-mount watcher firing with the class default.
        self.set_reactive(DensitySlider.value, max(min_value, min(max_value, value)))

    def _announce_value(self, value: int, force: bool = False) -> str | None:
        """Rate-limited screen reader announcement helper."""
        if self.announce_formatter is not None:
            try:
                msg = self.announce_formatter(value)
            except Exception:  # noqa: BLE001
                msg = f"Density threshold set to {value}"
        else:
            msg = f"Density threshold set to {value}"

        now = time.time()
        if force or (now - self._last_announce_time >= 0.25):
            self._last_announce_time = now
            return self.announce(msg)
        else:
            self.update_status(msg)
            return None

    def watch_value(self, new_value: int) -> None:
        """Emit Changed event on value change."""
        self.post_message(self.Changed(self, new_value))
        self._announce_value(new_value)

    def on_key(self, event: events.Key) -> None:
        """Handle keyboard key events to update slider position."""
        if event.key in ("left", "down"):
            self.value = max(self.min_value, self.value - self.step)
            event.stop()
        elif event.key in ("right", "up"):
            self.value = min(self.max_value, self.value + self.step)
            event.stop()
        elif event.key == "page_down":
            self.value = max(self.min_value, self.value - self.step * 5)
            event.stop()
        elif event.key == "page_up":
            self.value = min(self.max_value, self.value + self.step * 5)
            event.stop()
        elif event.key == "home":
            self.value = self.min_value
            event.stop()
        elif event.key == "end":
            self.value = self.max_value
            event.stop()

    def on_click(self, event: events.Click) -> None:
        """Handle mouse click to jump slider to position."""
        width = self.size.width
        if width > 0:
            pct = max(0.0, min(1.0, event.x / float(width)))
            new_val = self.min_value + int(pct * (self.max_value - self.min_value))
            rem = new_val % self.step
            if rem != 0:
                new_val = new_val - rem + (self.step if rem >= self.step / 2 else 0)
            self.value = max(self.min_value, min(self.max_value, new_val))

    def render(self) -> str:
        """Render visual slider bar string representation."""
        width = max(10, self.size.width - 8) if self.size.width > 8 else 20
        pct = (self.value - self.min_value) / max(1, (self.max_value - self.min_value))
        pos = int(pct * (width - 1))
        pos = max(0, min(width - 1, pos))
        bar = "━" * pos + "●" + "─" * (width - 1 - pos)
        return f"[{bar}] {self.value}"

Changed

Bases: Message

Event posted when slider value changes.

Source code in app/ui/widgets/density_slider.py
33
34
35
36
37
38
39
40
41
42
43
44
class Changed(Message):
    """Event posted when slider value changes."""

    def __init__(self, slider: "DensitySlider", value: int) -> None:
        self.slider = slider
        self.value = value
        super().__init__()

    @property
    def control(self) -> Widget:
        """Return control widget associated with this message."""
        return self.slider
control property

Return control widget associated with this message.

on_click(event)

Handle mouse click to jump slider to position.

Source code in app/ui/widgets/density_slider.py
113
114
115
116
117
118
119
120
121
122
def on_click(self, event: events.Click) -> None:
    """Handle mouse click to jump slider to position."""
    width = self.size.width
    if width > 0:
        pct = max(0.0, min(1.0, event.x / float(width)))
        new_val = self.min_value + int(pct * (self.max_value - self.min_value))
        rem = new_val % self.step
        if rem != 0:
            new_val = new_val - rem + (self.step if rem >= self.step / 2 else 0)
        self.value = max(self.min_value, min(self.max_value, new_val))

on_key(event)

Handle keyboard key events to update slider position.

Source code in app/ui/widgets/density_slider.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def on_key(self, event: events.Key) -> None:
    """Handle keyboard key events to update slider position."""
    if event.key in ("left", "down"):
        self.value = max(self.min_value, self.value - self.step)
        event.stop()
    elif event.key in ("right", "up"):
        self.value = min(self.max_value, self.value + self.step)
        event.stop()
    elif event.key == "page_down":
        self.value = max(self.min_value, self.value - self.step * 5)
        event.stop()
    elif event.key == "page_up":
        self.value = min(self.max_value, self.value + self.step * 5)
        event.stop()
    elif event.key == "home":
        self.value = self.min_value
        event.stop()
    elif event.key == "end":
        self.value = self.max_value
        event.stop()

render()

Render visual slider bar string representation.

Source code in app/ui/widgets/density_slider.py
124
125
126
127
128
129
130
131
def render(self) -> str:
    """Render visual slider bar string representation."""
    width = max(10, self.size.width - 8) if self.size.width > 8 else 20
    pct = (self.value - self.min_value) / max(1, (self.max_value - self.min_value))
    pos = int(pct * (width - 1))
    pos = max(0, min(width - 1, pos))
    bar = "━" * pos + "●" + "─" * (width - 1 - pos)
    return f"[{bar}] {self.value}"

watch_value(new_value)

Emit Changed event on value change.

Source code in app/ui/widgets/density_slider.py
87
88
89
90
def watch_value(self, new_value: int) -> None:
    """Emit Changed event on value change."""
    self.post_message(self.Changed(self, new_value))
    self._announce_value(new_value)

app.ui.widgets.labeled_switch

app.ui.widgets.labeled_switch

A switch with a visible label and screen-reader announcements.

LabeledSwitch

Bases: Horizontal

A horizontal container combining a Switch and an associated Label with container-level click delegation.

Source code in app/ui/widgets/labeled_switch.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
class LabeledSwitch(Horizontal):
    """A horizontal container combining a Switch and an associated Label with container-level click delegation."""

    DEFAULT_CSS = """
    LabeledSwitch {
        margin-top: 1;
        margin-bottom: 1;
        height: 3;
        align: left middle;
    }
    """

    def __init__(
        self,
        label: str,
        value: bool = False,
        switch_id: str | None = None,
        tooltip: str | None = None,
        *,
        name: str | None = None,
        id: str | None = None,
        classes: str | None = None,
        disabled: bool = False,
    ) -> None:
        cls_list = ["switch-row"]
        if classes:
            cls_list.append(classes)
        super().__init__(
            name=name,
            id=id,
            classes=" ".join(cls_list),
            disabled=disabled,
        )
        self.label_text = label
        effective_switch_id = switch_id or (
            id if id and id.startswith("switch-") else None
        )
        self.switch = Switch(value=value, id=effective_switch_id, disabled=disabled)
        if tooltip:
            self.tooltip = tooltip
            self.switch.tooltip = tooltip
        formatted_label = label if label.startswith(" ") else f" {label}"
        self.label_widget = Label(formatted_label)

    def compose(self) -> ComposeResult:
        """Yield child Switch and Label controls."""
        yield self.switch
        yield self.label_widget

    @property
    def value(self) -> bool:
        """Get the underlying switch value."""
        return self.switch.value

    @value.setter
    def value(self, val: bool) -> None:
        """Set the underlying switch value."""
        self.switch.value = val

    def _is_switch_target(self, target: Any) -> bool:
        """Check if target widget is the child switch or contained within it."""
        if target is None:
            return False
        curr = target
        while curr is not None and curr is not self:
            if curr is self.switch:
                return True
            curr = getattr(curr, "parent", None)
        return False

    def on_click(self, event: events.Click) -> None:
        """Handle mouse click events on container or label by toggling and focusing the switch."""
        if self.disabled or self.switch.disabled:
            return

        target_widget = getattr(event, "widget", getattr(event, "control", None))
        if not self._is_switch_target(target_widget):
            self.switch.value = not self.switch.value
            self.switch.focus()
            event.stop()
        else:
            self.switch.focus()

value property writable

Get the underlying switch value.

compose()

Yield child Switch and Label controls.

Source code in app/ui/widgets/labeled_switch.py
55
56
57
58
def compose(self) -> ComposeResult:
    """Yield child Switch and Label controls."""
    yield self.switch
    yield self.label_widget

on_click(event)

Handle mouse click events on container or label by toggling and focusing the switch.

Source code in app/ui/widgets/labeled_switch.py
81
82
83
84
85
86
87
88
89
90
91
92
def on_click(self, event: events.Click) -> None:
    """Handle mouse click events on container or label by toggling and focusing the switch."""
    if self.disabled or self.switch.disabled:
        return

    target_widget = getattr(event, "widget", getattr(event, "control", None))
    if not self._is_switch_target(target_widget):
        self.switch.value = not self.switch.value
        self.switch.focus()
        event.stop()
    else:
        self.switch.focus()

app.ui.widgets.path_diff

app.ui.widgets.path_diff

Side-by-side path comparisons with the changed segments highlighted.

format_folder_path_comparison(files_info, base_dir=None, max_items=8)

Render side-by-side path comparison table for items in a folder subtree.

Source code in app/ui/widgets/path_diff.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def format_folder_path_comparison(
    files_info: list[dict[str, Any]],
    base_dir: str | None = None,
    max_items: int = 8,
) -> Table:
    """Render side-by-side path comparison table for items in a folder subtree."""
    table = Table(
        expand=True,
        show_header=True,
        header_style="bold cyan",
        box=None,
    )
    table.add_column("Source Path (Current)", style="bold", ratio=1)
    table.add_column("Target Path (Proposed)", style="bold", ratio=1)

    if not files_info:
        table.add_row(
            Text("No files in folder", style="dim"),
            Text("No files in folder", style="dim"),
        )
        return table

    for fi in files_info[:max_items]:
        src_path = fi.get("filepath", "")
        key = fi.get("key") or fi.get("target_filename") or ""
        folder = fi.get("folder", "")
        target_fn = fi.get("target_filename") or key
        tgt_rel = (
            os.path.join(folder, target_fn).replace("\\", "/")
            if folder and folder != "(Root)"
            else target_fn
        )

        src_rel = src_path
        if base_dir and src_path:
            base_norm = base_dir.replace("\\", "/").rstrip("/") + "/"
            src_norm = src_path.replace("\\", "/")
            if src_norm.lower().startswith(base_norm.lower()):
                src_rel = src_norm[len(base_norm) :]

        src_fmt, tgt_fmt = _diff_highlight_paths(src_rel, tgt_rel)
        table.add_row(src_fmt, tgt_fmt)

    if len(files_info) > max_items:
        remaining = len(files_info) - max_items
        table.add_row(
            Text(f"... and {remaining} more items", style="dim italic"),
            Text(f"... and {remaining} more items", style="dim italic"),
        )

    return table

format_side_by_side_path_comparison(source_path, target_path, base_dir=None)

Render split side-by-side columns comparing source and target paths with contrasting color diffs.

Source code in app/ui/widgets/path_diff.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def format_side_by_side_path_comparison(
    source_path: str,
    target_path: str,
    base_dir: str | None = None,
) -> Table:
    """Render split side-by-side columns comparing source and target paths with contrasting color diffs."""
    table = Table(
        expand=True,
        show_header=True,
        header_style="bold cyan",
        box=None,
    )
    table.add_column("Source Path (Current)", style="bold", ratio=1)
    table.add_column("Target Path (Proposed)", style="bold", ratio=1)

    src_norm = source_path.replace("\\", "/") if source_path else ""
    tgt_norm = target_path.replace("\\", "/") if target_path else ""

    base_norm = base_dir.replace("\\", "/") if base_dir else ""
    if base_norm and not base_norm.endswith("/"):
        base_norm += "/"

    src_rel = (
        src_norm[len(base_norm) :]
        if base_norm and src_norm.lower().startswith(base_norm.lower())
        else src_norm
    )
    tgt_rel = (
        tgt_norm[len(base_norm) :]
        if base_norm and tgt_norm.lower().startswith(base_norm.lower())
        else tgt_norm
    )

    src_rel_fmt, tgt_rel_fmt = _diff_highlight_paths(src_rel, tgt_rel)
    table.add_row(src_rel_fmt, tgt_rel_fmt)

    if base_norm and (src_norm != src_rel or tgt_norm != tgt_rel):
        src_full_fmt, tgt_full_fmt = _diff_highlight_paths(src_norm, tgt_norm)
        table.add_row(src_full_fmt, tgt_full_fmt)

    return table

app.ui.widgets.vim_tree

app.ui.widgets.vim_tree

Tree widget with vim-style key navigation.

VimTree

Bases: Tree

Tree control with native vim motion navigation (h, j, k, l).

Source code in app/ui/widgets/vim_tree.py
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
class VimTree(Tree):
    """Tree control with native vim motion navigation (h, j, k, l)."""

    def _character_shortcuts_enabled(self) -> bool:
        """Check whether single-character keyboard shortcuts are enabled."""
        settings = getattr(getattr(self, "app", None), "settings", None)
        if settings is None:
            return True
        return bool(getattr(settings, "ENABLE_CHARACTER_KEY_SHORTCUTS", True))

    def on_key(self, event: events.Key) -> None:
        """Handle key events for native vim tree navigation."""
        if not self.has_focus:
            return

        char_shortcuts_enabled = self._character_shortcuts_enabled()

        reg_fn = getattr(self.app, "register_visual_selected_node", None)
        refresh_fn = getattr(self.app, "refresh_tree_selection_markers", None)
        extend_shift_fn = getattr(self.app, "extend_shift_range_selection", None)

        if event.key == "j":
            anchor = self.cursor_node
            if (
                getattr(self.app, "visual_select_active", False)
                and anchor
                and callable(reg_fn)
            ):
                reg_fn(anchor)
            self.action_cursor_down()
            if (
                getattr(self.app, "visual_select_active", False)
                and self.cursor_node
                and callable(reg_fn)
            ):
                reg_fn(self.cursor_node)
                if callable(refresh_fn):
                    refresh_fn()
            event.stop()
            event.prevent_default()
        elif event.key == "k":
            anchor = self.cursor_node
            if (
                getattr(self.app, "visual_select_active", False)
                and anchor
                and callable(reg_fn)
            ):
                reg_fn(anchor)
            self.action_cursor_up()
            if (
                getattr(self.app, "visual_select_active", False)
                and self.cursor_node
                and callable(reg_fn)
            ):
                reg_fn(self.cursor_node)
                if callable(refresh_fn):
                    refresh_fn()
            event.stop()
            event.prevent_default()
        elif event.key == "down" and getattr(self.app, "visual_select_active", False):
            anchor = self.cursor_node
            if anchor and callable(reg_fn):
                reg_fn(anchor)
            self.action_cursor_down()
            if self.cursor_node and callable(reg_fn):
                reg_fn(self.cursor_node)
            if callable(refresh_fn):
                refresh_fn()
            event.stop()
            event.prevent_default()
        elif event.key == "up" and getattr(self.app, "visual_select_active", False):
            anchor = self.cursor_node
            if anchor and callable(reg_fn):
                reg_fn(anchor)
            self.action_cursor_up()
            if self.cursor_node and callable(reg_fn):
                reg_fn(self.cursor_node)
            if callable(refresh_fn):
                refresh_fn()
            event.stop()
            event.prevent_default()
        elif event.key == "shift+down":
            anchor = self.cursor_node
            self.action_cursor_down()
            if callable(extend_shift_fn):
                extend_shift_fn(anchor, self.cursor_node)
            event.stop()
            event.prevent_default()
        elif event.key == "shift+up":
            anchor = self.cursor_node
            self.action_cursor_up()
            if callable(extend_shift_fn):
                extend_shift_fn(anchor, self.cursor_node)
            event.stop()
            event.prevent_default()
        elif event.key == "h":
            node = self.cursor_node
            if node:
                if node.is_expanded and node.children:
                    node.collapse()
                else:
                    self.action_cursor_parent()
            event.stop()
            event.prevent_default()
        elif event.key == "l":
            node = self.cursor_node
            if node:
                if not node.is_expanded and (node.children or node.allow_expand):
                    node.expand()
                elif node.is_expanded and node.children:
                    self.action_cursor_down()
            event.stop()
            event.prevent_default()
        elif event.key in ("space", " "):
            action = getattr(self.app, "action_toggle_selection", None)
            if char_shortcuts_enabled and callable(action):
                action()
            event.stop()
            event.prevent_default()
        elif event.key in ("x", "X"):
            action = getattr(self.app, "action_exclude_selected", None)
            if char_shortcuts_enabled and callable(action):
                action()
            event.stop()
            event.prevent_default()
        elif event.key in ("i", "I"):
            action = getattr(self.app, "action_include_selected", None)
            if char_shortcuts_enabled and callable(action):
                action()
            event.stop()
            event.prevent_default()
        elif event.key in ("r", "R"):
            action = getattr(self.app, "action_reassign_selected", None)
            if char_shortcuts_enabled and callable(action):
                action()
            event.stop()
            event.prevent_default()
        elif event.key in ("v", "V"):
            action = getattr(self.app, "action_visual_range_select", None)
            if char_shortcuts_enabled and callable(action):
                action()
            event.stop()
            event.prevent_default()
        elif event.key in ("a", "A"):
            action = getattr(self.app, "action_toggle_select_all", None)
            if char_shortcuts_enabled and callable(action):
                action()
            event.stop()
            event.prevent_default()
        elif event.key in ("g", "G", "shift+g"):
            action = getattr(self.app, "action_generate_sample_corpus", None)
            if char_shortcuts_enabled and callable(action):
                action(True)
            event.stop()
            event.prevent_default()
        elif event.key in ("d", "D", "shift+d"):
            action = getattr(self.app, "action_scan_subfolders", None)
            if char_shortcuts_enabled and callable(action):
                action(True)
            event.stop()
            event.prevent_default()
        elif event.key in ("plus", "+"):
            action = getattr(self.app, "action_rate_positive", None)
            if char_shortcuts_enabled and callable(action):
                action()
            event.stop()
            event.prevent_default()
        elif event.key in ("minus", "-"):
            action = getattr(self.app, "action_rate_negative", None)
            if char_shortcuts_enabled and callable(action):
                action()
            event.stop()
            event.prevent_default()
        elif event.key in ("question_mark", "?"):
            action = getattr(self.app, "action_open_cheat_sheet", None)
            if char_shortcuts_enabled and callable(action):
                action()
            event.stop()
            event.prevent_default()
        elif event.key in ("/", "slash") or getattr(event, "character", None) == "/":
            action = getattr(self.app, "action_focus_search", None)
            if char_shortcuts_enabled and callable(action):
                action()
            event.stop()
            event.prevent_default()
        elif event.key in ("enter", "return"):
            node = self.cursor_node
            if node:
                if node.children or node.allow_expand:
                    node.toggle()
                else:
                    self.select_node(node)
            event.stop()
            event.prevent_default()

on_key(event)

Handle key events for native vim tree navigation.

Source code in app/ui/widgets/vim_tree.py
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def on_key(self, event: events.Key) -> None:
    """Handle key events for native vim tree navigation."""
    if not self.has_focus:
        return

    char_shortcuts_enabled = self._character_shortcuts_enabled()

    reg_fn = getattr(self.app, "register_visual_selected_node", None)
    refresh_fn = getattr(self.app, "refresh_tree_selection_markers", None)
    extend_shift_fn = getattr(self.app, "extend_shift_range_selection", None)

    if event.key == "j":
        anchor = self.cursor_node
        if (
            getattr(self.app, "visual_select_active", False)
            and anchor
            and callable(reg_fn)
        ):
            reg_fn(anchor)
        self.action_cursor_down()
        if (
            getattr(self.app, "visual_select_active", False)
            and self.cursor_node
            and callable(reg_fn)
        ):
            reg_fn(self.cursor_node)
            if callable(refresh_fn):
                refresh_fn()
        event.stop()
        event.prevent_default()
    elif event.key == "k":
        anchor = self.cursor_node
        if (
            getattr(self.app, "visual_select_active", False)
            and anchor
            and callable(reg_fn)
        ):
            reg_fn(anchor)
        self.action_cursor_up()
        if (
            getattr(self.app, "visual_select_active", False)
            and self.cursor_node
            and callable(reg_fn)
        ):
            reg_fn(self.cursor_node)
            if callable(refresh_fn):
                refresh_fn()
        event.stop()
        event.prevent_default()
    elif event.key == "down" and getattr(self.app, "visual_select_active", False):
        anchor = self.cursor_node
        if anchor and callable(reg_fn):
            reg_fn(anchor)
        self.action_cursor_down()
        if self.cursor_node and callable(reg_fn):
            reg_fn(self.cursor_node)
        if callable(refresh_fn):
            refresh_fn()
        event.stop()
        event.prevent_default()
    elif event.key == "up" and getattr(self.app, "visual_select_active", False):
        anchor = self.cursor_node
        if anchor and callable(reg_fn):
            reg_fn(anchor)
        self.action_cursor_up()
        if self.cursor_node and callable(reg_fn):
            reg_fn(self.cursor_node)
        if callable(refresh_fn):
            refresh_fn()
        event.stop()
        event.prevent_default()
    elif event.key == "shift+down":
        anchor = self.cursor_node
        self.action_cursor_down()
        if callable(extend_shift_fn):
            extend_shift_fn(anchor, self.cursor_node)
        event.stop()
        event.prevent_default()
    elif event.key == "shift+up":
        anchor = self.cursor_node
        self.action_cursor_up()
        if callable(extend_shift_fn):
            extend_shift_fn(anchor, self.cursor_node)
        event.stop()
        event.prevent_default()
    elif event.key == "h":
        node = self.cursor_node
        if node:
            if node.is_expanded and node.children:
                node.collapse()
            else:
                self.action_cursor_parent()
        event.stop()
        event.prevent_default()
    elif event.key == "l":
        node = self.cursor_node
        if node:
            if not node.is_expanded and (node.children or node.allow_expand):
                node.expand()
            elif node.is_expanded and node.children:
                self.action_cursor_down()
        event.stop()
        event.prevent_default()
    elif event.key in ("space", " "):
        action = getattr(self.app, "action_toggle_selection", None)
        if char_shortcuts_enabled and callable(action):
            action()
        event.stop()
        event.prevent_default()
    elif event.key in ("x", "X"):
        action = getattr(self.app, "action_exclude_selected", None)
        if char_shortcuts_enabled and callable(action):
            action()
        event.stop()
        event.prevent_default()
    elif event.key in ("i", "I"):
        action = getattr(self.app, "action_include_selected", None)
        if char_shortcuts_enabled and callable(action):
            action()
        event.stop()
        event.prevent_default()
    elif event.key in ("r", "R"):
        action = getattr(self.app, "action_reassign_selected", None)
        if char_shortcuts_enabled and callable(action):
            action()
        event.stop()
        event.prevent_default()
    elif event.key in ("v", "V"):
        action = getattr(self.app, "action_visual_range_select", None)
        if char_shortcuts_enabled and callable(action):
            action()
        event.stop()
        event.prevent_default()
    elif event.key in ("a", "A"):
        action = getattr(self.app, "action_toggle_select_all", None)
        if char_shortcuts_enabled and callable(action):
            action()
        event.stop()
        event.prevent_default()
    elif event.key in ("g", "G", "shift+g"):
        action = getattr(self.app, "action_generate_sample_corpus", None)
        if char_shortcuts_enabled and callable(action):
            action(True)
        event.stop()
        event.prevent_default()
    elif event.key in ("d", "D", "shift+d"):
        action = getattr(self.app, "action_scan_subfolders", None)
        if char_shortcuts_enabled and callable(action):
            action(True)
        event.stop()
        event.prevent_default()
    elif event.key in ("plus", "+"):
        action = getattr(self.app, "action_rate_positive", None)
        if char_shortcuts_enabled and callable(action):
            action()
        event.stop()
        event.prevent_default()
    elif event.key in ("minus", "-"):
        action = getattr(self.app, "action_rate_negative", None)
        if char_shortcuts_enabled and callable(action):
            action()
        event.stop()
        event.prevent_default()
    elif event.key in ("question_mark", "?"):
        action = getattr(self.app, "action_open_cheat_sheet", None)
        if char_shortcuts_enabled and callable(action):
            action()
        event.stop()
        event.prevent_default()
    elif event.key in ("/", "slash") or getattr(event, "character", None) == "/":
        action = getattr(self.app, "action_focus_search", None)
        if char_shortcuts_enabled and callable(action):
            action()
        event.stop()
        event.prevent_default()
    elif event.key in ("enter", "return"):
        node = self.cursor_node
        if node:
            if node.children or node.allow_expand:
                node.toggle()
            else:
                self.select_node(node)
        event.stop()
        event.prevent_default()