ReMe/reme/steps/proactive/data_connectors/screen_capture.py
jinliyl ae55e2e570
Some checks are pending
CI / Python packages / Build and verify distributions (push) Waiting to run
CI / Python quality / GitHub Actions (push) Waiting to run
CI / Python quality / Pre-commit (push) Waiting to run
CI / Python tests / Hermes embedded - ubuntu-latest (push) Waiting to run
CI / Python tests / Hermes embedded - windows-latest (push) Waiting to run
CI / Python tests / Unit Tests - py3.11 (push) Waiting to run
CI / Python tests / Unit Tests - py3.12 (push) Waiting to run
CI / Python tests / Unit Tests - py3.13 (push) Waiting to run
CI / Python tests / Unit Tests - py3.14 (push) Waiting to run
CI / ReMe Studio / Studio checks (push) Waiting to run
CI / Windows / CLI smoke - py3.11 (push) Waiting to run
Deploy / Documentation / Build documentation (push) Waiting to run
Deploy / Documentation / deploy (push) Blocked by required conditions
Security / CodeQL / Analyze javascript-typescript (push) Waiting to run
Security / CodeQL / Analyze python (push) Waiting to run
feat!: split proactive runtimes and add Studio backend management (#776)
* refactor(proactive)!: separate runtime ownership and unify delivery

* refactor(proactive): finish runtime and Studio migration

* test(proactive): make scheduled skip coverage deterministic

* refactor(studio): unify navigation and notebook resource loading

* feat(studio): edit workspace documents and update proactive task names

* refactor(studio): simplify task settings and navigation

* feat(studio): secure and supervise backend settings

* feat(studio): unify workbench timelines and refine desktop updates

Use shared timeline panes for notebook, memory, and resources. Add Todo creation ordering, persist companion visibility, and align desktop update handling and release artifacts.

Recheck editor file versions at read and publication boundaries. Retry reminder detail requests from the resource view.

* fix(studio): support unsigned GitHub preview releases

* fix: verify container state and isolate proactive view errors

Mount private supervisor state in Docker smoke tests and verify token and settings persistence. Exercise Studio startup with a loopback-only model fixture, and exclude packaged desktop output from Docker contexts.

Keep Remy subscriptions and healthy tasks available when an individual task has an invalid workspace path or session history.

* fix(home): align candidate Docker context exclusions

* chore(deps): update openai-codex dependency to v0.172.0

- Bump openai-codex from version 0.169.0 to 0.172.0 in pyproject.toml
- Keep other dependencies unchanged
- Ensure compatibility with latest openai-codex features and fixes

* fix(daemon): discover parent dotenv and isolate listeners

Restore parent-directory environment discovery in workers while retaining system precedence. Partition the default supervisor profile and lock by the configured bind address and port.
2026-11-25 21:33:16 +08:00

101 lines
4.6 KiB
Python

"""Capture changed display groups without merging or rescaling images."""
import os
from pathlib import Path
from stat import S_ISREG
from .base_connector import BaseConnectorStep
from ...file_io import check_path_permission
from ....core.registry import R
from ....utils.files.workspace_files import WorkspaceFiles
from ....schema import ResourceMetadata
from ....schema.resource_metadata import ResourceFile
@R.register("screen_capture_step")
class ScreenCaptureStep(BaseConnectorStep):
"""Collect one PNG per display; a failed display aborts the whole package."""
source = "screenshot"
def __init__(self, similarity_threshold=0.99, **kwargs):
super().__init__(**kwargs)
if type(similarity_threshold) not in (int, float) or not 0 <= similarity_threshold <= 1:
raise ValueError("similarity_threshold must be a number between 0 and 1")
self.similarity_threshold = similarity_threshold
self.description = self.get_prompt("description")
def _image(self, folder, entry):
from PIL import Image
files = WorkspaceFiles(self.workspace_path)
path = files.checked(folder / entry.path)
if not check_path_permission(self.workspace_path, path, self.context.get("_allowed_paths")):
raise PermissionError("no permission to read screenshot history")
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
with os.fdopen(descriptor, "rb") as handle:
if not S_ISREG(os.fstat(handle.fileno()).st_mode):
raise ValueError("Screenshot payload must be a regular file")
with Image.open(handle) as image:
return image.convert("RGB")
def _similar(self, directory, entries, previous_directory, previous_entries):
try:
from PIL import ImageChops
except ImportError as exc:
raise RuntimeError("Screen capture similarity requires Pillow; install reme-ai[core]") from exc
entries = sorted(entries, key=lambda item: item.path)
previous_entries = sorted(previous_entries, key=lambda item: item.path)
if entries != previous_entries:
return False
for entry, previous_entry in zip(entries, previous_entries):
with self._image(directory, entry) as image, self._image(previous_directory, previous_entry) as previous:
if image.size != previous.size:
return False
red, green, blue = ImageChops.difference(image, previous).split()
equal_pixels = ImageChops.lighter(ImageChops.lighter(red, green), blue).histogram()[0]
pixels = image.width * image.height
if equal_pixels != pixels and equal_pixels / pixels <= self.similarity_threshold:
return False
return True
def _unchanged(self, directory, entries):
files = WorkspaceFiles(self.workspace_path)
latest = None
for manifest in directory.parent.parent.glob("*/*/metadata.json"):
files.checked(manifest)
if not check_path_permission(self.workspace_path, manifest, self.context.get("_allowed_paths")):
raise PermissionError("no permission to read screenshot history")
metadata = ResourceMetadata.model_validate_json(files.read(manifest))
if metadata.source != self.source:
raise ValueError(f"Unexpected screenshot source: {metadata.source}")
if latest is None or metadata.created_at > latest[1].created_at:
latest = manifest, metadata
return latest is not None and self._similar(
directory,
entries,
latest[0].parent,
latest[1].files,
)
def collect(self, directory: Path) -> list[dict]:
try:
import mss
from mss.tools import to_png
except ImportError as exc:
raise RuntimeError("Screen capture requires mss; install reme-ai[core]") from exc
files = []
with mss.MSS() as capture:
monitors = capture.monitors[1:]
if not monitors:
raise RuntimeError("No displays available for screen capture")
for display_id, monitor in enumerate(monitors, 1):
image = capture.grab(monitor)
filename = f"{display_id}.png"
to_png(image.rgb, image.size, output=str(directory / filename))
files.append({"path": filename, "monitor": dict(monitor)})
if self._unchanged(directory, [ResourceFile.model_validate(entry) for entry in files]):
return []
return files