Skip to content
Merged

V2 #6

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ phases land so any session resumes from the right place.
evolution phases on the spine (`/v1/threads/{id}/evolution`); `←`/`esc`
returns. Enter on a phase opens its representative target.
*Code-complete + type/compile-checked; visual verification pending.*
- [x] **Phase 3.5 — Every engine layer has a surface.** The resting state
gains **"On your radar"** (`/v1/resurface/idle` — topics set aside past
the idle threshold, deduped against active threads); search gains a
**file results** group (`/v1/search/files`, also in the extension
popup); and macOS **desktop-focus capture** (`darwin.py` probe,
opt-in `desktop_capture_enabled`) feeds the engine a third source.
- [ ] **Phase 4 — Restore choreography.** Enter on a candidate reopens the
work in order (files → chats → tabs by domain → searches).
- [ ] **Phase 5 — Settings & polish.** Configurable hotkey, folder picker,
Expand Down
9 changes: 9 additions & 0 deletions app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,15 @@ class Config:
# no persistent cache, the surface is derived on demand).
recovery_enabled: bool = True

# ── Phase 6M: desktop focus capture ─────────────────────────
# When True the daemon runs the foreground-window watcher and
# writes `desktop_window` events (app + window title + focus
# duration — metadata only, never contents). Off by default:
# watching every app you focus is the most intimate capture
# source, so it is an explicit opt-in. RECALL_DESKTOP=off in
# the environment silences the layer regardless of this flag.
desktop_capture_enabled: bool = False

@classmethod
def load(cls) -> "Config":
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
Expand Down
98 changes: 98 additions & 0 deletions app/core/desktop/darwin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
"""Phase 6M sibling — foreground window probe (macOS).

Same contract as ``windows.py``: one call returns the currently
focused app + window title, or ``None``. Uses pyobjc's AppKit for
the frontmost application and Quartz's window list for the title —
both already ship with the desktop app for the tray/launcher stack.

Privacy contract restated for macOS:

- ``NSWorkspace.frontmostApplication`` exposes only the app's
name, pid and bundle path — never document contents.
- The window *title* comes from ``kCGWindowName``, which macOS
only reveals when the user has granted Screen Recording
permission. Without it we fall back to the app name, so the
layer degrades to app-level granularity instead of silently
requesting scarier permissions.
- Same aggregation rules as Windows apply downstream: blocks
under the minimum focus duration never reach the JSONL.
"""

from __future__ import annotations

import sys
from typing import Optional

from .windows import ForegroundWindow

_IS_DARWIN = sys.platform == "darwin"

_APPKIT = None
_QUARTZ = None
if _IS_DARWIN:
try: # pragma: no cover — import availability is machine-specific
import AppKit as _APPKIT # type: ignore[no-redef]
import Quartz as _QUARTZ # type: ignore[no-redef]
except Exception: # noqa: BLE001 — no pyobjc → graceful no-op
_APPKIT = None
_QUARTZ = None


def is_supported() -> bool:
"""True when we're on macOS and pyobjc is importable."""
return _IS_DARWIN and _APPKIT is not None and _QUARTZ is not None


def _frontmost_window_title(pid: int) -> str:
"""Best-effort title of the frontmost window owned by `pid`.

The on-screen window list is ordered front-to-back, so the first
layer-0 window owned by the pid is the focused one. ``kCGWindowName``
is absent without Screen Recording permission — callers fall back
to the app name."""
if _QUARTZ is None:
return ""
try:
wl = _QUARTZ.CGWindowListCopyWindowInfo(
_QUARTZ.kCGWindowListOptionOnScreenOnly
| _QUARTZ.kCGWindowListExcludeDesktopElements,
_QUARTZ.kCGNullWindowID,
)
for w in wl or []:
if int(w.get("kCGWindowOwnerPID", -1)) != pid:
continue
if int(w.get("kCGWindowLayer", 1)) != 0:
continue
return str(w.get("kCGWindowName") or "")
except Exception: # noqa: BLE001 — a failed tick is silent
pass
return ""


def probe_foreground() -> Optional[ForegroundWindow]:
"""Return the currently focused window or ``None``."""
if not is_supported():
return None
try:
app = _APPKIT.NSWorkspace.sharedWorkspace().frontmostApplication()
if app is None:
return None
pid = int(app.processIdentifier())
name = str(app.localizedName() or "")
url = app.bundleURL()
exe_path = str(url.path()) if url is not None else None
title = _frontmost_window_title(pid) or name
if not name and not title:
return None
return ForegroundWindow(
hwnd=0, # macOS has no HWND; identity comes from exe::title
title=title,
pid=pid,
exe_name=name or None,
exe_path=exe_path,
)
except Exception: # noqa: BLE001
return None


__all__ = ["is_supported", "probe_foreground"]
25 changes: 18 additions & 7 deletions app/core/desktop/watcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@

Disable rules:

- The watcher refuses to start on non-Windows hosts (Windows is
the only platform with a probe today). Future macOS / Linux
siblings drop in next to ``windows.py``.
- The watcher refuses to start on hosts without a probe
(Windows via ``windows.py``, macOS via ``darwin.py``; a Linux
sibling drops in next to them).
- ``RECALL_DESKTOP=off`` in the environment makes start_watcher
a no-op — the directive's *metadata only* contract gives the
user a single env flag to silence the whole layer.
Expand All @@ -38,9 +38,11 @@
from typing import Optional

from ..events import EventLogger
from . import darwin
from .events import KIND, DesktopWindowEvent
from .sessions import FocusAggregator
from .windows import is_supported as windows_is_supported, probe_foreground
from .windows import is_supported as windows_is_supported
from .windows import probe_foreground as _probe_windows


log = logging.getLogger("recall.core.desktop.watcher")
Expand All @@ -55,9 +57,18 @@ def _env_disabled() -> bool:


def _platform_supported() -> bool:
if not sys.platform.startswith("win"):
return False
return windows_is_supported()
if sys.platform.startswith("win"):
return windows_is_supported()
if sys.platform == "darwin":
return darwin.is_supported()
return False


def probe_foreground():
"""Platform-dispatched foreground probe (Windows / macOS)."""
if sys.platform == "darwin":
return darwin.probe_foreground()
return _probe_windows()


class DesktopWatcher:
Expand Down
17 changes: 17 additions & 0 deletions app/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,18 @@ def run_service() -> int:
log.info("api service: %s on 127.0.0.1:%d",
"running" if api_started else "NOT started", config.browser_ingest_port)

# Desktop focus capture — explicit opt-in (config + RECALL_DESKTOP).
# Windows and macOS have probes; anywhere else this is a quiet no-op.
desktop_watcher = None
if getattr(config, "desktop_capture_enabled", False):
from .core.desktop.watcher import start_watcher as start_desktop_watcher

desktop_watcher = start_desktop_watcher(event_logger)
log.info("desktop watcher: %s",
"running" if desktop_watcher else "not started")
else:
log.info("desktop watcher: disabled by config.")

# Block until a termination signal. launchd sends SIGTERM on logout
# or `launchctl bootout`; Ctrl-C sends SIGINT when run by hand.
stop = threading.Event()
Expand All @@ -169,6 +181,11 @@ def _on_signal(signum, _frame):
watcher.stop()
except Exception:
pass
if desktop_watcher is not None:
try:
desktop_watcher.stop() # flushes any open focus block
except Exception:
pass
try:
api.stop()
except Exception:
Expand Down
Loading
Loading