blyte 0.94.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
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
use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::AtomicBool;
use std::sync::{mpsc, Arc, Mutex};
use std::time::{Duration, Instant};

use blyte_cli::http::Request;
use blyte_cli::serve::{generate_token, route, OpenCodes, Surface, TOKEN_HEADER};
use blyte_cli::session::{EntryBody, PromptRunner, Session};
use blyte_cli::surface_dir::{list_records_in, surfaces_dir};
use blyte_cli::surface_registry::read_entries;
use blyte_cli::surface_version::SurfaceRuntimeInfo;

struct NoopRunner;

impl PromptRunner for NoopRunner {
    fn run(
        &mut self,
        _prompt: &str,
        _model: &str,
        _emit: &(dyn Fn(EntryBody) + Sync),
    ) -> Result<(), String> {
        Ok(())
    }
}

struct BlockingRunner {
    started: mpsc::Sender<()>,
    release: Arc<Mutex<Option<mpsc::Receiver<()>>>>,
}

impl PromptRunner for BlockingRunner {
    fn run(
        &mut self,
        _prompt: &str,
        _model: &str,
        _emit: &(dyn Fn(EntryBody) + Sync),
    ) -> Result<(), String> {
        let _ = self.started.send(());
        if let Some(rx) = self.release.lock().unwrap().take() {
            let _ = rx.recv_timeout(Duration::from_secs(10));
        }
        Ok(())
    }
}

fn make_executable_file(path: &Path, bytes: &[u8]) {
    std::fs::write(path, bytes).unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
}

fn make_surface_with_runner(
    root: PathBuf,
    runtime: SurfaceRuntimeInfo,
    runner: Box<dyn PromptRunner>,
) -> Surface {
    let session = Session::start(runner, "m1".to_string());
    let mcp = Arc::new(blyte_cli::mcp::McpManager::empty_in(&root));
    Surface {
        surface_id: "s00000000000000c1".to_string(),
        surface_name: "reload-test".to_string(),
        root,
        repo: "reload-test".to_string(),
        session,
        session_id: "sess-reload-test".to_string(),
        started_at: 1_700_000_000,
        runtime,
        days: 14,
        token: generate_token().unwrap(),
        message_credential: generate_token().unwrap(),
        open_codes: OpenCodes::new(),
        requests: Arc::new(blyte_cli::requests::RequestsState::new()),
        publisher: Arc::new(blyte_cli::requests::RealPublisher),
        mcp,
        reconcile_lock: Mutex::new(()),
        reconcile_requested: AtomicBool::new(false),
    }
}

fn make_request(method: &str, path: &str, token: Option<&str>) -> Request {
    let headers = match token {
        Some(t) => vec![(TOKEN_HEADER.to_string(), t.to_string())],
        None => Vec::new(),
    };
    Request {
        method: method.to_string(),
        path: path.to_string(),
        query: Vec::new(),
        headers,
        body: Vec::new(),
    }
}

#[test]
fn reload_endpoint_rejects_unauthenticated_and_non_post() {
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    let fake_bin = tmp.path().join("blyte-bin");
    make_executable_file(&fake_bin, b"#!/bin/sh\n");

    let runtime = SurfaceRuntimeInfo::from_binary("0.83.0", &fake_bin, "boot-auth-1").unwrap();
    let surface = make_surface_with_runner(repo, runtime, Box::new(NoopRunner));

    let unauth = route(&surface, &make_request("POST", "/api/reload", None), 100);
    assert_eq!(unauth.status, 403);

    let wrong = route(
        &surface,
        &make_request("POST", "/api/reload", Some("wrong-token")),
        100,
    );
    assert_eq!(wrong.status, 403);

    let wrong_method = route(
        &surface,
        &make_request("GET", "/api/reload", Some(&surface.token)),
        100,
    );
    assert_eq!(wrong_method.status, 405);
}

#[test]
fn reload_endpoint_refuses_active_turn_with_409_conflict() {
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    let fake_bin = tmp.path().join("blyte-bin");
    make_executable_file(&fake_bin, b"#!/bin/sh\n");

    let (started_tx, started_rx) = mpsc::channel();
    let (release_tx, release_rx) = mpsc::channel();
    let runner = BlockingRunner {
        started: started_tx,
        release: Arc::new(Mutex::new(Some(release_rx))),
    };

    let runtime = SurfaceRuntimeInfo::from_binary("0.83.0", &fake_bin, "boot-turn-1").unwrap();
    let surface = make_surface_with_runner(repo, runtime, Box::new(runner));

    let _ = surface.session.submit("do work", Vec::new()).unwrap();
    started_rx
        .recv_timeout(Duration::from_secs(5))
        .expect("blocking turn did not start");

    let conflict = route(
        &surface,
        &make_request("POST", "/api/reload", Some(&surface.token)),
        100,
    );
    assert_eq!(conflict.status, 409);
    let body: serde_json::Value = serde_json::from_slice(&conflict.body).unwrap();
    let err_msg = body["error"].as_str().unwrap().to_lowercase();
    assert!(
        err_msg.contains("turn") && err_msg.contains("progress"),
        "expected active turn conflict error, got: {body:?}"
    );

    let _ = release_tx.send(());
    let deadline = Instant::now() + Duration::from_secs(5);
    while Instant::now() < deadline {
        if !surface.session.info().busy {
            break;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    assert!(!surface.session.info().busy);

    let ok = route(
        &surface,
        &make_request("POST", "/api/reload", Some(&surface.token)),
        101,
    );
    assert_eq!(ok.status, 200);
    let ok_body: serde_json::Value = serde_json::from_slice(&ok.body).unwrap();
    assert_eq!(ok_body["reloading"], true);
}

#[test]
fn reload_endpoint_verifies_target_executable_before_accepting_reload() {
    let tmp = tempfile::tempdir().unwrap();
    let repo = tmp.path().join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    let fake_bin = tmp.path().join("blyte-bin");
    std::fs::write(&fake_bin, b"not-executable").unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&fake_bin, std::fs::Permissions::from_mode(0o644)).unwrap();
    }

    let runtime = SurfaceRuntimeInfo::from_binary("0.83.0", &fake_bin, "boot-exec-1").unwrap();
    let surface = make_surface_with_runner(repo, runtime, Box::new(NoopRunner));

    #[cfg(unix)]
    {
        let non_exec = route(
            &surface,
            &make_request("POST", "/api/reload", Some(&surface.token)),
            100,
        );
        assert_eq!(non_exec.status, 500);
        let body: serde_json::Value = serde_json::from_slice(&non_exec.body).unwrap();
        assert!(
            body["error"].as_str().unwrap().contains("not executable"),
            "expected not executable error, got: {body:?}"
        );
    }

    std::fs::remove_file(&fake_bin).unwrap();
    let missing = route(
        &surface,
        &make_request("POST", "/api/reload", Some(&surface.token)),
        101,
    );
    assert_eq!(missing.status, 500);
    let missing_body: serde_json::Value = serde_json::from_slice(&missing.body).unwrap();
    assert!(
        missing_body["error"]
            .as_str()
            .unwrap()
            .contains(&fake_bin.display().to_string()),
        "expected missing path in error, got: {missing_body:?}"
    );
}

#[cfg(unix)]
mod unix_e2e {
    use super::*;

    struct ChildGuard(Option<std::process::Child>);

    impl Drop for ChildGuard {
        fn drop(&mut self) {
            if let Some(mut child) = self.0.take() {
                let pid = child.id().to_string();
                let _ = Command::new("kill").args(["-TERM", &pid]).status();
                let deadline = Instant::now() + Duration::from_secs(3);
                while Instant::now() < deadline {
                    if let Ok(Some(_)) = child.try_wait() {
                        return;
                    }
                    std::thread::sleep(Duration::from_millis(25));
                }
                let _ = child.kill();
                let _ = child.wait();
            }
        }
    }

    struct RunningSurface {
        guard: ChildGuard,
        port: u16,
        token: String,
        _rx: mpsc::Receiver<String>,
        _stdout_handle: std::thread::JoinHandle<()>,
        _stderr_handle: std::thread::JoinHandle<String>,
    }

    fn init_repo_with_commit(repo: &Path) {
        std::fs::create_dir_all(repo).unwrap();
        let run = |args: &[&str]| {
            let out = Command::new("git")
                .args(args)
                .current_dir(repo)
                .output()
                .unwrap();
            assert!(
                out.status.success(),
                "git {:?} failed: {}",
                args,
                String::from_utf8_lossy(&out.stderr)
            );
        };
        run(&["init", "-b", "main"]);
        run(&["config", "user.name", "Test"]);
        run(&["config", "user.email", "test@example.com"]);
        std::fs::write(repo.join("README.md"), "hello\n").unwrap();
        run(&["add", "README.md"]);
        run(&["commit", "-m", "initial"]);
    }

    fn spawn_surface(repo: &Path, home: &Path, state_dir: &Path) -> RunningSurface {
        let bin_path = PathBuf::from(env!("CARGO_BIN_EXE_blyte"));
        let mut child = Command::new(&bin_path)
            .args(["--foreground", "--no-open", "--port", "0"])
            .current_dir(repo)
            .env("HOME", home)
            .env("XDG_CONFIG_HOME", home.join(".config"))
            .env("BLYTE_STATE_DIR", state_dir)
            .env("BLYTE_ENV_FILE", "")
            .env("BLYTE_NO_UPDATE_CHECK", "1")
            .env("BLYTE_USAGE_LOG", "off")
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();

        let stdout = child.stdout.take().unwrap();
        let mut stderr = child.stderr.take().unwrap();
        let mut guard = ChildGuard(Some(child));

        let stderr_handle = std::thread::spawn(move || {
            let mut buf = String::new();
            let _ = stderr.read_to_string(&mut buf);
            buf
        });
        let (tx, rx) = mpsc::channel::<String>();
        let stdout_handle = std::thread::spawn(move || {
            for line in BufReader::new(stdout).lines().map_while(Result::ok) {
                if tx.send(line).is_err() {
                    break;
                }
            }
        });

        let deadline = Instant::now() + Duration::from_secs(15);
        let mut url: Option<String> = None;
        let mut seen = Vec::new();
        while Instant::now() < deadline {
            let remaining = deadline.saturating_duration_since(Instant::now());
            match rx.recv_timeout(remaining.min(Duration::from_millis(100))) {
                Ok(line) => {
                    if let Some((_, rest)) = line.split_once(" at http://127.0.0.1:") {
                        url = Some(format!("http://127.0.0.1:{rest}"));
                        break;
                    }
                    seen.push(line);
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {}
                Err(mpsc::RecvTimeoutError::Disconnected) => break,
            }
        }

        let url = match url {
            Some(u) => u,
            None => {
                if let Some(mut c) = guard.0.take() {
                    let _ = c.kill();
                    let _ = c.wait();
                }
                let err_text = stderr_handle.join().unwrap_or_default();
                drop(rx);
                let _ = stdout_handle.join();
                panic!(
                    "surface did not print url\nstdout:\n{}\nstderr:\n{err_text}",
                    seen.join("\n")
                );
            }
        };

        let (base, token) = url.split_once("/#token=").unwrap();
        let port: u16 = base
            .strip_prefix("http://127.0.0.1:")
            .unwrap()
            .parse()
            .unwrap();

        RunningSurface {
            guard,
            port,
            token: token.to_string(),
            _rx: rx,
            _stdout_handle: stdout_handle,
            _stderr_handle: stderr_handle,
        }
    }

    fn http_json(
        method: &str,
        port: u16,
        path: &str,
        token: &str,
    ) -> Result<(u16, serde_json::Value), String> {
        let mut stream =
            TcpStream::connect(("127.0.0.1", port)).map_err(|e| format!("connect: {e}"))?;
        let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
        let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
        let body = if method == "POST" { "{}" } else { "" };
        let req = format!(
            "{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
            body.len()
        );
        stream
            .write_all(req.as_bytes())
            .map_err(|e| format!("write: {e}"))?;
        let mut raw = String::new();
        stream
            .read_to_string(&mut raw)
            .map_err(|e| format!("read: {e}"))?;
        let (head, resp_body) = raw
            .split_once("\r\n\r\n")
            .ok_or_else(|| format!("malformed response: {raw}"))?;
        let status = head
            .lines()
            .next()
            .and_then(|l| l.split_whitespace().nth(1))
            .and_then(|s| s.parse::<u16>().ok())
            .ok_or_else(|| format!("bad status line: {head}"))?;
        let json =
            serde_json::from_str(resp_body).map_err(|e| format!("bad json ({e}): {resp_body}"))?;
        Ok((status, json))
    }

    fn wait_for_new_boot_id(
        port: u16,
        token: &str,
        old_boot_id: &str,
        timeout: Duration,
    ) -> serde_json::Value {
        let deadline = Instant::now() + timeout;
        let mut last = String::new();
        while Instant::now() < deadline {
            match http_json("GET", port, "/api/session", token) {
                Ok((200, val)) => {
                    if let Some(bid) = val["boot_id"].as_str() {
                        if !bid.is_empty() && bid != old_boot_id {
                            return val;
                        }
                    }
                    last = format!("same boot_id: {val}");
                }
                Ok((status, val)) => last = format!("HTTP {status}: {val}"),
                Err(e) => last = e,
            }
            std::thread::sleep(Duration::from_millis(100));
        }
        panic!("surface on port {port} did not return with a new boot_id (last: {last})");
    }

    #[test]
    fn end_to_end_post_api_reload_reexecs_same_port_token_surface_and_new_boot_id() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("reload-e2e");
        let home = tmp.path().join("home");
        let state_dir = tmp.path().join("state");
        std::fs::create_dir_all(&home).unwrap();
        init_repo_with_commit(&repo);

        let running = spawn_surface(&repo, &home, &state_dir);
        let (status1, sess1) = http_json("GET", running.port, "/api/session", &running.token)
            .expect("initial GET /api/session failed");
        assert_eq!(status1, 200);
        let boot1 = sess1["boot_id"].as_str().unwrap().to_string();
        let surface_name1 = sess1["surface_name"].as_str().unwrap().to_string();
        let recs1 = list_records_in(&surfaces_dir(&repo)).unwrap().records;
        assert_eq!(recs1.len(), 1);
        let surface_id1 = recs1[0].record.id.clone();
        let pid1 = recs1[0].record.pid;

        let (reload_status, reload_body) =
            http_json("POST", running.port, "/api/reload", &running.token)
                .expect("POST /api/reload failed");
        assert_eq!(reload_status, 200);
        assert_eq!(reload_body["reloading"], true);

        let sess2 = wait_for_new_boot_id(
            running.port,
            &running.token,
            &boot1,
            Duration::from_secs(15),
        );
        let boot2 = sess2["boot_id"].as_str().unwrap().to_string();
        assert_ne!(boot2, boot1);
        assert_eq!(sess2["surface_name"].as_str().unwrap(), surface_name1);

        let (health_status, health) =
            http_json("GET", running.port, "/api/health", &running.token).unwrap();
        assert_eq!(health_status, 200);
        assert_eq!(health["surface_id"].as_str().unwrap(), surface_id1);

        let recs2 = list_records_in(&surfaces_dir(&repo)).unwrap().records;
        assert_eq!(recs2.len(), 1);
        assert_eq!(recs2[0].record.id, surface_id1);
        assert_eq!(recs2[0].record.pid, pid1);

        let reg = read_entries(&state_dir.join("surfaces")).unwrap();
        assert!(reg.unreadable.is_empty(), "{:?}", reg.unreadable);
        assert_eq!(reg.entries.len(), 1);
        assert_eq!(reg.entries[0].id, surface_id1);
        assert_eq!(reg.entries[0].port, running.port);
        assert_eq!(reg.entries[0].runtime.boot_id, boot2);

        drop(running.guard);
    }

    #[test]
    fn blyte_reload_cli_named_all_and_unknown_error() {
        let tmp = tempfile::tempdir().unwrap();
        let repo_one = tmp.path().join("repo-one");
        let repo_two = tmp.path().join("repo-two");
        let home = tmp.path().join("home");
        let state_dir = tmp.path().join("state");
        std::fs::create_dir_all(&home).unwrap();
        init_repo_with_commit(&repo_one);
        init_repo_with_commit(&repo_two);

        let surf_one = spawn_surface(&repo_one, &home, &state_dir);
        let surf_two = spawn_surface(&repo_two, &home, &state_dir);

        let (_, s1_initial) =
            http_json("GET", surf_one.port, "/api/session", &surf_one.token).unwrap();
        let (_, s2_initial) =
            http_json("GET", surf_two.port, "/api/session", &surf_two.token).unwrap();
        let boot1_a = s1_initial["boot_id"].as_str().unwrap().to_string();
        let boot2_a = s2_initial["boot_id"].as_str().unwrap().to_string();

        let bin_path = PathBuf::from(env!("CARGO_BIN_EXE_blyte"));
        let run_cli = |args: &[&str], cwd: &Path| {
            Command::new(&bin_path)
                .args(args)
                .current_dir(cwd)
                .env("HOME", &home)
                .env("XDG_CONFIG_HOME", home.join(".config"))
                .env("BLYTE_STATE_DIR", &state_dir)
                .env("BLYTE_ENV_FILE", "")
                .env("BLYTE_NO_UPDATE_CHECK", "1")
                .env("BLYTE_USAGE_LOG", "off")
                .output()
                .unwrap()
        };

        let unknown = run_cli(&["reload", "does-not-exist"], &repo_one);
        assert!(!unknown.status.success());
        let unknown_err = String::from_utf8_lossy(&unknown.stderr);
        assert!(
            unknown_err.contains("does-not-exist"),
            "expected unknown surface name in stderr, got: {unknown_err}"
        );

        let named = run_cli(&["reload", "repo-one"], &repo_two);
        assert!(
            named.status.success(),
            "blyte reload repo-one failed: stdout={} stderr={}",
            String::from_utf8_lossy(&named.stdout),
            String::from_utf8_lossy(&named.stderr)
        );
        let named_out = String::from_utf8_lossy(&named.stdout);
        assert!(named_out.contains("repo-one"), "{named_out}");

        let s1_after_named = wait_for_new_boot_id(
            surf_one.port,
            &surf_one.token,
            &boot1_a,
            Duration::from_secs(15),
        );
        let boot1_b = s1_after_named["boot_id"].as_str().unwrap().to_string();
        assert_ne!(boot1_b, boot1_a);

        let (_, s2_still_same) =
            http_json("GET", surf_two.port, "/api/session", &surf_two.token).unwrap();
        assert_eq!(s2_still_same["boot_id"].as_str().unwrap(), boot2_a);

        let cwd_default = run_cli(&["reload"], &repo_two);
        assert!(
            cwd_default.status.success(),
            "blyte reload (default cwd) failed: stdout={} stderr={}",
            String::from_utf8_lossy(&cwd_default.stdout),
            String::from_utf8_lossy(&cwd_default.stderr)
        );
        let s2_after_cwd = wait_for_new_boot_id(
            surf_two.port,
            &surf_two.token,
            &boot2_a,
            Duration::from_secs(15),
        );
        let boot2_b = s2_after_cwd["boot_id"].as_str().unwrap().to_string();
        assert_ne!(boot2_b, boot2_a);

        let all = run_cli(&["reload", "--all"], &repo_one);
        assert!(
            all.status.success(),
            "blyte reload --all failed: stdout={} stderr={}",
            String::from_utf8_lossy(&all.stdout),
            String::from_utf8_lossy(&all.stderr)
        );
        let all_out = String::from_utf8_lossy(&all.stdout);
        assert!(all_out.contains("repo-one"), "{all_out}");
        assert!(all_out.contains("repo-two"), "{all_out}");

        let s1_after_all = wait_for_new_boot_id(
            surf_one.port,
            &surf_one.token,
            &boot1_b,
            Duration::from_secs(15),
        );
        let s2_after_all = wait_for_new_boot_id(
            surf_two.port,
            &surf_two.token,
            &boot2_b,
            Duration::from_secs(15),
        );
        assert_ne!(s1_after_all["boot_id"].as_str().unwrap(), boot1_b);
        assert_ne!(s2_after_all["boot_id"].as_str().unwrap(), boot2_b);

        drop(surf_one.guard);
        drop(surf_two.guard);
    }
}