textlog 0.1.2

macOS clipboard + OCR daemon exposed to Claude Code as an MCP server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Capture pipeline: clipboard event → privacy filter → OCR (images
//! only) → SHA-256 → Storage::insert → notifier + clipboard write-back.
//!
//! `Pipeline::process_event` is the unit-testable core; `Pipeline::run`
//! adds the polling task and the consumer loop and is exercised by
//! `tl start --foreground`.

use std::sync::atomic::AtomicI64;
use std::sync::Arc;
use std::time::Duration;

use chrono::Utc;
use sha2::{Digest, Sha256};
use tokio::sync::mpsc;

use crate::clipboard::{self, ClipboardEvent, ClipboardWriter};
use crate::config::Config;
use crate::error::{Error, Result};
use crate::filters::PrivacyFilter;
use crate::notifier::Notifier;
use crate::storage::{markdown, CaptureRow, Kind, Storage};

const CHANNEL_CAPACITY: usize = 16;

pub struct Pipeline {
    cfg: Config,
    storage: Arc<Storage>,
    notifier: Arc<dyn Notifier>,
    clipboard_writer: Arc<dyn ClipboardWriter>,
    self_write_token: Arc<AtomicI64>,
    privacy_filter: PrivacyFilter,
}

impl Pipeline {
    pub fn new(
        cfg: Config,
        storage: Arc<Storage>,
        notifier: Arc<dyn Notifier>,
        clipboard_writer: Arc<dyn ClipboardWriter>,
        self_write_token: Arc<AtomicI64>,
    ) -> Result<Self> {
        let privacy_filter = PrivacyFilter::from_config(&cfg.monitoring, &cfg.privacy)?;
        Ok(Self {
            cfg,
            storage,
            notifier,
            clipboard_writer,
            self_write_token,
            privacy_filter,
        })
    }

    /// Process one event: filter → OCR → store → notify. Returns `Ok`
    /// even when the event is intentionally dropped (empty bytes,
    /// sub-min length, sensitive content). Hard errors (storage write
    /// failed, OCR failed) bubble up.
    pub async fn process_event(&self, ev: ClipboardEvent) -> Result<()> {
        if ev.bytes.is_empty() {
            return Ok(());
        }

        // Min-length only applies to text (an image of any size is
        // signal even if the file is small).
        if ev.kind == Kind::Text && ev.bytes.len() < self.cfg.monitoring.min_length {
            return Ok(());
        }

        // Privacy filter — text only.
        if ev.kind == Kind::Text {
            let s = std::str::from_utf8(&ev.bytes).unwrap_or("");
            if self.privacy_filter.is_sensitive(s) {
                if self.cfg.privacy.show_filter_notification {
                    let _ = self
                        .notifier
                        .notify_capture("textlog dropped a sensitive clipboard entry");
                }
                return Ok(());
            }
        }

        // OCR (images only). Vision is sync — push it off the executor.
        let (content, ocr_confidence) = match ev.kind {
            Kind::Text => (
                Some(String::from_utf8_lossy(&ev.bytes).into_owned()),
                None,
            ),
            Kind::Image => {
                let cfg = self.cfg.ocr.clone();
                let bytes = ev.bytes.clone();
                let r = tokio::task::spawn_blocking(move || crate::ocr::ocr_image(&bytes, &cfg))
                    .await
                    .map_err(|e| Error::Ocr(format!("ocr task join: {e}")))??;
                (Some(r.text), Some(r.confidence))
            }
            Kind::File => (None, None),
        };

        // Hash + build CaptureRow.
        let mut h = Sha256::new();
        h.update(&ev.bytes);
        let sha: [u8; 32] = h.finalize().into();
        let ts = Utc::now();
        let md_path = markdown::daily_path(
            &self.cfg.storage.log_dir,
            &self.cfg.storage.date_format,
            ts,
        );
        let row = CaptureRow {
            id: 0,
            ts,
            kind: ev.kind,
            sha256: sha,
            size_bytes: ev.bytes.len(),
            content,
            ocr_confidence,
            source_app: None,
            source_url: None,
            md_path: md_path.clone(),
        };

        // Storage::insert is sync (mutex on rusqlite::Connection); push
        // it off the executor so concurrent MCP requests aren't
        // blocked.
        let storage = Arc::clone(&self.storage);
        let row_clone = row.clone();
        tokio::task::spawn_blocking(move || storage.insert(&row_clone))
            .await
            .map_err(|e| Error::Storage(format!("insert task join: {e}")))??;

        // Per-capture notification (default off).
        if self.cfg.notifications.enabled && self.cfg.notifications.on_capture {
            let summary = match ev.kind {
                Kind::Text => "captured text",
                Kind::Image => "captured image",
                Kind::File => "captured file",
            };
            let _ = self.notifier.notify_capture(summary);
        }

        // Completion notification + optional path-back-to-clipboard.
        let _ = self.notifier.notify_complete(&md_path);
        if self.cfg.notifications.copy_log_path_on_complete {
            let path_str = md_path.to_string_lossy().into_owned();
            let writer = Arc::clone(&self.clipboard_writer);
            let _ = tokio::task::spawn_blocking(move || writer.write_text(&path_str))
                .await
                .map_err(|e| Error::ClipboardAccess(format!("write_text join: {e}")))?;
        }

        Ok(())
    }

    /// Run forever: poll the system clipboard, push events through a
    /// bounded channel, drain into `process_event`. Returns when either
    /// task exits (typically on shutdown signal).
    pub async fn run(self: Arc<Self>) -> Result<()> {
        let (tx, mut rx) = mpsc::channel::<ClipboardEvent>(CHANNEL_CAPACITY);
        let interval = Duration::from_millis(self.cfg.monitoring.poll_interval_ms.max(50));
        let token = Arc::clone(&self.self_write_token);

        let monitor = tokio::spawn(monitor_loop(interval, token, tx));
        let consumer = {
            let me = Arc::clone(&self);
            tokio::spawn(async move {
                while let Some(ev) = rx.recv().await {
                    if let Err(e) = me.process_event(ev).await {
                        tracing::error!(?e, "pipeline process_event failed");
                    }
                }
            })
        };

        tokio::select! {
            r = monitor => {
                r.map_err(|e| Error::ClipboardAccess(format!("monitor task panicked: {e}")))?;
            }
            r = consumer => {
                r.map_err(|e| Error::Storage(format!("consumer task panicked: {e}")))?;
            }
        }
        Ok(())
    }
}

async fn monitor_loop(
    interval: Duration,
    token: Arc<AtomicI64>,
    tx: mpsc::Sender<ClipboardEvent>,
) {
    let mut last = clipboard::current_change_count();
    let mut ticker = tokio::time::interval(interval);
    ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
    loop {
        ticker.tick().await;
        let token = Arc::clone(&token);
        let result =
            tokio::task::spawn_blocking(move || clipboard::poll_once(&token, last)).await;
        match result {
            Ok(Ok(Some(ev))) => {
                last = ev.change_count;
                if ev.bytes.is_empty() {
                    // Nothing to enqueue — but keep `last` updated so we
                    // don't re-scan the same change count next tick.
                    continue;
                }
                if tx.try_send(ev).is_err() {
                    tracing::warn!(
                        "clipboard channel full ({CHANNEL_CAPACITY}); dropping event"
                    );
                }
            }
            Ok(Ok(None)) => {}
            Ok(Err(e)) => tracing::error!(?e, "clipboard poll error"),
            Err(e) => {
                tracing::error!(?e, "clipboard poll task panicked");
                return;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::clipboard::{ClipboardEvent, CountingClipboardWriter, NullClipboardWriter};
    use crate::notifier::CountingNotifier;
    use std::path::PathBuf;
    use tempfile::TempDir;

    fn cfg_with_tmp(tmp: &TempDir) -> Config {
        let mut cfg = Config::default();
        cfg.storage.sqlite_path = tmp
            .path()
            .join("index.db")
            .to_string_lossy()
            .into_owned();
        cfg.storage.log_dir = tmp.path().join("logs").to_string_lossy().into_owned();
        cfg
    }

    fn build_pipeline(
        cfg: Config,
        tmp: &TempDir,
        notifier: Arc<CountingNotifier>,
        writer: Arc<CountingClipboardWriter>,
    ) -> (Arc<Pipeline>, PathBuf) {
        let storage = Arc::new(
            Storage::open(tmp.path().join("index.db"), cfg.storage.ring_buffer_size).unwrap(),
        );
        let token = Arc::new(AtomicI64::new(0));
        let p = Pipeline::new(
            cfg,
            Arc::clone(&storage) as Arc<Storage>,
            notifier as Arc<dyn Notifier>,
            writer as Arc<dyn ClipboardWriter>,
            token,
        )
        .unwrap();
        (Arc::new(p), tmp.path().to_path_buf())
    }

    fn text_event(s: &str, cc: i64) -> ClipboardEvent {
        ClipboardEvent {
            kind: Kind::Text,
            bytes: s.as_bytes().to_vec(),
            change_count: cc,
        }
    }

    #[tokio::test]
    async fn empty_event_is_dropped_silently() {
        let tmp = TempDir::new().unwrap();
        let cfg = cfg_with_tmp(&tmp);
        let notifier = Arc::new(CountingNotifier::new());
        let writer = Arc::new(CountingClipboardWriter::new());
        let (p, _) = build_pipeline(cfg, &tmp, Arc::clone(&notifier), Arc::clone(&writer));

        p.process_event(ClipboardEvent {
            kind: Kind::Text,
            bytes: Vec::new(),
            change_count: 1,
        })
        .await
        .unwrap();

        assert_eq!(notifier.completed(), 0);
        assert_eq!(notifier.captured(), 0);
        assert!(writer.calls().is_empty());
    }

    #[tokio::test]
    async fn sub_min_length_text_is_dropped() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = cfg_with_tmp(&tmp);
        cfg.monitoring.min_length = 50;
        let notifier = Arc::new(CountingNotifier::new());
        let writer = Arc::new(NullClipboardWriter);
        let (p, _) = build_pipeline(
            cfg,
            &tmp,
            Arc::clone(&notifier),
            Arc::new(CountingClipboardWriter::new()),
        );

        let _ = writer; // silence unused
        p.process_event(text_event("short", 1)).await.unwrap();
        assert_eq!(notifier.completed(), 0);
    }

    #[tokio::test]
    async fn normal_text_event_inserts_and_notifies() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = cfg_with_tmp(&tmp);
        cfg.monitoring.min_length = 1;
        cfg.privacy.filter_enabled = false;
        cfg.notifications.copy_log_path_on_complete = false;
        let notifier = Arc::new(CountingNotifier::new());
        let writer = Arc::new(CountingClipboardWriter::new());
        let (p, _) = build_pipeline(cfg, &tmp, Arc::clone(&notifier), Arc::clone(&writer));

        p.process_event(text_event("hello world", 1)).await.unwrap();

        assert_eq!(notifier.completed(), 1);
        assert!(writer.calls().is_empty(), "no copy-back when flag is off");

        // Re-open same storage to confirm the row landed.
        let storage = Storage::open(tmp.path().join("index.db"), 100).unwrap();
        let rows = storage.get_recent(10, None).unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].content.as_deref(), Some("hello world"));
    }

    #[tokio::test]
    async fn sensitive_text_is_filtered_and_notified() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = cfg_with_tmp(&tmp);
        cfg.monitoring.min_length = 1;
        cfg.privacy.filter_enabled = true;
        cfg.privacy.show_filter_notification = true;
        let notifier = Arc::new(CountingNotifier::new());
        let writer = Arc::new(NullClipboardWriter);
        let (p, _) = build_pipeline(
            cfg,
            &tmp,
            Arc::clone(&notifier),
            Arc::new(CountingClipboardWriter::new()),
        );

        let _ = writer;
        // OpenAI-style key — matches default ignore patterns.
        p.process_event(text_event("sk-1234567890abcdefghij", 1))
            .await
            .unwrap();

        assert_eq!(notifier.captured(), 1, "filter notification fired");
        assert_eq!(notifier.completed(), 0, "no insert → no completion");

        let storage = Storage::open(tmp.path().join("index.db"), 100).unwrap();
        assert!(storage.get_recent(10, None).unwrap().is_empty());
    }

    #[tokio::test]
    async fn copy_log_path_writes_clipboard_when_enabled() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = cfg_with_tmp(&tmp);
        cfg.monitoring.min_length = 1;
        cfg.privacy.filter_enabled = false;
        cfg.notifications.enabled = true;
        cfg.notifications.on_complete = true;
        cfg.notifications.copy_log_path_on_complete = true;
        let notifier = Arc::new(CountingNotifier::new());
        let writer = Arc::new(CountingClipboardWriter::new());
        let (p, _) = build_pipeline(cfg, &tmp, Arc::clone(&notifier), Arc::clone(&writer));

        p.process_event(text_event("a useful clipboard payload", 1))
            .await
            .unwrap();

        assert_eq!(notifier.completed(), 1);
        let calls = writer.calls();
        assert_eq!(calls.len(), 1, "expected one clipboard write-back");
        assert!(
            calls[0].ends_with(".md"),
            "wrote the daily MD path; got {:?}",
            calls[0]
        );
    }

    #[tokio::test]
    async fn on_capture_notification_fires_when_configured() {
        let tmp = TempDir::new().unwrap();
        let mut cfg = cfg_with_tmp(&tmp);
        cfg.monitoring.min_length = 1;
        cfg.privacy.filter_enabled = false;
        cfg.notifications.enabled = true;
        cfg.notifications.on_capture = true;
        cfg.notifications.copy_log_path_on_complete = false;
        let notifier = Arc::new(CountingNotifier::new());
        let (p, _) = build_pipeline(
            cfg,
            &tmp,
            Arc::clone(&notifier),
            Arc::new(CountingClipboardWriter::new()),
        );

        p.process_event(text_event("payload", 1)).await.unwrap();

        assert_eq!(notifier.captured(), 1, "on_capture should fire");
        assert_eq!(notifier.completed(), 1);
    }
}