apoc 0.9.1

Agentic process control for LLMs
Documentation
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use futures::SinkExt;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::net::UnixStream;
use tokio::net::unix::OwnedWriteHalf;
use tokio::sync::{Mutex, oneshot};
use tokio_util::codec::{FramedWrite, LinesCodec};

use crate::model::now_ms;
use crate::store::state_dir;

pub const EXTENSION_PROTOCOL_VERSION: u64 = 1;
pub const EXTENSION_SOCKET_NAME: &str = "apoc-extension.sock";
pub const DEFAULT_EXTENSION_HOST_NAME: &str = "com.douglance.apoc";
pub const PACKAGED_EXTENSION_ID: &str = "agnjkkdhkkcmdeeeamngnokpbpciebbn";
const MAX_EXTENSION_EVENTS: usize = 1_000;
const PACKAGED_EXTENSION_ASSETS: &[(&str, &[u8])] = &[
    (
        "manifest.json",
        include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/extensions/chrome-extension/manifest.json"
        )),
    ),
    (
        "service-worker.js",
        include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/extensions/chrome-extension/service-worker.js"
        )),
    ),
    (
        "content-script.js",
        include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/extensions/chrome-extension/content-script.js"
        )),
    ),
    (
        "page-probe.js",
        include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/extensions/chrome-extension/page-probe.js"
        )),
    ),
];

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExtensionBridgeConnection {
    pub connected: bool,
    pub socket: String,
    pub host_name: Option<String>,
    pub extension_origin: Option<String>,
    pub extension_id: Option<String>,
    pub version: Option<String>,
    pub connected_at: Option<u64>,
    pub last_seen_at: Option<u64>,
    pub retained_events: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExtensionEvent {
    pub ts: u64,
    #[serde(default)]
    #[serde(alias = "tabId")]
    pub tab_id: Option<u64>,
    pub kind: String,
    #[serde(default)]
    pub url: Option<String>,
    #[serde(default)]
    pub method: Option<String>,
    #[serde(default)]
    pub level: Option<String>,
    #[serde(default)]
    pub message: Option<String>,
    #[serde(default)]
    pub data: Option<Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExtensionTab {
    pub id: u64,
    #[serde(default)]
    #[serde(alias = "windowId")]
    pub window_id: Option<u64>,
    #[serde(default)]
    pub active: Option<bool>,
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub url: Option<String>,
    #[serde(default)]
    pub status: Option<String>,
    #[serde(default)]
    pub attached: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExtensionRuntimeStatus {
    pub connected: bool,
    #[serde(default)]
    #[serde(alias = "extensionId")]
    pub extension_id: Option<String>,
    #[serde(default)]
    pub version: Option<String>,
    #[serde(default)]
    #[serde(alias = "tabId")]
    pub tab_id: Option<u64>,
    #[serde(default)]
    #[serde(alias = "attachedTabs")]
    pub attached_tabs: Vec<u64>,
    #[serde(default)]
    #[serde(alias = "observedTabs")]
    pub observed_tabs: Vec<ExtensionObservation>,
    #[serde(default)]
    #[serde(alias = "lastSeenTs")]
    pub last_seen_ts: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExtensionObservation {
    #[serde(alias = "tabId")]
    pub tab_id: u64,
    pub kinds: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExtensionStatusView {
    pub bridge: ExtensionBridgeConnection,
    pub extension: Option<ExtensionRuntimeStatus>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExtensionAttachResult {
    #[serde(default)]
    pub tab: Option<ExtensionTab>,
    #[serde(default)]
    pub attached: Option<bool>,
    #[serde(default)]
    pub detached: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExtensionEvaluation {
    pub value: Value,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExtensionCdpResult {
    pub cdp: Value,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExtensionSnapshotResult {
    pub snapshot: Value,
    #[serde(default)]
    #[serde(alias = "artifactPath")]
    pub artifact_path: Option<String>,
    #[serde(default)]
    #[serde(alias = "traceAnchor")]
    pub trace_anchor: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExtensionObserveResult {
    #[serde(default)]
    pub observing: Vec<ExtensionObservation>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExtensionHostInstallation {
    pub installed: bool,
    pub browser: String,
    pub manifest_path: String,
    pub manifest_backup: Option<String>,
    pub user_data_dir: Option<String>,
    pub host_path: String,
    pub extension_id: String,
    pub extension_path: String,
    pub extension_backup: Option<String>,
    pub extension_assets: Vec<ExtensionAsset>,
    pub manifest: Value,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExtensionAsset {
    pub name: String,
    pub path: String,
    pub bytes: u64,
    pub sha256: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExtensionDoctor {
    pub browser: String,
    pub manifest_path: String,
    pub user_data_dir: Option<String>,
    pub manifest_exists: bool,
    pub manifest_valid: bool,
    pub host_path: String,
    pub host_exists: bool,
    pub extension_id: String,
    pub extension_path: String,
    pub extension_exists: bool,
    pub extension_valid: bool,
    pub extension_assets: Vec<ExtensionAsset>,
    pub issues: Vec<String>,
}

pub fn install_extension_host(
    browser: &str,
    extension_id: &str,
    host_name: &str,
    host_path: Option<&str>,
    home: Option<&str>,
    user_data_dir: Option<&str>,
    dry_run: bool,
) -> Result<ExtensionHostInstallation, String> {
    validate_host_name(host_name)?;
    validate_extension_id(extension_id)?;
    let explicit_home = home.is_some();
    let home = resolve_home(home)?;
    let host_path = resolve_host_path(host_path)?;
    if !dry_run && !host_path.is_file() {
        return Err(format!(
            "Chrome native host executable does not exist: {}",
            host_path.display()
        ));
    }
    let user_data_dir = resolve_optional_path(user_data_dir, "user_data_dir")?;
    let manifest_path =
        extension_manifest_path(browser, host_name, &home, user_data_dir.as_deref())?;
    let extension_path = extension_install_path(&home, explicit_home)?;
    let (extension_assets, extension_backup) =
        install_packaged_extension(&extension_path, dry_run)?;
    let mut allowed_origins = vec![format!("chrome-extension://{PACKAGED_EXTENSION_ID}/")];
    let requested_origin = format!("chrome-extension://{extension_id}/");
    if requested_origin != allowed_origins[0] {
        allowed_origins.push(requested_origin);
    }
    let manifest = json!({
        "name":host_name,
        "description":"apoc Chrome native messaging host",
        "path":host_path.display().to_string(),
        "type":"stdio",
        "allowed_origins":allowed_origins
    });
    let mut manifest_backup = None;
    if !dry_run {
        let parent = manifest_path
            .parent()
            .ok_or_else(|| "extension manifest path has no parent".to_string())?;
        std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
        let temporary = manifest_path.with_extension(format!("json.{}.tmp", uuid::Uuid::now_v7()));
        std::fs::write(
            &temporary,
            serde_json::to_vec_pretty(&manifest).map_err(|error| error.to_string())?,
        )
        .map_err(|error| error.to_string())?;
        if manifest_path.exists() {
            let backup =
                manifest_path.with_extension(format!("json.backup-{}", uuid::Uuid::now_v7()));
            std::fs::rename(&manifest_path, &backup).map_err(|error| error.to_string())?;
            manifest_backup = Some(backup);
        }
        if let Err(error) = std::fs::rename(&temporary, &manifest_path) {
            let _ = std::fs::remove_file(&temporary);
            if let Some(backup) = manifest_backup.as_ref() {
                let _ = std::fs::rename(backup, &manifest_path);
            }
            return Err(error.to_string());
        }
    }
    Ok(ExtensionHostInstallation {
        installed: !dry_run,
        browser: browser.to_string(),
        manifest_path: manifest_path.display().to_string(),
        manifest_backup: manifest_backup.map(|path| path.display().to_string()),
        user_data_dir: user_data_dir.map(|path| path.display().to_string()),
        host_path: host_path.display().to_string(),
        extension_id: PACKAGED_EXTENSION_ID.to_string(),
        extension_path: extension_path.display().to_string(),
        extension_backup,
        extension_assets,
        manifest,
    })
}

pub fn extension_doctor(
    browser: &str,
    host_name: &str,
    host_path: Option<&str>,
    home: Option<&str>,
    user_data_dir: Option<&str>,
) -> Result<ExtensionDoctor, String> {
    validate_host_name(host_name)?;
    let explicit_home = home.is_some();
    let home = resolve_home(home)?;
    let user_data_dir = resolve_optional_path(user_data_dir, "user_data_dir")?;
    let manifest_path =
        extension_manifest_path(browser, host_name, &home, user_data_dir.as_deref())?;
    let extension_path = extension_install_path(&home, explicit_home)?;
    let extension_assets = packaged_extension_assets(&extension_path);
    let extension_exists = extension_path.is_dir();
    let extension_valid = extension_exists
        && extension_assets.iter().all(|asset| {
            std::fs::read(&asset.path)
                .ok()
                .is_some_and(|bytes| sha256(&bytes) == asset.sha256)
        });
    let requested_host = resolve_host_path(host_path)?;
    let manifest = std::fs::read(&manifest_path)
        .ok()
        .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok());
    let manifest_host = manifest
        .as_ref()
        .and_then(|value| value.get("path"))
        .and_then(Value::as_str)
        .map(PathBuf::from);
    let effective_host = manifest_host.unwrap_or(requested_host);
    let manifest_valid = manifest.as_ref().is_some_and(|value| {
        value.get("name").and_then(Value::as_str) == Some(host_name)
            && value.get("type").and_then(Value::as_str) == Some("stdio")
            && value
                .get("allowed_origins")
                .and_then(Value::as_array)
                .is_some_and(|origins| {
                    let packaged_origin = format!("chrome-extension://{PACKAGED_EXTENSION_ID}/");
                    origins
                        .iter()
                        .any(|origin| origin.as_str() == Some(packaged_origin.as_str()))
                })
    });
    let mut issues = Vec::new();
    if !manifest_path.is_file() {
        issues.push("native host manifest is not installed".to_string());
    } else if !manifest_valid {
        issues.push("native host manifest is invalid".to_string());
    }
    if !effective_host.is_file() {
        issues.push("native host executable is missing".to_string());
    }
    if !extension_exists {
        issues.push("packaged Chrome extension is not installed".to_string());
    } else if !extension_valid {
        issues.push("packaged Chrome extension assets do not match this apoc build".to_string());
    }
    Ok(ExtensionDoctor {
        browser: browser.to_string(),
        manifest_path: manifest_path.display().to_string(),
        user_data_dir: user_data_dir.map(|path| path.display().to_string()),
        manifest_exists: manifest_path.is_file(),
        manifest_valid,
        host_path: effective_host.display().to_string(),
        host_exists: effective_host.is_file(),
        extension_id: PACKAGED_EXTENSION_ID.to_string(),
        extension_path: extension_path.display().to_string(),
        extension_exists,
        extension_valid,
        extension_assets,
        issues,
    })
}

fn extension_install_path(home: &Path, explicit_home: bool) -> Result<PathBuf, String> {
    if explicit_home {
        Ok(home.join(".apoc/chrome-extension"))
    } else {
        Ok(state_dir()?.join("chrome-extension"))
    }
}

fn install_packaged_extension(
    extension_path: &Path,
    dry_run: bool,
) -> Result<(Vec<ExtensionAsset>, Option<String>), String> {
    let assets = packaged_extension_assets(extension_path);
    if dry_run {
        return Ok((assets, None));
    }
    let parent = extension_path
        .parent()
        .ok_or_else(|| "packaged extension path has no parent".to_string())?;
    std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
    let staging = parent.join(format!(".chrome-extension.{}.tmp", uuid::Uuid::now_v7()));
    std::fs::create_dir(&staging).map_err(|error| error.to_string())?;
    for (name, bytes) in PACKAGED_EXTENSION_ASSETS {
        if let Err(error) = std::fs::write(staging.join(name), bytes) {
            let _ = std::fs::remove_dir_all(&staging);
            return Err(error.to_string());
        }
    }
    let backup = if extension_path.exists() {
        let backup = parent.join(format!("chrome-extension.backup-{}", now_ms()));
        std::fs::rename(extension_path, &backup).map_err(|error| error.to_string())?;
        Some(backup)
    } else {
        None
    };
    if let Err(error) = std::fs::rename(&staging, extension_path) {
        if let Some(backup) = &backup {
            let _ = std::fs::rename(backup, extension_path);
        }
        let _ = std::fs::remove_dir_all(&staging);
        return Err(error.to_string());
    }
    Ok((assets, backup.map(|path| path.display().to_string())))
}

fn packaged_extension_assets(extension_path: &Path) -> Vec<ExtensionAsset> {
    PACKAGED_EXTENSION_ASSETS
        .iter()
        .map(|(name, bytes)| ExtensionAsset {
            name: (*name).to_string(),
            path: extension_path.join(name).display().to_string(),
            bytes: bytes.len() as u64,
            sha256: sha256(bytes),
        })
        .collect()
}

fn sha256(bytes: &[u8]) -> String {
    format!("sha256:{:x}", Sha256::digest(bytes))
}

pub fn extension_manifest_path(
    browser: &str,
    host_name: &str,
    home: &Path,
    user_data_dir: Option<&Path>,
) -> Result<PathBuf, String> {
    match browser {
        "chrome" | "chrome-for-testing" | "chromium" => {}
        _ => return Err("browser must be chrome, chrome-for-testing, or chromium".to_string()),
    }
    if let Some(user_data_dir) = user_data_dir {
        return Ok(user_data_dir
            .join("NativeMessagingHosts")
            .join(format!("{host_name}.json")));
    }
    let directory = if cfg!(target_os = "macos") {
        match browser {
            "chrome" => "Library/Application Support/Google/Chrome/NativeMessagingHosts",
            "chrome-for-testing" => {
                "Library/Application Support/Google/ChromeForTesting/NativeMessagingHosts"
            }
            "chromium" => "Library/Application Support/Chromium/NativeMessagingHosts",
            _ => return Err("browser must be chrome, chrome-for-testing, or chromium".to_string()),
        }
    } else if cfg!(target_os = "linux") {
        match browser {
            "chrome" => ".config/google-chrome/NativeMessagingHosts",
            "chrome-for-testing" => ".config/google-chrome-for-testing/NativeMessagingHosts",
            "chromium" => ".config/chromium/NativeMessagingHosts",
            _ => return Err("browser must be chrome, chrome-for-testing, or chromium".to_string()),
        }
    } else {
        return Err("Chrome native-host installation supports macOS and Linux".to_string());
    };
    Ok(home.join(directory).join(format!("{host_name}.json")))
}

fn resolve_optional_path(path: Option<&str>, name: &str) -> Result<Option<PathBuf>, String> {
    match path {
        Some(path) if !path.trim().is_empty() => Ok(Some(PathBuf::from(path))),
        Some(_) => Err(format!("{name} must not be empty")),
        None => Ok(None),
    }
}

fn resolve_home(home: Option<&str>) -> Result<PathBuf, String> {
    match home {
        Some(home) if !home.trim().is_empty() => Ok(PathBuf::from(home)),
        Some(_) => Err("home must not be empty".to_string()),
        None => dirs::home_dir().ok_or_else(|| "could not resolve the user home".to_string()),
    }
}

fn resolve_host_path(host_path: Option<&str>) -> Result<PathBuf, String> {
    let path = match host_path {
        Some(path) if !path.trim().is_empty() => PathBuf::from(path),
        Some(_) => return Err("host_path must not be empty".to_string()),
        None => std::env::current_exe()
            .map_err(|error| error.to_string())?
            .with_file_name("apoc-chrome-native-host"),
    };
    if !path.is_absolute() {
        return Err("host_path must be absolute".to_string());
    }
    Ok(path)
}

fn validate_host_name(host_name: &str) -> Result<(), String> {
    if host_name.is_empty()
        || host_name.starts_with('.')
        || host_name.ends_with('.')
        || host_name.contains("..")
        || !host_name
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
    {
        return Err("invalid Chrome native host name".to_string());
    }
    Ok(())
}

fn validate_extension_id(extension_id: &str) -> Result<(), String> {
    if extension_id.is_empty()
        || !extension_id
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
    {
        return Err("invalid Chrome extension id".to_string());
    }
    Ok(())
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct BridgeConnect {
    cmd: String,
    host_name: String,
    #[serde(default)]
    extension_origin: Option<String>,
}

#[derive(Default)]
struct ExtensionBridgeState {
    generation: u64,
    writer: Option<FramedWrite<OwnedWriteHalf, LinesCodec>>,
    host_name: Option<String>,
    extension_origin: Option<String>,
    extension_id: Option<String>,
    version: Option<String>,
    connected_at: Option<u64>,
    last_seen_at: Option<u64>,
    events: VecDeque<ExtensionEvent>,
    pending: HashMap<String, oneshot::Sender<Result<Value, String>>>,
}

#[derive(Clone, Default)]
pub struct ExtensionBridge {
    state: Arc<Mutex<ExtensionBridgeState>>,
}

impl ExtensionBridge {
    pub async fn serve_connection(&self, stream: UnixStream) -> Result<(), String> {
        let (reader, writer) = stream.into_split();
        let mut lines = BufReader::new(reader).lines();
        let handshake = lines
            .next_line()
            .await
            .map_err(|error| error.to_string())?
            .ok_or_else(|| "extension bridge closed before handshake".to_string())?;
        let handshake = serde_json::from_str::<BridgeConnect>(&handshake)
            .map_err(|error| format!("invalid extension bridge handshake: {error}"))?;
        if handshake.cmd != "ext.bridge.connect" || handshake.host_name.trim().is_empty() {
            return Err("invalid extension bridge handshake".to_string());
        }

        let generation = {
            let mut state = self.state.lock().await;
            state.generation = state.generation.wrapping_add(1);
            let generation = state.generation;
            let replaced = state
                .pending
                .drain()
                .map(|(_, pending)| pending)
                .collect::<Vec<_>>();
            for pending in replaced {
                let _ = pending.send(Err("extension bridge connection was replaced".to_string()));
            }
            state.writer = Some(FramedWrite::new(writer, LinesCodec::new()));
            state.host_name = Some(handshake.host_name);
            state.extension_origin = handshake.extension_origin;
            state.extension_id = None;
            state.version = None;
            state.connected_at = Some(now_ms());
            state.last_seen_at = Some(now_ms());
            generation
        };
        self.send_envelope(json!({"v":1,"type":"ack","id":"bridge"}))
            .await?;

        while let Some(line) = lines.next_line().await.map_err(|error| error.to_string())? {
            let envelope = serde_json::from_str::<Value>(&line)
                .map_err(|error| format!("invalid extension bridge envelope: {error}"))?;
            if envelope.get("v").and_then(Value::as_u64) != Some(EXTENSION_PROTOCOL_VERSION) {
                continue;
            }
            let mut state = self.state.lock().await;
            if state.generation != generation {
                break;
            }
            state.last_seen_at = Some(now_ms());
            match envelope.get("type").and_then(Value::as_str) {
                Some("hello") => {
                    state.extension_id = envelope
                        .get("extensionId")
                        .and_then(Value::as_str)
                        .map(str::to_string);
                    state.version = envelope
                        .get("version")
                        .and_then(Value::as_str)
                        .map(str::to_string);
                }
                Some("response") => {
                    let Some(id) = envelope.get("id").and_then(Value::as_str) else {
                        continue;
                    };
                    let Some(pending) = state.pending.remove(id) else {
                        continue;
                    };
                    let response = if envelope.get("ok").and_then(Value::as_bool) == Some(true) {
                        Ok(envelope.get("result").cloned().unwrap_or_else(|| json!({})))
                    } else {
                        Err(envelope
                            .get("error")
                            .and_then(Value::as_str)
                            .unwrap_or("extension request failed")
                            .to_string())
                    };
                    let _ = pending.send(response);
                }
                Some("event") => {
                    if let Some(event) = envelope.get("event")
                        && let Ok(event) = serde_json::from_value::<ExtensionEvent>(event.clone())
                    {
                        state.events.push_back(event);
                        while state.events.len() > MAX_EXTENSION_EVENTS {
                            state.events.pop_front();
                        }
                    }
                }
                _ => {}
            }
        }

        let mut state = self.state.lock().await;
        if state.generation == generation {
            state.writer = None;
            let pending = state
                .pending
                .drain()
                .map(|(_, pending)| pending)
                .collect::<Vec<_>>();
            for pending in pending {
                let _ = pending.send(Err("extension bridge disconnected".to_string()));
            }
        }
        Ok(())
    }

    pub async fn request(&self, request: Value, timeout: Duration) -> Result<Value, String> {
        let id = uuid::Uuid::now_v7().to_string();
        let (sender, receiver) = oneshot::channel();
        {
            let mut state = self.state.lock().await;
            if state.writer.is_none() {
                return Err("Chrome extension bridge is not connected".to_string());
            }
            state.pending.insert(id.clone(), sender);
        }
        if let Err(error) = self
            .send_envelope(json!({
                "v": EXTENSION_PROTOCOL_VERSION,
                "id": id,
                "type": "request",
                "request": request
            }))
            .await
        {
            self.state.lock().await.pending.remove(&id);
            return Err(error);
        }
        match tokio::time::timeout(timeout, receiver).await {
            Ok(Ok(result)) => result,
            Ok(Err(_)) => Err("extension bridge disconnected".to_string()),
            Err(_) => {
                self.state.lock().await.pending.remove(&id);
                Err("extension request timed out".to_string())
            }
        }
    }

    pub async fn status(&self, socket: String) -> ExtensionBridgeConnection {
        let state = self.state.lock().await;
        ExtensionBridgeConnection {
            connected: state.writer.is_some(),
            socket,
            host_name: state.host_name.clone(),
            extension_origin: state.extension_origin.clone(),
            extension_id: state.extension_id.clone(),
            version: state.version.clone(),
            connected_at: state.connected_at,
            last_seen_at: state.last_seen_at,
            retained_events: state.events.len(),
        }
    }

    pub async fn events(&self, after: u64, limit: usize) -> Vec<ExtensionEvent> {
        self.state
            .lock()
            .await
            .events
            .iter()
            .filter(|event| event.ts > after)
            .take(limit.min(MAX_EXTENSION_EVENTS))
            .cloned()
            .collect()
    }

    async fn send_envelope(&self, envelope: Value) -> Result<(), String> {
        let line = serde_json::to_string(&envelope).map_err(|error| error.to_string())?;
        let mut state = self.state.lock().await;
        let writer = state
            .writer
            .as_mut()
            .ok_or_else(|| "Chrome extension bridge is not connected".to_string())?;
        writer.send(line).await.map_err(|error| error.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};

    #[tokio::test]
    async fn bridge_correlates_requests_and_retains_connection_state_and_events() {
        let bridge = ExtensionBridge::default();
        let (daemon, extension) = UnixStream::pair().unwrap();
        let serving = {
            let bridge = bridge.clone();
            tokio::spawn(async move { bridge.serve_connection(daemon).await })
        };
        let (reader, mut writer) = extension.into_split();
        let mut reader = BufReader::new(reader).lines();
        writer
            .write_all(b"{\"cmd\":\"ext.bridge.connect\",\"hostName\":\"com.douglance.apoc\",\"extensionOrigin\":\"chrome-extension://one/\"}\n")
            .await
            .unwrap();
        assert_eq!(
            serde_json::from_str::<Value>(&reader.next_line().await.unwrap().unwrap()).unwrap(),
            json!({"v":1,"type":"ack","id":"bridge"})
        );
        writer
            .write_all(
                b"{\"v\":1,\"type\":\"hello\",\"extensionId\":\"one\",\"version\":\"0.5.0\"}\n",
            )
            .await
            .unwrap();
        writer
            .write_all(b"{\"v\":1,\"type\":\"event\",\"event\":{\"ts\":7,\"kind\":\"route\",\"message\":\"ready\"}}\n")
            .await
            .unwrap();

        let request = {
            let bridge = bridge.clone();
            tokio::spawn(async move {
                bridge
                    .request(json!({"op":"tabs"}), Duration::from_secs(1))
                    .await
            })
        };
        let envelope =
            serde_json::from_str::<Value>(&reader.next_line().await.unwrap().unwrap()).unwrap();
        assert_eq!(envelope["request"], json!({"op":"tabs"}));
        writer
            .write_all(
                format!(
                    "{{\"v\":1,\"id\":{},\"type\":\"response\",\"ok\":true,\"result\":{{\"tabs\":[{{\"id\":3}}]}}}}\n",
                    serde_json::to_string(envelope["id"].as_str().unwrap()).unwrap()
                )
                .as_bytes(),
            )
            .await
            .unwrap();
        assert_eq!(request.await.unwrap().unwrap(), json!({"tabs":[{"id":3}]}));

        tokio::task::yield_now().await;
        let status = bridge.status("/tmp/apoc-extension.sock".to_string()).await;
        assert!(status.connected);
        assert_eq!(status.extension_id.as_deref(), Some("one"));
        assert_eq!(bridge.events(0, 10).await.len(), 1);
        drop(writer);
        serving.await.unwrap().unwrap();
        assert!(!bridge.status("socket".to_string()).await.connected);
    }

    #[test]
    fn native_host_installation_writes_a_valid_distribution_manifest() {
        let home = tempfile::tempdir().unwrap();
        let host = home.path().join("apoc-chrome-native-host");
        std::fs::write(&host, b"fixture").unwrap();
        let installed = install_extension_host(
            "chrome-for-testing",
            "fixture_extension",
            DEFAULT_EXTENSION_HOST_NAME,
            Some(host.to_str().unwrap()),
            Some(home.path().to_str().unwrap()),
            None,
            false,
        )
        .unwrap();
        assert!(installed.installed);
        assert_eq!(installed.manifest["path"], host.display().to_string());
        assert_eq!(
            installed.manifest["allowed_origins"][0],
            format!("chrome-extension://{PACKAGED_EXTENSION_ID}/")
        );
        assert_eq!(
            installed.manifest["allowed_origins"][1],
            "chrome-extension://fixture_extension/"
        );
        assert_eq!(installed.extension_id, PACKAGED_EXTENSION_ID);
        assert_eq!(installed.extension_assets.len(), 4);
        assert!(
            installed
                .extension_assets
                .iter()
                .all(|asset| Path::new(&asset.path).is_file())
        );
        let doctor = extension_doctor(
            "chrome-for-testing",
            DEFAULT_EXTENSION_HOST_NAME,
            Some(host.to_str().unwrap()),
            Some(home.path().to_str().unwrap()),
            None,
        )
        .unwrap();
        assert!(doctor.manifest_exists);
        assert!(doctor.manifest_valid);
        assert!(doctor.host_exists);
        assert!(doctor.extension_exists);
        assert!(doctor.extension_valid);
        assert_eq!(doctor.extension_id, PACKAGED_EXTENSION_ID);
        assert!(doctor.issues.is_empty());

        let replaced = install_extension_host(
            "chrome-for-testing",
            "fixture_extension",
            DEFAULT_EXTENSION_HOST_NAME,
            Some(host.to_str().unwrap()),
            Some(home.path().to_str().unwrap()),
            None,
            false,
        )
        .unwrap();
        assert!(
            replaced
                .manifest_backup
                .as_deref()
                .is_some_and(|path| Path::new(path).is_file())
        );

        let user_data_dir = home.path().join("isolated-profile");
        let installed = install_extension_host(
            "chrome-for-testing",
            PACKAGED_EXTENSION_ID,
            DEFAULT_EXTENSION_HOST_NAME,
            Some(host.to_str().unwrap()),
            Some(home.path().to_str().unwrap()),
            Some(user_data_dir.to_str().unwrap()),
            false,
        )
        .unwrap();
        assert_eq!(
            Path::new(&installed.manifest_path),
            user_data_dir
                .join("NativeMessagingHosts")
                .join(format!("{DEFAULT_EXTENSION_HOST_NAME}.json"))
        );
        assert_eq!(installed.user_data_dir.as_deref(), user_data_dir.to_str());
    }
}