cmux/tests/test_markdown_open_regressions.py
Ismail Pelaseyed d72b014d6d
feat: add markdown viewer panel with live file watching (#883)
* Add markdown viewer panel with live file watching

Introduce a new PanelType.markdown that renders .md files in a dedicated
panel using MarkdownUI (SwiftUI), with live file watching via DispatchSource
so content auto-updates when the file changes on disk.

- New MarkdownPanel class with file system watcher (write/delete/rename/extend)
- New MarkdownPanelView with custom cmux theme (headings, code blocks, tables,
  blockquotes, inline code, lists, horizontal rules, light/dark mode)
- Full workspace integration: SurfaceKind, creation methods, tab subscription
- Session persistence: snapshot/restore across app restarts
- V2 socket command: markdown.open (validates path, resolves workspace, splits)
- CLI command: cmux markdown open <path> with routing flags and help text
- Agent skill: skills/cmux-markdown/ with SKILL.md, openai.yaml, and references
- Cross-link from skills/cmux/SKILL.md to the new markdown skill
- SPM dependency: gonzalezreal/swift-markdown-ui 2.4.1

* Fix unreachable guard in markdown subcommand dispatch

Use looksLikePath() to distinguish subcommands from path arguments
so the guard can catch unknown subcommands and future subcommands
are parsed correctly.

* Use .isoLatin1 fallback instead of .ascii for encoding recovery

ASCII is a strict subset of UTF-8, so falling back to .ascii after
UTF-8 fails is dead code. Use .isoLatin1 which accepts all 256 byte
values and covers legacy encodings like Windows-1252.

* Mark fileWatchSource as nonisolated(unsafe) for deinit safety

deinit is not guaranteed to run on the main actor, so accessing
@MainActor-isolated storage is a data race under strict concurrency.
DispatchSource.cancel() is thread-safe, so nonisolated(unsafe) is
sufficient with a documented invariant that writes only occur on main.

* Fix file watcher reattach: retry loop with cancellation guard

- Replace one-shot 500ms retry with up to 6 attempts (3s total window)
  so files that reappear after a slow atomic replace are picked up
- Add isClosed flag checked before each retry to prevent restarting
  the watcher after close()/deinit

* Harden path validation in markdown.open command

Reject directories and non-absolute paths before panel creation
to prevent ambiguous behavior and generic downstream failures.

* Always reattach file watcher on delete/rename events

After an atomic save (delete old + create new), the DispatchSource still
points to the old inode. Previously we only reattached when the file was
unreadable, so successful atomic saves left the watcher on a stale inode
and live updates silently stopped. Now we always stop and reattach:
immediately if the new file is readable, via retry loop if not.

* Restore markdown panels even when file is missing at launch

MarkdownPanel already handles unavailable files gracefully (shows
'file unavailable' UI and retries via the reattach loop). Dropping
the panel on restore lost the user's layout for files that may
reappear shortly after (network drives, build artifacts, etc.).

* Harden markdown CLI parsing and startup reconnect behavior

---------

Co-authored-by: Lawrence Chen <54008264+lawrencecchen@users.noreply.github.com>
2026-03-04 17:48:28 -08:00

126 lines
3.7 KiB
Python

#!/usr/bin/env python3
"""Regression tests for markdown-open CLI parsing/help behavior."""
from __future__ import annotations
import subprocess
from pathlib import Path
def get_repo_root() -> Path:
result = subprocess.run(
["git", "rev-parse", "--show-toplevel"],
capture_output=True,
text=True,
check=False,
)
if result.returncode == 0:
return Path(result.stdout.strip())
return Path.cwd()
def require(content: str, needle: str, message: str, failures: list[str]) -> None:
if needle not in content:
failures.append(message)
def main() -> int:
repo_root = get_repo_root()
cli_path = repo_root / "CLI" / "cmux.swift"
panel_path = repo_root / "Sources" / "Panels" / "MarkdownPanel.swift"
if not cli_path.exists():
print(f"FAIL: missing expected file: {cli_path}")
return 1
if not panel_path.exists():
print(f"FAIL: missing expected file: {panel_path}")
return 1
cli_content = cli_path.read_text(encoding="utf-8")
panel_content = panel_path.read_text(encoding="utf-8")
failures: list[str] = []
# CLI parser behavior.
require(
cli_content,
'if let first = args.first, first.lowercased() == "open" {',
"markdown parser should explicitly support the 'open' subcommand",
failures,
)
require(
cli_content,
"args.count == 1",
"markdown parser should accept single-arg shorthand path",
failures,
)
require(
cli_content,
"args.count == 1, let first = args.first, !first.hasPrefix(\"-\")",
"markdown parser should reject option-like single args from shorthand path mode",
failures,
)
require(
cli_content,
"let trailingArgs = Array(subArgs.dropFirst())",
"markdown parser should validate trailing arguments",
failures,
)
require(
cli_content,
'trailingArgs.first(where: { $0.hasPrefix("-") })',
"markdown parser should detect unknown trailing flags",
failures,
)
require(
cli_content,
"markdown open: unexpected argument",
"markdown parser should error on unexpected trailing args",
failures,
)
# Help text should document shorthand and full index handle support.
require(
cli_content,
"Usage: cmux markdown open <path> [options]\n cmux markdown <path> (shorthand for 'open')",
"markdown subcommand help should include shorthand usage",
failures,
)
require(
cli_content,
"--window <id|ref|index> Target window",
"markdown subcommand help should document window index handles",
failures,
)
require(
cli_content,
"markdown [open] <path> (open markdown file in formatted viewer panel with live reload)",
"top-level help should include markdown shorthand syntax",
failures,
)
# Session restore edge case: file missing at startup should still attempt reconnect.
require(
panel_content,
"if isFileUnavailable && fileWatchSource == nil {",
"MarkdownPanel should schedule reattach when watcher cannot start at init",
failures,
)
require(
panel_content,
"scheduleReattach(attempt: 1)",
"MarkdownPanel should trigger reattach retries for missing files",
failures,
)
if failures:
print("FAIL: markdown-open regression(s) detected")
for failure in failures:
print(f"- {failure}")
return 1
print("PASS: markdown-open CLI/help/reattach regression checks are present")
return 0
if __name__ == "__main__":
raise SystemExit(main())