-
Notifications
You must be signed in to change notification settings - Fork 170
feat(capture): add S1 app parser registry with golden fixture tests #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
heming-gmh
wants to merge
2
commits into
Einsia:main
Choose a base branch
from
heming-gmh:feat/s1-parser-registry-golden-tests
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| """S1 app parser registry. | ||
|
|
||
| Parsers are registered at import time and run in priority order during | ||
| :func:`apply_parsers`. Later parsers can match on fields produced by | ||
| earlier parsers (e.g. a Linear parser matching ``fields.url`` that | ||
| contains ``linear.app``, which was extracted by the browser parser). | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from ...logger import get | ||
| from .base import AppParser, ParseContext, S1Fields | ||
| from .browser import BrowserParser | ||
|
|
||
| logger = get("openchronicle.capture.s1_registry") | ||
|
|
||
| _parsers: list[AppParser] = [] | ||
|
|
||
|
|
||
| def _register_builtins() -> None: | ||
| register(BrowserParser()) | ||
|
|
||
|
|
||
| def register(parser: AppParser) -> None: | ||
| _parsers.append(parser) | ||
| _parsers.sort(key=lambda p: p.priority) | ||
|
|
||
|
|
||
| def _reset_registry() -> None: | ||
| """Clear all registered parsers and re-register builtins. | ||
|
|
||
| Intended for test isolation so registry mutations in one test | ||
| do not leak into another. | ||
| """ | ||
| _parsers.clear() | ||
| _register_builtins() | ||
|
|
||
|
|
||
| def apply_parsers(ctx: ParseContext, fields: S1Fields) -> None: | ||
| for parser in _parsers: | ||
| try: | ||
| if parser.matches(ctx, fields): | ||
| patch = parser.parse(ctx, fields) | ||
| if patch.focused_element is not None: | ||
| fields.focused_element = patch.focused_element | ||
| if patch.visible_text is not None: | ||
| fields.visible_text = patch.visible_text | ||
| if patch.url is not None: | ||
| fields.url = patch.url | ||
| if patch.app_context: | ||
| fields.app_context = {**fields.app_context, **patch.app_context} | ||
| except Exception: | ||
| logger.exception("S1 parser %r failed", parser.name) | ||
|
|
||
|
|
||
| _register_builtins() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| """Base types for the S1 app parser registry. | ||
|
|
||
| Every app-specific parser implements the :class:`AppParser` protocol. | ||
| The :class:`ParseContext` gives parsers read-only access to the raw | ||
| capture data; :class:`S1Fields` holds the current state; and | ||
| :class:`S1Patch` lets a parser selectively override fields. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import asdict, dataclass, field | ||
| from typing import Any, Iterable, Protocol | ||
|
|
||
|
|
||
| @dataclass | ||
| class FocusedElement: | ||
| role: str = "" | ||
| title: str = "" | ||
| value: str = "" | ||
| is_editable: bool = False | ||
| has_value: bool = False | ||
| value_length: int = 0 | ||
|
|
||
| def to_dict(self) -> dict[str, Any]: | ||
| d = asdict(self) | ||
| stripped = (self.value or "").strip() | ||
| d["has_value"] = bool(stripped) | ||
| d["value_length"] = len(stripped) | ||
| return d | ||
|
|
||
|
|
||
| @dataclass | ||
| class ParseContext: | ||
| """Read-only view of the raw capture data for a parser.""" | ||
|
|
||
| capture: dict[str, Any] | ||
| app: dict[str, Any] | ||
| window_meta: dict[str, Any] | ||
|
|
||
| @property | ||
| def bundle_id(self) -> str: | ||
| return (self.app.get("bundle_id") or "").strip() | ||
|
|
||
| @property | ||
| def app_name(self) -> str: | ||
| return (self.app.get("name") or "").strip() | ||
|
|
||
| def iter_windows(self) -> Iterable[dict[str, Any]]: | ||
| return iter(self.app.get("windows", [])) | ||
|
|
||
| def focused_window(self) -> dict[str, Any] | None: | ||
| for w in self.app.get("windows", []): | ||
| if w.get("focused"): | ||
| return w | ||
| return None | ||
|
|
||
| def iter_elements(self) -> Iterable[dict[str, Any]]: | ||
| """Iterate top-level elements across all windows.""" | ||
| for window in self.app.get("windows", []): | ||
| yield from window.get("elements", []) | ||
|
|
||
|
|
||
| @dataclass | ||
| class S1Fields: | ||
| focused_element: FocusedElement | ||
| visible_text: str | ||
| url: str | None = None | ||
| app_context: dict[str, Any] = field(default_factory=dict) | ||
|
|
||
|
|
||
| @dataclass | ||
| class S1Patch: | ||
| focused_element: FocusedElement | None = None | ||
| visible_text: str | None = None | ||
| url: str | None = None | ||
| app_context: dict[str, Any] = field(default_factory=dict) | ||
|
|
||
|
|
||
| class AppParser(Protocol): | ||
| """Protocol for app-specific S1 field parsers. | ||
|
|
||
| .. warning:: | ||
|
|
||
| ``matches()`` and ``parse()`` **must not** call ``register()``. | ||
| Doing so mutates the parser list while ``apply_parsers()`` is | ||
| iterating and will raise a ``RuntimeError``. | ||
| """ | ||
|
|
||
| name: str | ||
| priority: int | ||
|
|
||
| def matches(self, ctx: ParseContext, fields: S1Fields) -> bool: ... | ||
|
|
||
| def parse(self, ctx: ParseContext, fields: S1Fields) -> S1Patch: ... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| """Browser URL extraction parser. | ||
|
|
||
| Migrated from ``s1_parser._extract_url``. Matches known browser | ||
| bundle IDs and extracts the URL from the first ``AXTextField`` whose | ||
| value looks like a URL or bare domain. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import re | ||
| from typing import Any | ||
|
|
||
| from .base import ParseContext, S1Fields, S1Patch | ||
|
|
||
| _BROWSER_BUNDLES = { | ||
| "com.google.Chrome", | ||
| "com.apple.Safari", | ||
| "org.mozilla.firefox", | ||
| "com.microsoft.edgemac", | ||
| "company.thebrowser.Browser", | ||
| "com.brave.Browser", | ||
| "com.operasoftware.Opera", | ||
| } | ||
|
|
||
| _URL_RE = re.compile(r"https?://\S+") | ||
|
|
||
|
|
||
| class BrowserParser: | ||
| name = "browser" | ||
| priority = 10 | ||
|
|
||
| def matches(self, ctx: ParseContext, fields: S1Fields) -> bool: | ||
| return ctx.bundle_id in _BROWSER_BUNDLES | ||
|
|
||
| def parse(self, ctx: ParseContext, fields: S1Fields) -> S1Patch: | ||
| url = _extract_url_from_app(ctx.app) | ||
| return S1Patch(url=url) | ||
|
|
||
|
|
||
| def _extract_url_from_app(app_data: dict[str, Any]) -> str | None: | ||
| for window in app_data.get("windows", []): | ||
| for el in window.get("elements", []): | ||
| if el.get("role") != "AXTextField": | ||
| continue | ||
| value = (el.get("value") or "").strip() | ||
| if not value: | ||
| continue | ||
| if _URL_RE.search(value): | ||
| return value | ||
| if "." in value and " " not in value: | ||
| return f"https://{value}" | ||
| return None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| { | ||
| "focused_element": { | ||
| "role": "AXTextField", | ||
| "title": "Address and search bar", | ||
| "value": "https://www.anthropic.com/news", | ||
| "is_editable": true, | ||
| "has_value": true, | ||
| "value_length": 30 | ||
| }, | ||
| "visible_text": "## Google Chrome [active]\n_com.google.Chrome_\n### Anthropic — Claude Code\n- [TextField] Address and search bar — https://www.anthropic.com/news", | ||
| "url": "https://www.anthropic.com/news" | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| { | ||
| "ax_tree": { | ||
| "apps": [ | ||
| { | ||
| "name": "Google Chrome", | ||
| "bundle_id": "com.google.Chrome", | ||
| "is_frontmost": true, | ||
| "windows": [ | ||
| { | ||
| "title": "Anthropic — Claude Code", | ||
| "focused": true, | ||
| "elements": [ | ||
| { | ||
| "role": "AXTextField", | ||
| "title": "Address and search bar", | ||
| "value": "https://www.anthropic.com/news" | ||
| } | ||
| ] | ||
| } | ||
| ] | ||
| } | ||
| ] | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| { | ||
| "focused_element": { | ||
| "role": "AXTextArea", | ||
| "title": "editor", | ||
| "value": "def enrich(capture):\n ...", | ||
| "is_editable": true, | ||
| "has_value": true, | ||
| "value_length": 28 | ||
| }, | ||
| "visible_text": "## Cursor [active]\n_com.todesktop.230313mzl4w4u92_\n### s1_parser.py\n- [TextArea] editor — def enrich(capture):\n ...", | ||
| "url": null | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.