YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat(privacy): per-field PII redaction toggles (text + image)
Louis Beaumont7a1e3784d6ec
diff --git a/apps/screenpipe-app-tauri/components/settings/privacy-section.tsx b/apps/screenpipe-app-tauri/components/settings/privacy-section.tsxindex 563065c33..0cb4f9308 100644--- a/apps/screenpipe-app-tauri/components/settings/privacy-section.tsx+++ b/apps/screenpipe-app-tauri/components/settings/privacy-section.tsx@@ -462,6 +462,43 @@ export function PrivacySection() {handleSettingsChange({ piiBackend: next } as any, true);};+ // Which PII classes the AI workers actually remove. Secret is the+ // always-on baseline (the backend forces it in too — see+ // screenpipe_redact::parse_allow_list); the rest are opt-in. Stored+ // as canonical snake_case SpanLabel names in `piiRedactionLabels`.+ // The model detects every class, but only the selected ones get+ // redacted — everything else stays as searchable timeline value.+ const PII_FIELD_OPTIONS: {+ value: string;+ label: string;+ desc: string;+ always?: boolean;+ }[] = [+ { value: "secret", label: "Secrets", desc: "passwords, API keys, tokens", always: true },+ { value: "person", label: "Names", desc: "people's names" },+ { value: "email", label: "Emails", desc: "email addresses" },+ { value: "phone", label: "Phone numbers", desc: "phone numbers" },+ { value: "address", label: "Addresses", desc: "postal addresses" },+ { value: "sensitive", label: "Sensitive info", desc: "health, financial, identity context" },+ ];++ const piiRedactionLabels = useMemo<string[]>(() => {+ const raw = (settings.piiRedactionLabels as string[] | undefined) ?? ["secret"];+ // Secret is always implied, regardless of what's persisted.+ return raw.includes("secret") ? raw : ["secret", ...raw];+ }, [settings.piiRedactionLabels]);++ const handlePiiLabelToggle = (value: string, checked: boolean) => {+ if (value === "secret") return; // always-on baseline; can't be unchecked+ const next = new Set(piiRedactionLabels);+ if (checked) next.add(value);+ else next.delete(value);+ next.add("secret"); // never drop the baseline+ // Persist in the canonical option order so diffs stay stable.+ const ordered = PII_FIELD_OPTIONS.map((o) => o.value).filter((v) => next.has(v));+ handleSettingsChange({ piiRedactionLabels: ordered } as Partial<Settings>, true);+ };+const handleIncognitoToggle = (checked: boolean) => {handleSettingsChange({ ignoreIncognitoWindows: checked }, true);};@@ -1070,6 +1107,50 @@ export function PrivacySection() {</span></span></label>++ <p className="text-xs font-medium text-foreground pt-2">+ Fields to redact+ </p>+ {PII_FIELD_OPTIONS.map((opt) => {+ const checked =+ opt.always || piiRedactionLabels.includes(opt.value);+ return (+ <label+ key={opt.value}+ className={cn(+ "flex items-start gap-2 text-xs",+ opt.always ? "cursor-default" : "cursor-pointer",+ )}+ >+ <input+ type="checkbox"+ className="mt-0.5"+ checked={checked}+ disabled={opt.always}+ onChange={(e) =>+ handlePiiLabelToggle(opt.value, e.target.checked)+ }+ />+ <span>+ <span className="font-medium text-foreground">+ {opt.label}+ </span>+ {opt.always && (+ <span className="text-muted-foreground">+ {" "}(always on)+ </span>+ )}+ <span className="text-muted-foreground">+ {" "}— {opt.desc}+ </span>+ </span>+ </label>+ );+ })}+ <p className="text-[11px] text-muted-foreground pt-0.5">+ Unselected types stay visible so your timeline remains+ searchable. Secrets are always removed.+ </p></div>)}</CardContent>diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.tsindex b585986f4..9173e345d 100644--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts@@ -2177,6 +2177,19 @@ asyncImagePiiRedaction?: boolean;* Tinfoil operator. Tracked separately; structured for swap-in.*/piiBackend?: string;+/**+ * Which PII classes the AI redaction workers actually rewrite+ * when `asyncPiiRedaction` / `asyncImagePiiRedaction` are on.+ * Canonical snake_case `SpanLabel` names (e.g.+ * `["secret", "email", "person"]`). The models detect every+ * class but only these are removed — the rest is *value* (a+ * searchable timeline). Defaults to `["secret"]`, the safety+ * baseline; `secret` is always treated as included regardless of+ * what's stored (see screenpipe-redact `parse_allow_list`). The+ * Settings UI surfaces a curated subset (Names, Emails, Phones,+ * Addresses, Sensitive) as opt-in checkboxes.+ */+piiRedactionLabels?: string[];/*** Screenpipe cloud user ID. Empty string means not logged in.* Kept as String (not Option) to match existing store.bin schema.diff --git a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rsindex dafb8e4b7..3074407eb 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs@@ -616,6 +616,14 @@ impl ServerCore {let backend = config.pii_backend.as_str();let use_tinfoil = matches!(backend, "tinfoil" | "cloud" | "enclave");+ // User-selected redaction classes (the `piiRedactionLabels`+ // setting, default ["secret"]). Local adapters return spans and+ // we filter client-side via the text/image policies built from+ // this list; the tinfoil adapters forward the raw list so the+ // enclave filters server-side. `secret` is always included+ // regardless (see screenpipe_redact::parse_allow_list).+ let pii_labels = config.pii_redaction_labels.clone();+// Cloud Clerk JWT — same token used for the cloud transcription// bearer (see line 96). Tinfoil's enclave is on the screenpipe// cloud auth boundary, so the user's signed-in token is what@@ -638,6 +646,7 @@ impl ServerCore {use screenpipe_redact::pipeline::{Pipeline, PipelineConfig};use screenpipe_redact::worker::{Worker, WorkerConfig, ALL_TARGET_TABLES};use screenpipe_redact::Redactor;+ use screenpipe_redact::TextRedactionPolicy;// Backend selection for the text "AI" step:// - "local" → on-device candle OPF v3 (opf-rs). First@@ -660,9 +669,16 @@ impl ServerCore {);let ai: Arc<dyn Redactor> = Arc::new(TinfoilRedactor::new(TinfoilConfig {api_key: tinfoil_api_key.clone(),+ labels: pii_labels.clone(),..Default::default()}));- let pipeline = Pipeline::regex_then_ai(ai, PipelineConfig::default());+ let pipeline = Pipeline::regex_then_ai(+ ai,+ PipelineConfig {+ policy: TextRedactionPolicy::from_labels(&pii_labels),+ ..Default::default()+ },+ );let pipeline_arc = Arc::new(pipeline) as Arc<dyn Redactor>;let cfg = WorkerConfig {tables: ALL_TARGET_TABLES.to_vec(),@@ -677,7 +693,9 @@ impl ServerCore {// task once the model is ready.let pool = db.pool.clone();let shutdown = redact_shutdown.clone();+ let labels = pii_labels.clone();tokio::spawn(async move {+ let policy = TextRedactionPolicy::from_labels(&labels);// Prefer v45 phase 3 ONNX (~278 MB INT8, HIPAA 90.2%,// sub-10 ms p50, gets CoreML on macOS / DirectML on// Windows / CPU on Linux via the redact-onnx-* CI@@ -697,7 +715,13 @@ impl ServerCore {v45_phase3_onnx)");let ai: Arc<dyn Redactor> = Arc::new(adapter);- Pipeline::regex_then_ai(ai, PipelineConfig::default())+ Pipeline::regex_then_ai(+ ai,+ PipelineConfig {+ policy: policy.clone(),+ ..Default::default()+ },+ )}Err(onnx_err) => {warn!(@@ -711,7 +735,13 @@ impl ServerCore {(backend=local, opf-rs fallback)");let ai: Arc<dyn Redactor> = Arc::new(adapter);- Pipeline::regex_then_ai(ai, PipelineConfig::default())+ Pipeline::regex_then_ai(+ ai,+ PipelineConfig {+ policy: policy.clone(),+ ..Default::default()+ },+ )}Err(e) => {warn!(@@ -720,7 +750,7 @@ impl ServerCore {to 'tinfoil' in Settings → Privacy → AI PII removal \to use the cloud enclave instead.");- Pipeline::regex_only()+ Pipeline::regex_only_with_policy(policy.clone())}}}@@ -741,6 +771,7 @@ impl ServerCore {TinfoilImageConfig, TinfoilImageRedactor,};use screenpipe_redact::image::worker::{ImageWorker, ImageWorkerConfig};+ use screenpipe_redact::ImageRedactionPolicy;use screenpipe_redact::ImageRedactor;let pool = db.pool.clone();@@ -752,23 +783,38 @@ impl ServerCore {let detector =Arc::new(TinfoilImageRedactor::new(TinfoilImageConfig {api_key: tinfoil_api_key.clone(),+ labels: pii_labels.clone(),..Default::default()})) as Arc<dyn ImageRedactor>;- let _ = ImageWorker::new(pool, detector, ImageWorkerConfig::default())- .spawn_with_shutdown(redact_shutdown.clone());+ let _ = ImageWorker::new(+ pool,+ detector,+ ImageWorkerConfig {+ policy: ImageRedactionPolicy::from_labels(&pii_labels),+ ..Default::default()+ },+ )+ .spawn_with_shutdown(redact_shutdown.clone());} else {// Local mode: rfdetr_v8 ONNX. First-run downloads// ~108 MB from huggingface.co/screenpipe/pii-image-redactor// and verifies SHA-256 before landing in ~/.screenpipe/models/.let shutdown = redact_shutdown.clone();+ let labels = pii_labels.clone();tokio::spawn(async move {match RfdetrRedactor::load_or_download(RfdetrConfig::default()).await {Ok(detector) => {info!("starting async image-PII worker (backend=local)");let detector_arc = Arc::new(detector) as Arc<dyn ImageRedactor>;- let _ =- ImageWorker::new(pool, detector_arc, ImageWorkerConfig::default())- .spawn_with_shutdown(shutdown);+ let _ = ImageWorker::new(+ pool,+ detector_arc,+ ImageWorkerConfig {+ policy: ImageRedactionPolicy::from_labels(&labels),+ ..Default::default()+ },+ )+ .spawn_with_shutdown(shutdown);}Err(e) => {warn!(diff --git a/crates/screenpipe-config/src/recording.rs b/crates/screenpipe-config/src/recording.rsindex 1ed6051bc..d490102be 100644--- a/crates/screenpipe-config/src/recording.rs+++ b/crates/screenpipe-config/src/recording.rs@@ -362,6 +362,19 @@ pub struct RecordingSettings {#[serde(rename = "piiBackend", default = "default_pii_backend")]pub pii_backend: String,+ /// Which PII classes the AI redaction workers actually rewrite+ /// when `asyncPiiRedaction` / `asyncImagePiiRedaction` are on.+ /// Canonical snake_case `SpanLabel` names (e.g.+ /// `["secret", "email", "person"]`). The models detect every+ /// class but only these are removed — the rest is *value* (a+ /// searchable timeline). Defaults to `["secret"]`, the safety+ /// baseline; `secret` is always treated as included regardless of+ /// what's stored (see screenpipe-redact `parse_allow_list`). The+ /// Settings UI surfaces a curated subset (Names, Emails, Phones,+ /// Addresses, Sensitive) as opt-in checkboxes.+ #[serde(rename = "piiRedactionLabels", default = "default_pii_redaction_labels")]+ pub pii_redaction_labels: Vec<String>,+// ── Cloud / Auth ───────────────────────────────────────────────────/// Screenpipe cloud user ID. Empty string means not logged in./// Kept as String (not Option) to match existing store.bin schema.@@ -541,6 +554,7 @@ impl Default for RecordingSettings {async_pii_redaction: false,async_image_pii_redaction: false,pii_backend: default_pii_backend(),+ pii_redaction_labels: default_pii_redaction_labels(),user_id: String::new(),user_name: None,openai_compatible_endpoint: None,@@ -595,6 +609,12 @@ fn default_pii_backend() -> String {"local".to_string()}+/// Default redaction allow-list: secrets only. The safety baseline —+/// credentials are the one class where a miss is genuinely dangerous.+fn default_pii_redaction_labels() -> Vec<String> {+ vec!["secret".to_string()]+}+fn default_hd_recording_default() -> String {"ask".to_string()}diff --git a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs b/crates/screenpipe-engine/src/bin/screenpipe-engine.rsindex 759c9b392..4b8a31f99 100644--- a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs+++ b/crates/screenpipe-engine/src/bin/screenpipe-engine.rs@@ -1713,11 +1713,11 @@ async fn main() -> anyhow::Result<()> {adapters::{onnx::{OnnxConfig, OnnxRedactor},opf::{OpfAdapter, OpfConfig},- tinfoil::TinfoilRedactor,+ tinfoil::{TinfoilConfig, TinfoilRedactor},},pipeline::{Pipeline, PipelineConfig},worker::{Worker, WorkerConfig, ALL_TARGET_TABLES},- Redactor,+ Redactor, TextRedactionPolicy,};use std::sync::Arc;@@ -1741,7 +1741,13 @@ async fn main() -> anyhow::Result<()> {// 4. Regex-only otherwise (still destructive — overwrites// regex-redacted text into the source columns).let pool = db.pool.clone();+ let labels = config.pii_redaction_labels.clone();tokio::spawn(async move {+ // Per-label allow-list from the `piiRedactionLabels` setting+ // (default ["secret"]). Local adapters filter client-side via+ // this policy; the env-gated tinfoil fallback forwards the+ // raw labels so the enclave filters server-side.+ let policy = TextRedactionPolicy::from_labels(&labels);info!("fetching v45 phase 3 ONNX text redactor (~278 MB INT8 on first run, \cached at ~/.screenpipe/models/v45_phase3_onnx/)"@@ -1753,7 +1759,13 @@ async fn main() -> anyhow::Result<()> {desktop app + Tinfoil container, sub-10 ms p50 on CPU");let ai: Arc<dyn Redactor> = Arc::new(adapter);- Pipeline::regex_then_ai(ai, PipelineConfig::default())+ Pipeline::regex_then_ai(+ ai,+ PipelineConfig {+ policy: policy.clone(),+ ..Default::default()+ },+ )}Err(onnx_err) => {tracing::warn!(@@ -1776,7 +1788,13 @@ async fn main() -> anyhow::Result<()> {let adapter = Arc::new(adapter);let _unloader = Arc::clone(&adapter).spawn_idle_unloader();let ai: Arc<dyn Redactor> = adapter;- Pipeline::regex_then_ai(ai, PipelineConfig::default())+ Pipeline::regex_then_ai(+ ai,+ PipelineConfig {+ policy: policy.clone(),+ ..Default::default()+ },+ )}Err(e) => {if std::env::var("TINFOIL_API_KEY").is_ok()@@ -1786,15 +1804,26 @@ async fn main() -> anyhow::Result<()> {"text-PII AI step: tinfoil enclave (local adapters \unavailable: opf-rs={e})");- let ai: Arc<dyn Redactor> = Arc::new(TinfoilRedactor::from_env());- Pipeline::regex_then_ai(ai, PipelineConfig::default())+ let ai: Arc<dyn Redactor> = Arc::new(TinfoilRedactor::new(+ TinfoilConfig {+ labels: labels.clone(),+ ..Default::default()+ },+ ));+ Pipeline::regex_then_ai(+ ai,+ PipelineConfig {+ policy: policy.clone(),+ ..Default::default()+ },+ )} else {tracing::warn!("text-PII AI step disabled — both v45 ONNX and opf-rs \unavailable ({e}), and no TINFOIL_* env vars set. Worker \will run regex-only.");- Pipeline::regex_only()+ Pipeline::regex_only_with_policy(policy.clone())}}}@@ -1829,7 +1858,7 @@ async fn main() -> anyhow::Result<()> {if config.async_image_pii_redaction {use screenpipe_redact::adapters::rfdetr::{RfdetrConfig, RfdetrRedactor};use screenpipe_redact::image::worker::{ImageWorker, ImageWorkerConfig};- use screenpipe_redact::ImageRedactor;+ use screenpipe_redact::{ImageRedactionPolicy, ImageRedactor};use std::sync::Arc;// Prefer the MLX runtime on Mac when the safetensors weights@@ -1894,7 +1923,10 @@ async fn main() -> anyhow::Result<()> {info!("starting async image-PII reconciliation worker (destructive overwrite of source JPGs)");- let cfg = ImageWorkerConfig::default();+ let cfg = ImageWorkerConfig {+ policy: ImageRedactionPolicy::from_labels(&config.pii_redaction_labels),+ ..Default::default()+ };let _img_handle = ImageWorker::new(db.pool.clone(), detector, cfg).spawn();}}diff --git a/crates/screenpipe-engine/src/cli/mod.rs b/crates/screenpipe-engine/src/cli/mod.rsindex 6be409727..115e825a1 100644--- a/crates/screenpipe-engine/src/cli/mod.rs+++ b/crates/screenpipe-engine/src/cli/mod.rs@@ -432,6 +432,13 @@ pub struct RecordArgs {#[arg(long, default_value = "local")]pub pii_backend: String,+ /// Which PII classes the AI redaction workers rewrite when enabled.+ /// Comma-separated canonical labels: secret, person, email, phone,+ /// address, sensitive, url, company, repo, handle, channel, id,+ /// date. `secret` is always included regardless. Default: secret.+ #[arg(long, value_delimiter = ',', default_value = "secret")]+ pub pii_redaction_labels: Vec<String>,+/// Filter music-dominant audio before transcription (reduces Spotify/YouTube music noise)#[arg(long, default_value_t = false)]pub filter_music: bool,@@ -647,6 +654,7 @@ pub struct RecordArgSources {pub async_pii_redaction: bool,pub async_image_pii_redaction: bool,pub pii_backend: bool,+ pub pii_redaction_labels: bool,pub filter_music: bool,pub disable_vision: bool,pub ignored_windows: bool,@@ -691,6 +699,7 @@ impl RecordArgSources {async_pii_redaction: from_command_line(record, "async_pii_redaction"),async_image_pii_redaction: from_command_line(record, "async_image_pii_redaction"),pii_backend: from_command_line(record, "pii_backend"),+ pii_redaction_labels: from_command_line(record, "pii_redaction_labels"),filter_music: from_command_line(record, "filter_music"),disable_vision: from_command_line(record, "disable_vision"),ignored_windows: from_command_line(record, "ignored_windows"),@@ -727,6 +736,7 @@ impl RecordArgSources {|| self.async_pii_redaction|| self.async_image_pii_redaction|| self.pii_backend+ || self.pii_redaction_labels|| self.filter_music|| self.disable_vision|| self.ignored_windows@@ -807,6 +817,7 @@ impl RecordArgs {async_pii_redaction: self.async_pii_redaction,async_image_pii_redaction: self.async_image_pii_redaction,pii_backend: self.pii_backend.clone(),+ pii_redaction_labels: self.pii_redaction_labels.clone(),filter_music: self.filter_music,audio_transcription_engine: engine_str.to_string(),transcription_mode: mode_str.to_string(),@@ -1049,6 +1060,9 @@ impl RecordArgs {if sources.pii_backend {settings.pii_backend = self.pii_backend.clone();}+ if sources.pii_redaction_labels {+ settings.pii_redaction_labels = self.pii_redaction_labels.clone();+ }if sources.filter_music {settings.filter_music = self.filter_music;}diff --git a/crates/screenpipe-engine/src/recording_config.rs b/crates/screenpipe-engine/src/recording_config.rsindex 45e1ee7e5..d86e30198 100644--- a/crates/screenpipe-engine/src/recording_config.rs+++ b/crates/screenpipe-engine/src/recording_config.rs@@ -46,6 +46,12 @@ pub struct RecordingConfig {/// One toggle covers both modalities; the user-facing UI is a/// single radio under the AI PII removal switch.pub pii_backend: String,+ /// Which PII classes the AI redaction workers rewrite. Canonical+ /// snake_case `SpanLabel` names; defaults to `["secret"]`, with+ /// `secret` always included. Mirrors the `piiRedactionLabels`+ /// setting; consumed when building the text + image worker+ /// policies.+ pub pii_redaction_labels: Vec<String>,/// Filter music-dominant audio before transcription using spectral analysispub filter_music: bool,@@ -227,6 +233,7 @@ impl RecordingConfig {async_pii_redaction: settings.async_pii_redaction,async_image_pii_redaction: settings.async_image_pii_redaction,pii_backend: settings.pii_backend.clone(),+ pii_redaction_labels: settings.pii_redaction_labels.clone(),filter_music: settings.filter_music,enable_workflow_events: settings.enable_workflow_events,audio_transcription_engine: engine_strdiff --git a/crates/screenpipe-redact/src/adapters/tinfoil.rs b/crates/screenpipe-redact/src/adapters/tinfoil.rsindex b1170a66b..4a5e6e2f4 100644--- a/crates/screenpipe-redact/src/adapters/tinfoil.rs+++ b/crates/screenpipe-redact/src/adapters/tinfoil.rs@@ -116,12 +116,24 @@ pub struct TinfoilConfig {pub api_key: Option<String>,/// Per-request HTTP timeout. Default: 60s.pub timeout: Option<Duration>,+ /// Canonical [`crate::SpanLabel`] snake_case names the enclave+ /// should redact (e.g. `["secret", "email", "person"]`). The+ /// enclave detects every class but only rewrites these. Empty =+ /// let the enclave use its own default (back-compat). The desktop+ /// app populates this from the `piiRedactionLabels` setting.+ pub labels: Vec<String>,}#[derive(Serialize)]struct FilterRequest<'a> {text: &'a str,include_spans: bool,+ /// Server-side allow-list. Older enclave builds ignore this field+ /// (pydantic drops unknown keys); newer builds filter to exactly+ /// these classes. Sent only when non-empty so an unconfigured+ /// caller falls back to the enclave's own default policy.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ labels: &'a Vec<String>,}#[derive(Deserialize)]@@ -150,6 +162,10 @@ pub struct TinfoilRedactor {/// the OpenAI chat path), so we keep the header logic local.bearer: Option<HeaderValue>,timeout: Duration,+ /// Server-side redaction allow-list (canonical snake_case label+ /// names). Forwarded on every `/filter` request; empty = enclave+ /// default.+ labels: Vec<String>,/// Cached attested client. RwLock so reads (the hot path) don't/// serialize, write lock only on (re-)attest. Lazy: the first/// `http()` call pays the ~1-2 s attestation handshake.@@ -206,6 +222,7 @@ impl TinfoilRedactor {repo,bearer,timeout: cfg.timeout.unwrap_or(DEFAULT_TIMEOUT),+ labels: cfg.labels,client: RwLock::new(None),has_auth,}@@ -357,6 +374,7 @@ impl TinfoilRedactor {.json(&FilterRequest {text,include_spans: false,+ labels: &self.labels,});if let Some(b) = &self.bearer {req = req.header(AUTHORIZATION, b.clone());@@ -407,6 +425,7 @@ mod tests {repo: Some("test/never".into()),api_key: None,timeout: None,+ labels: vec![],}}@@ -447,6 +466,7 @@ mod tests {repo: Some("test/never".into()),api_key: Some("test-token-abc".into()),timeout: None,+ labels: vec![],});assert!(r.has_auth(),@@ -465,6 +485,7 @@ mod tests {repo: Some("test/never".into()),api_key: None,timeout: None,+ labels: vec![],});assert!(!r.has_auth(), "no api key should mean no auth header");}diff --git a/crates/screenpipe-redact/src/adapters/tinfoil_image.rs b/crates/screenpipe-redact/src/adapters/tinfoil_image.rsindex 21c801f0a..d23a71698 100644--- a/crates/screenpipe-redact/src/adapters/tinfoil_image.rs+++ b/crates/screenpipe-redact/src/adapters/tinfoil_image.rs@@ -88,6 +88,12 @@ pub struct TinfoilImageConfig {/// Score floor sent to the server. Below this, the server drops/// detections before returning.pub threshold: f32,+ /// Canonical [`crate::SpanLabel`] snake_case names the enclave+ /// should return regions for (e.g. `["secret", "email"]`). The+ /// detector finds every class but only the requested ones come+ /// back. Empty = enclave default. Populated from the+ /// `piiRedactionLabels` setting.+ pub labels: Vec<String>,}/// See sibling `tinfoil::CachedClient` for the rationale on holding@@ -105,6 +111,9 @@ pub struct TinfoilImageRedactor {bearer: Option<HeaderValue>,timeout: Duration,threshold: f32,+ /// Server-side label allow-list forwarded on every request; empty =+ /// enclave default.+ labels: Vec<String>,client: RwLock<Option<CachedClient>>,has_auth: bool,}@@ -173,6 +182,7 @@ impl TinfoilImageRedactor {bearer,timeout: cfg.timeout.unwrap_or(DEFAULT_TIMEOUT),threshold,+ labels: cfg.labels,client: RwLock::new(None),has_auth,}@@ -235,6 +245,11 @@ impl TinfoilImageRedactor {struct DetectRequest<'a> {image_b64: &'a str,threshold: f32,+ /// Server-side label allow-list. Older enclave builds ignore this+ /// field (pydantic drops unknown keys); newer builds only return+ /// regions for these classes. Sent only when non-empty.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ labels: &'a Vec<String>,}#[derive(Debug, Deserialize)]@@ -276,6 +291,7 @@ impl ImageRedactor for TinfoilImageRedactor {.json(&DetectRequest {image_b64: &image_b64,threshold: self.threshold,+ labels: &self.labels,});if let Some(b) = &self.bearer {req = req.header(AUTHORIZATION, b.clone());@@ -358,6 +374,7 @@ mod tests {api_key: None,timeout: None,threshold: 0.0,+ labels: vec![],}}diff --git a/crates/screenpipe-redact/src/image/mod.rs b/crates/screenpipe-redact/src/image/mod.rsindex 83efada9f..a83bafb3e 100644--- a/crates/screenpipe-redact/src/image/mod.rs+++ b/crates/screenpipe-redact/src/image/mod.rs@@ -153,4 +153,15 @@ impl ImageRedactionPolicy {min_score: 0.50,}}++ /// Build a policy from user-configured label names (the+ /// `piiRedactionLabels` setting), keeping the default `min_score`.+ /// See [`crate::span::parse_allow_list`] — Secret is always+ /// included.+ pub fn from_labels(labels: &[String]) -> Self {+ Self {+ allow: crate::span::parse_allow_list(labels),+ ..Default::default()+ }+ }}diff --git a/crates/screenpipe-redact/src/pipeline.rs b/crates/screenpipe-redact/src/pipeline.rsindex 04d61842f..22b8d88f1 100644--- a/crates/screenpipe-redact/src/pipeline.rs+++ b/crates/screenpipe-redact/src/pipeline.rs@@ -106,12 +106,25 @@ pub struct Pipeline {impl Pipeline {/// Pipeline with regex only. Most useful for tests and as the- /// "off" state when the user disables AI redaction.+ /// "off" state when the user disables AI redaction. Uses the+ /// default (secrets-only) policy.pub fn regex_only() -> Self {+ Self::regex_only_with_policy(TextRedactionPolicy::default())+ }++ /// Regex-only pipeline with an explicit policy. Used as the local+ /// fallback when neither AI adapter loads but the user still+ /// selected classes the deterministic regex pass can catch+ /// (emails, phones, cards, connection strings, …) — without this+ /// those would silently stop being redacted.+ pub fn regex_only_with_policy(policy: TextRedactionPolicy) -> Self {Self {regex: RegexRedactor::new(),ai: None,- cfg: PipelineConfig::default(),+ cfg: PipelineConfig {+ policy,+ ..Default::default()+ },cache: RedactionCache::with_defaults(),}}@@ -176,16 +189,29 @@ impl Redactor for Pipeline {let ai = self.ai.as_ref().expect("checked above");match ai.redact(¤t.redacted).await {Ok(ai_out) => {- // Filter AI output to the same policy + re-render- // its `redacted` from its `input` (= the- // regex-redacted text). Now the AI's redacted- // string carries only allowed-class- // placeholders, alongside the regex pass's- // already-allowed placeholders.- let ai_filtered = apply_policy(ai_out, &self.cfg.policy);+ let redacted = if ai_out.spans.is_empty() {+ // Span-less adapter (the Tinfoil enclave+ // returns redacted text only, no spans). It+ // already applied the label policy we sent+ // it server-side, so trust its output+ // verbatim. Running apply_policy here would+ // be wrong — it rebuilds `redacted` from+ // spans, of which there are none, and would+ // therefore throw the enclave's redaction+ // away and hand back the text we sent.+ ai_out.redacted+ } else {+ // Span-aware adapter (regex / local ONNX):+ // filter to the allow-list client-side + re-+ // render from `input` (= the regex-redacted+ // text). Now the AI's redacted string carries+ // only allowed-class placeholders, alongside+ // the regex pass's already-allowed ones.+ apply_policy(ai_out, &self.cfg.policy).redacted+ };current = RedactionOutput {input: current.input,- redacted: ai_filtered.redacted,+ redacted,spans: current.spans,};}@@ -297,6 +323,24 @@ mod tests {assert_eq!(ai.calls.load(Ordering::SeqCst), 1);}+ #[tokio::test]+ async fn span_less_ai_output_is_trusted() {+ // A span-less adapter (like the Tinfoil enclave, which returns+ // redacted text and no spans) must have its output used+ // verbatim — it applied the policy server-side. UppercaseAi+ // stands in for it: its `redacted` is the uppercased input with+ // an empty span list. Regression guard for the bug where+ // apply_policy rebuilt from the (empty) spans and silently+ // discarded the enclave's redaction.+ let ai = Arc::new(UppercaseAi::new());+ let p = Pipeline::regex_then_ai(ai, PipelineConfig::default());+ let out = p+ .redact("hello world this is a long enough sentence")+ .await+ .unwrap();+ assert_eq!(out.redacted, "HELLO WORLD THIS IS A LONG ENOUGH SENTENCE");+ }+#[tokio::test]async fn cache_short_circuits_ai_on_repeat() {let ai = Arc::new(UppercaseAi::new());diff --git a/crates/screenpipe-redact/src/span.rs b/crates/screenpipe-redact/src/span.rsindex 4d6080fed..d9c40910c 100644--- a/crates/screenpipe-redact/src/span.rs+++ b/crates/screenpipe-redact/src/span.rs@@ -64,6 +64,54 @@ impl SpanLabel {Self::Sensitive => "[SENSITIVE]",}}++ /// Parse the canonical snake_case wire name (the same form+ /// `#[serde(rename_all = "snake_case")]` emits) back into a label.+ /// Case-insensitive and whitespace-trimming so values coming from a+ /// settings file or CLI flag are forgiving. Returns `None` for+ /// unknown names — callers decide whether to ignore or error.+ pub fn from_wire(s: &str) -> Option<Self> {+ Some(match s.trim().to_ascii_lowercase().as_str() {+ "person" => Self::Person,+ "email" => Self::Email,+ "phone" => Self::Phone,+ "address" => Self::Address,+ "url" => Self::Url,+ "company" => Self::Company,+ "repo" => Self::Repo,+ "handle" => Self::Handle,+ "channel" => Self::Channel,+ "id" => Self::Id,+ "date" => Self::Date,+ "secret" => Self::Secret,+ "sensitive" => Self::Sensitive,+ _ => return None,+ })+ }+}++/// Parse user-configured label names (canonical snake_case [`SpanLabel`]+/// wire names) into a de-duplicated allow-list, preserving the caller's+/// order.+///+/// [`SpanLabel::Secret`] is **always** included regardless of input —+/// it's the safety baseline the user-facing "AI PII removal" toggle+/// promises, and silently dropping it would stop redacting leaked+/// credentials (the one class where a miss is genuinely dangerous). The+/// Settings UI enforces the same invariant by rendering Secret as an+/// always-on, disabled checkbox; this is the matching defense-in-depth+/// at the policy layer. Unknown names are ignored; an empty or+/// all-unknown input therefore yields exactly `[Secret]`.+pub fn parse_allow_list(labels: &[String]) -> Vec<SpanLabel> {+ let mut out: Vec<SpanLabel> = vec![SpanLabel::Secret];+ for raw in labels {+ if let Some(label) = SpanLabel::from_wire(raw) {+ if !out.contains(&label) {+ out.push(label);+ }+ }+ }+ out}/// A redacted region of an input string.@@ -111,8 +159,69 @@ impl Default for TextRedactionPolicy {}impl TextRedactionPolicy {+ /// Build a policy from user-configured label names (the+ /// `piiRedactionLabels` setting). See [`parse_allow_list`] — Secret+ /// is always included.+ pub fn from_labels(labels: &[String]) -> Self {+ Self {+ allow: parse_allow_list(labels),+ }+ }+/// Is this span eligible for redaction under the current policy?pub fn allows(&self, label: SpanLabel) -> bool {self.allow.contains(&label)}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn from_wire_round_trips_and_is_forgiving() {+ assert_eq!(SpanLabel::from_wire("person"), Some(SpanLabel::Person));+ assert_eq!(SpanLabel::from_wire(" Email "), Some(SpanLabel::Email));+ assert_eq!(SpanLabel::from_wire("SECRET"), Some(SpanLabel::Secret));+ assert_eq!(SpanLabel::from_wire("sensitive"), Some(SpanLabel::Sensitive));+ assert_eq!(SpanLabel::from_wire("nonsense"), None);+ assert_eq!(SpanLabel::from_wire(""), None);+ }++ #[test]+ fn parse_allow_list_always_includes_secret() {+ // Empty input → just the baseline.+ assert_eq!(parse_allow_list(&[]), vec![SpanLabel::Secret]);+ // All-unknown input → still just the baseline.+ assert_eq!(+ parse_allow_list(&["bogus".into(), "".into()]),+ vec![SpanLabel::Secret]+ );+ // A selection that omits "secret" still gets it forced in first.+ assert_eq!(+ parse_allow_list(&["email".into(), "person".into()]),+ vec![SpanLabel::Secret, SpanLabel::Email, SpanLabel::Person]+ );+ }++ #[test]+ fn parse_allow_list_dedupes_and_keeps_order() {+ assert_eq!(+ parse_allow_list(&[+ "secret".into(),+ "email".into(),+ "email".into(),+ "phone".into()+ ]),+ vec![SpanLabel::Secret, SpanLabel::Email, SpanLabel::Phone]+ );+ }++ #[test]+ fn text_policy_from_labels_matches_parse() {+ let p = TextRedactionPolicy::from_labels(&["email".into()]);+ assert!(p.allows(SpanLabel::Secret));+ assert!(p.allows(SpanLabel::Email));+ assert!(!p.allows(SpanLabel::Person));+ }+}