diff --git a/.gitignore b/.gitignore index 027dc8b..805262f 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,8 @@ demo/*.gif # that ARE tracked - see docs/trust/INSTALL_PROOF_WINDOWS.md) *.log.tmp *.runtime.log + +# bundled engine sidecar — built by pyinstaller, never committed +apps/launcher/src-tauri/binaries/ +dist/ +build/ diff --git a/CLAUDE.md b/CLAUDE.md index 80685d5..0d0d2de 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -230,6 +230,7 @@ verification is performed — see │ │ ├── events.py EventLogger + EventStore (JSONL) │ │ ├── episodic.py Keyword + recency + kind-hint scorer │ │ ├── sessions.py Session reconstructor +│ │ ├── workblocks.py Behavioural work-blocks (dwell-aware, C5) │ │ ├── microcontexts.py Micro-context reconstructor │ │ ├── resurfacing.py Idle-launcher continuity surface │ │ ├── threads.py Persistent topic identity diff --git a/ROADMAP.md b/ROADMAP.md index 929bae8..e02d714 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -105,4 +105,17 @@ telemetry. See the capture audit for the full diagnosis. opted in via `ALLOWED_KINDS` + payload allowlist + smoke §34, with the kind **deliberately absent from `RETRIEVABLE_KINDS`** — it is a grouping signal for behavioural work-blocks, never a search result. - *The consumer (sessions grouping on dwell/blocks) is the follow-on.* +- [x] **Capture C5 — Behavioural sessions (use the signal).** + [`app/core/workblocks.py`](app/core/workblocks.py) — a pure, + deterministic derivation that regroups a session's events into + *work-blocks* of continuous attention. The 30-min clock over-merges + two scattered bursts into one session and can't tell focus from a + tab left open; work-blocks read the `dwell_ms`/`block` signal back + and **split** what the clock lumped (10-min behavioural idle) while + **bridging** gaps a dwell span or shared `wb-` id proves were + continuous. Additive — the `session_id` spine is untouched; `Session` + gains derived `work_blocks` + `behavioural_label` ("one 47-minute + focus block" / "3 attention blocks"), surfaced through `SessionOut` + and the launcher caption. 9 pure unit checks + ([`_test_workblocks.py`](_test_workblocks.py)) + smoke §38; ~1 µs per + derivation, safe on the search hot path. diff --git a/_smoke_api.py b/_smoke_api.py index ffa39b9..6c4fdf2 100644 --- a/_smoke_api.py +++ b/_smoke_api.py @@ -1723,6 +1723,58 @@ def search(self, query, top_k=8): print("[OK] /v1/loop/bump feeds the same ledger the console reads") +# ---------------------------------------------------------------------- +section("38. Behavioural work-blocks reach the session wire (Capture C5)") +# ---------------------------------------------------------------------- +# The 30-minute clock lumps two scattered bursts into one session; the +# dwell/work-block signal splits them. This verifies the derivation is +# wired all the way to SessionOut — the field the launcher and console +# describe attention with. +from app.core.events import Event as _Ev # noqa: E402 +from app.core.sessions import Session as _Session # noqa: E402 +from api.main import _session_to_out as _sess_out # noqa: E402 + +_wb_base = datetime(2026, 7, 20, 9, 0, 0, tzinfo=timezone.utc) + + +def _wb_ev(offset_s, kind="browser_visit", **payload): + ts = (_wb_base + timedelta(seconds=offset_s)).strftime("%Y-%m-%dT%H:%M:%SZ") + return _Ev(ts=ts, session_id="s_wb", kind=kind, payload=payload) + + +# one clock session, two attention islands 15 minutes apart +_scattered = _Session( + session_id="s_wb", + events=[ + _wb_ev(0, kind="browser_focus", dwell_ms=20 * 60 * 1000, block="wb-a"), + _wb_ev(120), + _wb_ev(240 + 15 * 60, kind="browser_focus", dwell_ms=12 * 60 * 1000, block="wb-b"), + _wb_ev(240 + 15 * 60 + 120), + ], + topic="websocket", + label="Working on websocket", + time_label="today", + score=1.0, +) +assert _scattered.work_blocks == 2, _scattered.work_blocks +assert "attention blocks" in _scattered.behavioural_label, _scattered.behavioural_label +_out = _sess_out(_scattered) +assert _out.work_blocks == 2 +assert _out.behavioural_label == _scattered.behavioural_label +# a tight single burst stays one block and adds no clause +_tight = _Session(session_id="s2", events=[_wb_ev(0), _wb_ev(30), _wb_ev(90)]) +assert _tight.work_blocks == 1 and _sess_out(_tight).behavioural_label == "" +# derivation is cheap — it runs on the search hot path +t0 = time.perf_counter() +for _ in range(200): + _ = _scattered.work_blocks +wb_us = (time.perf_counter() - t0) / 200 * 1e6 +assert wb_us < 500, f"work-block derivation {wb_us:.0f}us, budget 500us" +print(f" scattered → {_out.work_blocks} blocks · \"{_out.behavioural_label}\"; " + f"{wb_us:.0f}us/derivation") +print("[OK] work-blocks flow to SessionOut, cheap enough for the hot path") + + # Cleanup shutil.rmtree(TMP, ignore_errors=True) diff --git a/_test_workblocks.py b/_test_workblocks.py new file mode 100644 index 0000000..2ce1b16 --- /dev/null +++ b/_test_workblocks.py @@ -0,0 +1,112 @@ +"""Deterministic tests for the pure work-blocks derivation (Capture C5). + +Run: python _test_workblocks.py + +No daemon, no disk, no clock — `workblocks` is a pure function of the +event timestamps and captured dwell spans, which is exactly why the +riskiest continuity logic is verifiable in isolation. +""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone + +from app.core.events import Event +from app.core.workblocks import ( + BEHAVIOURAL_IDLE_SECONDS, + describe_blocks, + group_work_blocks, +) + +_BASE = datetime(2026, 7, 20, 9, 0, 0, tzinfo=timezone.utc) + +n = 0 + + +def ok(msg: str) -> None: + global n + n += 1 + print(f" [ok] {msg}") + + +def ev(offset_s: float, kind: str = "browser_visit", **payload) -> Event: + """An event `offset_s` seconds after the base moment.""" + ts = (_BASE + timedelta(seconds=offset_s)).strftime("%Y-%m-%dT%H:%M:%SZ") + return Event(ts=ts, session_id="s_test", kind=kind, payload=payload) + + +# --- empty + trivial --------------------------------------------------- +assert group_work_blocks([]) == [] +assert describe_blocks([]) == "" +ok("empty stream → no blocks, no description") + +single = [ev(0), ev(60), ev(120)] +blocks = group_work_blocks(single) +assert len(blocks) == 1, blocks +# a single block with no dwell signal stays quiet — the clock label covers it +assert describe_blocks(blocks) == "" +ok("tight clicks with no dwell → one block, no clause") + +# --- the split the clock can't see ------------------------------------- +# Two five-minute bursts 15 minutes apart. The 30-minute clock lumps +# them into ONE session; behaviourally they're two attention islands. +scattered = [ + ev(0), ev(120), ev(240), # burst 1 (0–4 min) + ev(240 + 15 * 60), ev(240 + 15 * 60 + 120), # burst 2, 15-min gap +] +blocks = group_work_blocks(scattered) +assert len(blocks) == 2, f"expected 2 blocks, got {len(blocks)}" +assert len(blocks[0]) == 3 and len(blocks[1]) == 2 +ok("15-min silence inside one clock session → two work-blocks") + +# --- dwell bridges a gap the idle rule would split --------------------- +# A gap longer than the idle threshold, but a dwell event whose span +# reaches back across it — the user was present the whole time. +gap = BEHAVIOURAL_IDLE_SECONDS + 120 # over the idle threshold +bridged = [ + ev(0), + ev(gap, kind="browser_focus", dwell_ms=(gap + 30) * 1000, block="wb-1"), +] +blocks = group_work_blocks(bridged) +assert len(blocks) == 1, f"dwell should bridge the gap, got {len(blocks)}" +ok("long gap covered by a dwell span → stays one block") + +# a dwell too short to bridge does NOT rescue the gap +not_bridged = [ + ev(0), + ev(gap, kind="browser_focus", dwell_ms=9000, block="wb-1"), +] +assert len(group_work_blocks(not_bridged)) == 2 +ok("sub-threshold dwell across a long gap → two blocks") + +# --- shared extension block id bridges --------------------------------- +same_block = [ + ev(0, kind="browser_focus", dwell_ms=30000, block="wb-9"), + ev(gap, kind="browser_focus", dwell_ms=9000, block="wb-9"), +] +assert len(group_work_blocks(same_block)) == 1 +ok("same extension work-block id bridges a long gap") + +# --- order independence ------------------------------------------------ +shuffled = [scattered[3], scattered[0], scattered[4], scattered[2], scattered[1]] +assert len(group_work_blocks(shuffled)) == 2 +ok("result is independent of input order (stable sort)") + +# --- descriptions ------------------------------------------------------ +focus_hour = [ + ev(0, kind="browser_focus", dwell_ms=47 * 60 * 1000, block="wb-1"), +] +assert describe_blocks(group_work_blocks(focus_hour)) == "one 47-minute focus block" +ok("single long dwell → 'one 47-minute focus block'") + +multi = group_work_blocks([ + ev(0, kind="browser_focus", dwell_ms=20 * 60 * 1000, block="wb-1"), + ev(240 + 15 * 60, kind="browser_focus", dwell_ms=15 * 60 * 1000, block="wb-2"), + ev(240 + 40 * 60, kind="browser_focus", dwell_ms=10 * 60 * 1000, block="wb-3"), +]) +desc = describe_blocks(multi) +assert desc.startswith("3 attention blocks"), desc +assert "focused" in desc +ok(f"three blocks with dwell → '{desc}'") + +print(f"\n{n} work-block checks passed") diff --git a/api/main.py b/api/main.py index 69647ab..e224741 100644 --- a/api/main.py +++ b/api/main.py @@ -164,6 +164,8 @@ def _session_to_out(s: Session) -> SessionOut: time_label=s.time_label, score=s.score, event_count=s.event_count, + work_blocks=s.work_blocks, + behavioural_label=s.behavioural_label, kinds=s.kinds, preview_events=[_event_to_out(ev) for ev in s.preview_events()], openable_targets=[ diff --git a/api/schemas.py b/api/schemas.py index aeb2203..a9cc545 100644 --- a/api/schemas.py +++ b/api/schemas.py @@ -200,6 +200,12 @@ class SessionOut(BaseModel): time_label: str score: float event_count: int + # Capture C5 — behavioural attention shape, derived from the + # dwell/work-block signal. `work_blocks` counts continuous runs of + # attention inside the clock session; `behavioural_label` is the + # one-clause description ("" when there's no signal to add). + work_blocks: int = 1 + behavioural_label: str = "" kinds: List[str] preview_events: List[EventOut] openable_targets: List[OpenableTarget] diff --git a/app/core/sessions.py b/app/core/sessions.py index eda3ea0..7aa6d6b 100644 --- a/app/core/sessions.py +++ b/app/core/sessions.py @@ -106,6 +106,25 @@ class Session: def event_count(self) -> int: return len(self.events) + @property + def work_blocks(self) -> int: + """How many behavioural work-blocks this clock session actually + contains (Capture C5). 1 means one continuous run of attention; + more means the 30-minute window lumped together separate + bursts. Derived, never stored — see `workblocks.py`.""" + from .workblocks import group_work_blocks + + return len(group_work_blocks(self.events)) + + @property + def behavioural_label(self) -> str: + """One quiet clause naming the session's attention shape, e.g. + "one 47-minute focus block" or "3 attention blocks". Empty when + there's no signal worth adding to the clock label.""" + from .workblocks import describe_blocks, group_work_blocks + + return describe_blocks(group_work_blocks(self.events)) + @property def kinds(self) -> List[str]: seen: set[str] = set() diff --git a/app/core/workblocks.py b/app/core/workblocks.py new file mode 100644 index 0000000..3131573 --- /dev/null +++ b/app/core/workblocks.py @@ -0,0 +1,160 @@ +"""Work-blocks — behavioural grouping of a session's events (Capture C5). + +The `session` layer groups events by a 30-minute *clock* gap, stamped +at capture time. That's a good first cut, but the clock lies in two +directions: it **over-merges** two scattered five-minute bursts that +happened to fall inside one half-hour window, and it can't tell an +hour of unbroken focus from an hour with the tab left open. + +The browser extension already captures the missing signal: every +`browser_focus` event carries how long attention actually stayed on a +page (`dwell_ms`) and a work-block id (`block`, `wb-`) that the +extension derived from focus runs and five-minute silences. This +module reads that signal back and regroups a session's events into +*work-blocks* — periods of continuous attention. + +Design rules (charter): + + • **Deterministic.** Same events in → same blocks out. No clocks + read here, no randomness; every boundary is a pure function of + the event timestamps and the captured dwell spans. + • **Additive.** This never touches `session_id` or the events on + disk. It's a read-time derivation the session layer *describes* + with; delete this file and sessions still reconstruct. + • **Honest when the signal is absent.** With no `browser_focus` + events (a day of pure clicks), it falls back to a plain idle-gap + split — still useful, never wrong. + +The one number this earns: a session that reads "one 47-minute focus +block" is a very different memory from one that reads "four scattered +blocks across the afternoon", and only attention can tell them apart. +""" + +from __future__ import annotations + +from typing import List + +from .events import Event + +# A behavioural boundary is shorter than the 30-minute clock session: +# ten minutes of true silence (no event, no dwell bridging it) ends a +# work-block. Deliberately below SESSION_GAP_SECONDS so a single clock +# session can still split into several attention blocks. +BEHAVIOURAL_IDLE_SECONDS = 10 * 60 + +# A dwell shorter than this doesn't count as attention that can bridge +# a gap — it's passing through, matching the extension's own floor. +_MIN_BRIDGE_DWELL_MS = 8_000 + + +def _dwell_span_start(ev: Event) -> float | None: + """For a `browser_focus` event, the epoch second attention began — + i.e. `ts - dwell_ms`. The event lands when focus *leaves* a page, + so its dwell reaches backward in time and can bridge a preceding + gap. Returns None for any event without a usable dwell.""" + if ev.kind != "browser_focus": + return None + dwell = ev.payload.get("dwell_ms") + if not isinstance(dwell, (int, float)) or dwell < _MIN_BRIDGE_DWELL_MS: + return None + return ev.ts_epoch() - (dwell / 1000.0) + + +def _block_hint(ev: Event) -> str | None: + if ev.kind != "browser_focus": + return None + block = ev.payload.get("block") + return block if isinstance(block, str) and block else None + + +def group_work_blocks( + events: List[Event], + *, + idle_gap_s: float = BEHAVIOURAL_IDLE_SECONDS, +) -> List[List[Event]]: + """Split a chronological event list into behavioural work-blocks. + + A new block starts when the gap from the previous event exceeds + `idle_gap_s` **and** nothing bridges it. Two things bridge a gap: + + 1. This event is a dwell whose attention span (`ts - dwell_ms`) + reaches back to the previous event — the user was present the + whole time. + 2. This and the previous browser-focus event share the same + extension work-block id — the extension already judged them + one continuous run. + + Input need not be pre-sorted; a stable sort by timestamp is applied + so the result is order-independent. Empty in → empty out. + """ + if not events: + return [] + + ordered = sorted(events, key=lambda e: e.ts_epoch()) + blocks: List[List[Event]] = [[ordered[0]]] + prev_ts = ordered[0].ts_epoch() + prev_block = _block_hint(ordered[0]) + + for ev in ordered[1:]: + ts = ev.ts_epoch() + gap = ts - prev_ts + + bridged = False + if gap <= idle_gap_s: + bridged = True + else: + span_start = _dwell_span_start(ev) + if span_start is not None and span_start <= prev_ts: + bridged = True + else: + hint = _block_hint(ev) + if hint is not None and hint == prev_block: + bridged = True + + if bridged: + blocks[-1].append(ev) + else: + blocks.append([ev]) + + prev_ts = ts + this_block = _block_hint(ev) + if this_block is not None: + prev_block = this_block + + return blocks + + +def describe_blocks(blocks: List[List[Event]]) -> str: + """One quiet clause naming a session's attention shape. Empty + string when there's nothing worth saying (a single trivial block + with no dwell signal — the clock label already covers it).""" + n = len(blocks) + if n == 0: + return "" + + total_dwell_ms = 0.0 + for blk in blocks: + for ev in blk: + dwell = ev.payload.get("dwell_ms") + if ev.kind == "browser_focus" and isinstance(dwell, (int, float)): + total_dwell_ms += float(dwell) + + if n == 1: + if total_dwell_ms >= 60_000: + return f"one {_mins(total_dwell_ms)} focus block" + return "" # single block, no real attention signal — say nothing + + if total_dwell_ms >= 60_000: + return f"{n} attention blocks · {_mins(total_dwell_ms)} focused" + return f"{n} attention blocks" + + +def _mins(ms: float) -> str: + m = int(round(ms / 60_000.0)) + if m < 1: + return "under a minute of" + if m < 60: + return f"{m}-minute" + h = m // 60 + rem = m % 60 + return f"{h}h{rem:02d}m" if rem else f"{h}-hour" diff --git a/app/service.py b/app/service.py index 256cff1..277acf4 100644 --- a/app/service.py +++ b/app/service.py @@ -26,14 +26,15 @@ from typing import Optional from .core.config import CHROMA_DIR, CONFIG_DIR, Config -from .core.embeddings import EmbeddingModel from .core.events import EventLogger -from .core.indexer import Indexer -from .core.search import SearchEngine -from .core.watcher import IndexWatcher -from .db.store import VectorStore from api import APIService # type: ignore[import-not-found] +# The file-search stack (chromadb + sentence-transformers + torch) is +# optional at runtime: the bundled daemon ships without it to stay +# small, and /v1/search/files answers `enabled: false` — a calm +# state, not an error. Importing lazily inside run() keeps the +# frozen binary from even trying to load torch at boot. + log = logging.getLogger("recall.service") INSTANCE_LOCK = CONFIG_DIR / "instance.lock" @@ -108,26 +109,40 @@ def run_service() -> int: # File index + watcher: keep ~/.recall/chroma in step with the # configured folders so file search stays fresh across reboots. - store = VectorStore(CHROMA_DIR) - model = EmbeddingModel.get(config.embedding_model) - indexer = Indexer(config, store, model) - - watcher: Optional[IndexWatcher] = None - if config.indexed_folders: - # Watcher-forward indexing: the watcher embeds files as they are - # created or modified, so real work from today onward is captured - # into file search. We deliberately do NOT run a full historical - # index pass here — Documents/Desktop are large, file search is - # secondary to event capture, and any prior pass is already on - # disk in ~/.recall/chroma. - watcher = IndexWatcher(indexer, list(config.indexed_folders)) - started = watcher.start() - log.info("watcher running: %s (%d folder(s))", - started, len(config.indexed_folders)) - if not started: - watcher = None - else: - log.info("no indexed folders configured — watcher idle.") + # The whole stack is optional — a bundled daemon without the + # embedding packages runs everything else at full fidelity. + watcher = None + search_engine = None + try: + from .core.embeddings import EmbeddingModel + from .core.indexer import Indexer + from .core.search import SearchEngine + from .core.watcher import IndexWatcher + from .db.store import VectorStore + + store = VectorStore(CHROMA_DIR) + model = EmbeddingModel.get(config.embedding_model) + indexer = Indexer(config, store, model) + search_engine = SearchEngine(store, model) + + if config.indexed_folders: + # Watcher-forward indexing: the watcher embeds files as + # they are created or modified, so real work from today + # onward is captured into file search. We deliberately do + # NOT run a full historical index pass here — folders are + # large, file search is secondary to event capture, and + # any prior pass is already on disk in ~/.recall/chroma. + watcher = IndexWatcher(indexer, list(config.indexed_folders)) + started = watcher.start() + log.info("watcher running: %s (%d folder(s))", + started, len(config.indexed_folders)) + if not started: + watcher = None + else: + log.info("no indexed folders configured — watcher idle.") + except Exception: + log.info("file-search stack unavailable — " + "/v1/search/files will answer enabled:false") # Local memory API — ingestion (capture) + retrieval. Same wiring as # the GUI path in app.main, minus everything Qt. @@ -143,7 +158,7 @@ def run_service() -> int: # Same store + model the watcher indexes into — the daemon now # answers /v1/search/files for every client (launcher, # extension, editors) instead of keeping file search in-process. - file_search_engine=SearchEngine(store, model), + file_search_engine=search_engine, ) api_started = api.start() log.info("api service: %s on 127.0.0.1:%d", diff --git a/apps/launcher/src-tauri/Cargo.lock b/apps/launcher/src-tauri/Cargo.lock index a5fa119..a36d6a0 100644 --- a/apps/launcher/src-tauri/Cargo.lock +++ b/apps/launcher/src-tauri/Cargo.lock @@ -2499,6 +2499,16 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "os_pipe" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "pango" version = "0.18.3" @@ -2825,6 +2835,7 @@ dependencies = [ "tauri-plugin-autostart", "tauri-plugin-global-shortcut", "tauri-plugin-opener", + "tauri-plugin-shell", "tokio", "window-vibrancy", ] @@ -3378,12 +3389,44 @@ dependencies = [ "digest", ] +[[package]] +name = "shared_child" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e362d9935bc50f019969e2f9ecd66786612daae13e8f277be7bfb66e8bed3f7" +dependencies = [ + "libc", + "sigchld", + "windows-sys 0.60.2", +] + [[package]] name = "shlex" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "sigchld" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47106eded3c154e70176fc83df9737335c94ce22f821c32d17ed1db1f83badb1" +dependencies = [ + "libc", + "os_pipe", + "signal-hook", +] + +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + [[package]] name = "signal-hook-registry" version = "1.4.8" @@ -3841,6 +3884,27 @@ dependencies = [ "zbus", ] +[[package]] +name = "tauri-plugin-shell" +version = "2.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8457dbf9e2bab1edd8df22bb2c20857a59a9868e79cb3eac5ed639eec4d0c73b" +dependencies = [ + "encoding_rs", + "log", + "open", + "os_pipe", + "regex", + "schemars 0.8.22", + "serde", + "serde_json", + "shared_child", + "tauri", + "tauri-plugin", + "thiserror 2.0.18", + "tokio", +] + [[package]] name = "tauri-runtime" version = "2.11.3" @@ -4926,6 +4990,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -4959,13 +5032,30 @@ dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm", + "windows_i686_gnullvm 0.52.6", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6", ] +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link 0.2.1", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + [[package]] name = "windows-threading" version = "0.1.0" @@ -4996,6 +5086,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + [[package]] name = "windows_aarch64_msvc" version = "0.42.2" @@ -5008,6 +5104,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + [[package]] name = "windows_i686_gnu" version = "0.42.2" @@ -5020,12 +5122,24 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + [[package]] name = "windows_i686_msvc" version = "0.42.2" @@ -5038,6 +5152,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + [[package]] name = "windows_x86_64_gnu" version = "0.42.2" @@ -5050,6 +5170,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + [[package]] name = "windows_x86_64_gnullvm" version = "0.42.2" @@ -5062,6 +5188,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + [[package]] name = "windows_x86_64_msvc" version = "0.42.2" @@ -5074,6 +5206,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + [[package]] name = "winnow" version = "0.5.40" diff --git a/apps/launcher/src-tauri/Cargo.toml b/apps/launcher/src-tauri/Cargo.toml index 7caf530..6df9b39 100644 --- a/apps/launcher/src-tauri/Cargo.toml +++ b/apps/launcher/src-tauri/Cargo.toml @@ -18,6 +18,7 @@ tauri = { version = "2", features = ["macos-private-api", "tray-icon"] } tauri-plugin-global-shortcut = "2" tauri-plugin-opener = "2" tauri-plugin-autostart = "2" +tauri-plugin-shell = "2" # Pinned to the same minor tauri's macos-private-api feature pulls — # two window-vibrancy versions define the same ObjC class and the # duplicate symbol breaks the fat-LTO release link. diff --git a/apps/launcher/src-tauri/src/lib.rs b/apps/launcher/src-tauri/src/lib.rs index d8f3cb5..34201a9 100644 --- a/apps/launcher/src-tauri/src/lib.rs +++ b/apps/launcher/src-tauri/src/lib.rs @@ -21,6 +21,7 @@ use tauri_plugin_global_shortcut::{ Code, GlobalShortcutExt, Modifiers, Shortcut, ShortcutState, }; use tauri_plugin_opener::OpenerExt; +use tauri_plugin_shell::{process::CommandChild, ShellExt}; const ENGINE: &str = "http://127.0.0.1:4545"; const PANEL_WIDTH: f64 = 720.0; @@ -145,6 +146,45 @@ fn default_shortcut() -> Shortcut { Shortcut::new(Some(Modifiers::CONTROL), Code::Space) } +// ------------------------------------------------- bundled engine +// +// The .dmg carries the engine as a sidecar binary. On boot the +// launcher probes 127.0.0.1:4545: if a daemon already answers (a +// dev checkout, a launchd service), it does nothing — the running +// engine always wins. Otherwise it spawns the bundled one and kills +// it again on exit. The engine's own instance lock makes a race +// harmless. + +struct EngineChild(std::sync::Mutex>); + +fn ensure_engine(app: &AppHandle) { + let app = app.clone(); + tauri::async_runtime::spawn(async move { + if engine_get("/v1/health").await.is_ok() { + return; // an engine is already serving — never double-start + } + match app.shell().sidecar("recall-daemon") { + Ok(cmd) => match cmd.args(["--service"]).spawn() { + Ok((_rx, child)) => { + if let Some(state) = app.try_state::() { + *state.0.lock().unwrap() = Some(child); + } + } + Err(e) => eprintln!("recall: bundled engine failed to spawn: {e}"), + }, + Err(e) => eprintln!("recall: no bundled engine sidecar: {e}"), + } + }); +} + +fn stop_engine(app: &AppHandle) { + if let Some(state) = app.try_state::() { + if let Some(child) = state.0.lock().unwrap().take() { + let _ = child.kill(); + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -444,6 +484,8 @@ fn toggle_panel(win: &WebviewWindow) { pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_opener::init()) + .plugin(tauri_plugin_shell::init()) + .manage(EngineChild(std::sync::Mutex::new(None))) .plugin(tauri_plugin_autostart::init( MacosLauncher::LaunchAgent, None, @@ -477,6 +519,10 @@ pub fn run() { settings_set_autostart, ]) .setup(move |app| { + // Bring the bundled engine up first — the panel is only + // as good as the daemon behind it. + ensure_engine(app.handle()); + let win = app .get_webview_window("main") .expect("main window must exist"); @@ -529,6 +575,13 @@ pub fn run() { Ok(()) }) - .run(tauri::generate_context!()) - .expect("error while running Recall launcher"); + .build(tauri::generate_context!()) + .expect("error while building Recall launcher") + .run(|app, event| { + if let tauri::RunEvent::Exit = event { + // Take the bundled engine down with us; an external + // daemon (dev checkout / launchd) is never ours to kill. + stop_engine(app); + } + }); } diff --git a/apps/launcher/src-tauri/tauri.conf.json b/apps/launcher/src-tauri/tauri.conf.json index 4fd828b..bc83824 100644 --- a/apps/launcher/src-tauri/tauri.conf.json +++ b/apps/launcher/src-tauri/tauri.conf.json @@ -39,6 +39,7 @@ "bundle": { "active": true, "targets": "all", + "externalBin": ["binaries/recall-daemon"], "icon": [ "icons/32x32.png", "icons/128x128.png", diff --git a/apps/launcher/src/App.tsx b/apps/launcher/src/App.tsx index 239a8c9..0bdb551 100644 --- a/apps/launcher/src/App.tsx +++ b/apps/launcher/src/App.tsx @@ -230,7 +230,10 @@ export default function App() { key: `s${i}`, layer: "session", title: s.label || s.topic, - caption: `${s.time_label} · ${s.event_count} events`, + // Attention shape wins the caption when the dwell signal has + // something to say ("2 attention blocks"); otherwise fall back + // to the plain event count. + caption: `${s.time_label} · ${s.behavioural_label || `${s.event_count} events`}`, action: s.openable_targets[0] ? "open" : "none", hint: "↵ open", target: s.openable_targets[0], diff --git a/apps/launcher/src/types.ts b/apps/launcher/src/types.ts index 0371017..a24f5e2 100644 --- a/apps/launcher/src/types.ts +++ b/apps/launcher/src/types.ts @@ -63,6 +63,10 @@ export interface SessionResult { time_label: string; score: number; event_count: number; + // Capture C5 — behavioural attention shape from the dwell signal. + // `behavioural_label` is "" when there's no signal worth adding. + work_blocks: number; + behavioural_label: string; kinds: string[]; preview_events: EventOut[]; openable_targets: OpenableTarget[]; diff --git a/docs/release/RELEASE.md b/docs/release/RELEASE.md index 149d337..34b9e1a 100644 --- a/docs/release/RELEASE.md +++ b/docs/release/RELEASE.md @@ -90,7 +90,23 @@ explicit consent. ## Installer pipeline (macOS launcher) -The v2 Tauri launcher ships as a `.dmg`: +The v2 Tauri launcher ships as a `.dmg` **with the engine bundled +as a sidecar**: + +0. `pyinstaller --noconfirm recall-daemon.spec` (repo root) — builds + the ~21 MB headless engine (no Qt, no embedding stack; file + search degrades to `enabled:false`), then place it for Tauri: + + ```bash + cp dist/recall-daemon \ + apps/launcher/src-tauri/binaries/recall-daemon-aarch64-apple-darwin + ``` + + `src-tauri/binaries/` is gitignored — the sidecar is a build + artifact, rebuilt per release. At app boot the launcher probes + 127.0.0.1:4545 and only spawns the bundled engine if nothing + answers; it kills its own child on exit and never touches an + externally-run daemon. 1. `cd apps/launcher && pnpm tauri build` — compiles the release binary (fat-LTO, `opt-level = "s"`) and bundles both artifacts: diff --git a/docs/release/notes-v0.1.0.md b/docs/release/notes-v0.1.0.md index 9b15d95..e53d793 100644 --- a/docs/release/notes-v0.1.0.md +++ b/docs/release/notes-v0.1.0.md @@ -45,27 +45,29 @@ from `apps/extension/`) read-only engine room that talks to your daemon from your own browser. Zero proxying; your data never touches a server. -## Install (the honest version) +## Install -1. **The engine first** (the .dmg is the launcher shell; the engine - ships from source in this alpha): - ```bash - git clone https://github.com/kunalKumar-13/Recall-me && cd Recall-me - pip install -r requirements.txt - python recall.py - ``` -2. **The launcher**: open the `.dmg`, drag Recall to Applications. - It's ad-hoc signed — right-click → Open the first time. -3. **The extension**: `chrome://extensions` → Developer mode → - Load unpacked → select `apps/extension/`. -4. Work normally. Next interruption, press **⌃Space**. +1. **The launcher**: open the `.dmg`, drag Recall to Applications, + launch it. **The engine is bundled** — the app starts it on + 127.0.0.1:4545 automatically (and never double-starts if you + already run one from source). Ad-hoc signed — right-click → + Open the first time. +2. **The extension**: `chrome://extensions` → Developer mode → + Load unpacked → select `apps/extension/` from the repo. +3. Work normally. Next interruption, press **⌃Space**. + +Running from source still works and always wins: if a daemon is +already on 4545, the app uses it and starts nothing. ## Known edges - macOS Apple Silicon only; Windows/Linux are on the roadmap - Unsigned build (Gatekeeper warning is expected; notarization lands with a paid certificate) -- The engine requires Python 3.12+ until the bundled build ships +- **Semantic file search is not in the bundled engine** (it needs + the ~2 GB embedding stack) — `/v1/search/files` stays quietly + disabled unless you run the engine from source with + `pip install -r requirements.txt` - Desktop app-focus capture is opt-in (`desktop_capture_enabled`) Delete `~/.recall/` at any time — that is the full reset, and the diff --git a/recall-daemon.spec b/recall-daemon.spec new file mode 100644 index 0000000..132bb3f --- /dev/null +++ b/recall-daemon.spec @@ -0,0 +1,71 @@ +# PyInstaller spec — the bundled Recall engine (`recall-daemon`). +# +# One small headless binary: the FastAPI service, the seven-layer +# engine, capture ingest, and the desktop-focus watcher. Deliberately +# EXCLUDES the GUI (PyQt6) and the file-search stack (chromadb + +# sentence-transformers + torch, ~2 GB) — /v1/search/files answers +# `enabled: false` until the full stack is present, which the whole +# product treats as a calm state. +# +# Build: pyinstaller --noconfirm recall-daemon.spec +# Test : HOME=$(mktemp -d) dist/recall-daemon --service +# Ship : apps/launcher/src-tauri/binaries/recall-daemon- + +a = Analysis( + ["recall.py"], + pathex=[], + binaries=[], + datas=[], + hiddenimports=[ + # uvicorn's runtime imports are dynamic + "uvicorn.logging", + "uvicorn.loops.auto", + "uvicorn.protocols.http.auto", + "uvicorn.protocols.websockets.auto", + "uvicorn.lifespan.on", + # the desktop probes are imported by platform dispatch + "app.core.desktop.darwin", + "app.core.desktop.watcher", + ], + excludes=[ + # GUI — never in the daemon + "PyQt6", + "PyQt6.QtCore", + "PyQt6.QtGui", + "PyQt6.QtWidgets", + # the optional file-search stack (service.py degrades cleanly) + "chromadb", + "sentence_transformers", + "torch", + "transformers", + "onnxruntime", + "tokenizers", + "scipy", + "sklearn", + "pandas", + "matplotlib", + "PIL", + ], + noarchive=False, +) + +pyz = PYZ(a.pure) + +exe = EXE( + pyz, + a.scripts, + a.binaries, + a.datas, + [], + name="recall-daemon", + debug=False, + bootloader_ignore_signals=False, + strip=False, + upx=False, + console=True, + disable_windowed_traceback=False, + argv_emulation=False, + target_arch=None, + codesign_identity=None, + entitlements_file=None, +)