agentty 0.15.2

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
//! Generator for the marketing demo GIF served at
//! `docs/site/static/demo/demo.gif`.
//!
//! Marked `#[ignore]` so the regular E2E suite stays fast; run explicitly with
//! `cargo test -p agentty --test e2e demo -- --ignored` to regenerate the GIF.
//! The test is self-contained: it seeds fake projects, installs a scripted
//! `claude` stub that emits a canned reply over the stream-json protocol, and
//! drives VHS with a hand-crafted tape.

use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};

use agentty::db::{DB_DIR, DB_FILE, Database};
use assert_cmd::cargo::cargo_bin;
use sqlx::sqlite::SqliteConnectOptions;
use sqlx::{ConnectOptions, Connection, Executor};

use crate::common::{
    BuilderEnv, PINNED_CLOCK_ENV_VAR, PINNED_CLOCK_UNIX_SECONDS, PINNED_CLOCK_UTC_OFFSET_ENV_VAR,
    PINNED_CLOCK_UTC_OFFSET_SECONDS,
};

type DemoResult = Result<(), Box<dyn std::error::Error>>;
type SeedSessionRow<'a> = (
    &'a str,
    &'a str,
    &'a str,
    &'a str,
    &'a str,
    i64,
    i64,
    &'a str,
    i64,
);

const GIF_NAME: &str = "demo";

/// Regenerates the marketing demo GIF under `docs/site/static/demo/`.
///
/// Gated behind `#[ignore]` because it requires VHS, the real `agentty`
/// binary, and ~2 minutes of wall clock time.
#[test]
#[ignore = "requires VHS and regenerates a marketing asset"]
fn generate_marketing_demo_gif() -> DemoResult {
    // Arrange
    if Command::new("vhs").arg("--version").output().is_err() {
        return Ok(());
    }

    // Use a short, clean /tmp path so project rows and the footer path read
    // nicely in the final GIF (macOS tempdirs live under /var/folders/...).
    let demo_root = make_fresh_demo_root()?;
    let env = make_demo_env(&demo_root)?;

    install_scripted_claude_stub(&env)?;
    install_scripted_codex_stub(&env)?;
    install_agent_availability_stubs(&env)?;
    symlink_agentty_into_stub_bin(&env)?;

    let fake_project_paths = create_fake_project_dirs(&env)?;
    // Agentty reads `current_dir()` which is canonicalized; seed using the
    // same canonical form the app will upsert itself.
    let canonical_cwd = env.workdir.canonicalize()?;
    seed_database(&env, &fake_project_paths, &canonical_cwd)?;

    let output_dir = repo_demo_dir();
    std::fs::create_dir_all(&output_dir)?;
    let gif_path = output_dir.join(format!("{GIF_NAME}.gif"));

    let tape = build_demo_tape(&env, &gif_path);
    let tape_path = demo_root.join("demo.tape");
    std::fs::write(&tape_path, &tape)?;

    // Act
    let output = Command::new("vhs").arg(&tape_path).output()?;

    // Assert
    if !output.status.success() {
        return Err(format!(
            "vhs failed: {}\nstdout: {}",
            String::from_utf8_lossy(&output.stderr),
            String::from_utf8_lossy(&output.stdout),
        )
        .into());
    }
    if !gif_path.exists() {
        return Err(format!("demo gif not produced at {}", gif_path.display()).into());
    }

    // Best-effort cleanup of the scratch directory.
    let _ = std::fs::remove_dir_all(&demo_root);

    Ok(())
}

/// Returns a fresh `/tmp/agentty-demo-<nanos>/` directory so paths shown in
/// the GIF are short and do not leak the operator's personal temp path.
fn make_fresh_demo_root() -> std::io::Result<PathBuf> {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |duration| duration.as_nanos());
    let root = PathBuf::from(format!("/tmp/agentty-demo-{nanos}"));
    if root.exists() {
        std::fs::remove_dir_all(&root)?;
    }
    std::fs::create_dir_all(&root)?;

    Ok(root)
}

/// Builds a `BuilderEnv` whose workdir is named `opencloudtool` so the project
/// row and path shown in the demo read cleanly while discovery uses a
/// deterministic isolated home directory.
fn make_demo_env(demo_root: &Path) -> std::io::Result<BuilderEnv> {
    let agentty_root = demo_root.join("agentty_root");
    let home_dir = demo_root.join("home");
    let workdir = demo_root.join("opencloudtool");
    let stub_bin = demo_root.join("stub-bin");

    std::fs::create_dir_all(&agentty_root)?;
    std::fs::create_dir_all(&home_dir)?;
    std::fs::create_dir_all(&workdir)?;
    std::fs::create_dir_all(&stub_bin)?;

    let env = BuilderEnv {
        agentty_root,
        home_dir,
        stub_bin,
        workdir,
    };
    env.init_git()?;

    Ok(env)
}

/// Creates the `agentty` git repository shown below the current project in
/// the opening Projects list.
fn create_fake_project_dirs(env: &BuilderEnv) -> std::io::Result<Vec<PathBuf>> {
    let demo_root = env
        .workdir
        .parent()
        .ok_or_else(|| std::io::Error::other("missing demo root"))?;
    let path = demo_root.join("agentty");
    let git_clone = Command::new("git")
        .args(["clone", "-q"])
        .arg(&env.workdir)
        .arg(&path)
        .status()?;
    if !git_clone.success() {
        return Err(std::io::Error::other(
            "failed to clone demo agentty project",
        ));
    }

    Ok(vec![path])
}

/// Overwrites the `claude` stub in `stub_bin` with a script that ignores its
/// CLI args and stdin, pauses briefly, then emits Claude's `stream-json`
/// protocol output with a canned reply.
fn install_scripted_claude_stub(env: &BuilderEnv) -> std::io::Result<()> {
    let claude_path = env.stub_bin.join("claude");
    // Reply text is hard-coded to match session 1's stacked-commits prompt.
    // Session 2 in the tape never finishes, so the same canned output never
    // renders on-screen for it.
    let reply = r"Stacked sessions let you build dependent features in parallel while Agentty keeps your branches clean with a single evolving commit per session.

```mermaid
flowchart LR
    A[Base branch] --> B[Parent commit P]
    B --> C[Child commit C]
    B --> D[Base after parent merge]
    D --> E[Child C replayed]
```";
    let response = serde_json::json!({
        "answer": reply,
        "questions": [],
        "summary": {
            "turn": "Traced the documented workflow and implementation for stack creation, commit amendment, automatic rebasing, publishing, parent merge, and cancellation.",
            "session": "Explained Agentty’s stacked-session commit model; no workspace files were changed."
        }
    });
    let assistant_event = serde_json::json!({
        "type": "assistant",
        "message": {
            "role": "assistant",
            "content": [{"type": "text", "text": reply}]
        }
    });
    let result_event = serde_json::json!({
        "type": "result",
        "subtype": "success",
        "result": response.to_string(),
        "usage": {"input_tokens": 5, "output_tokens": 42}
    });
    let script = format!(
        r#"#!/bin/sh
if [ "$1" = "update" ]; then
    exit 0
fi
if [ "$1" = "--version" ]; then
    printf '%s\n' 'claude 2.1.7'
    exit 0
fi
# Consume stdin so the parent's writer does not block.
cat > /dev/null 2>&1
# "Thinking" pause: long enough for the viewer to see InProgress and the
# timer tick, but short enough that session 1 reaches Review (~6s total
# with the two trailing sleeps) several seconds before session 2 is
# submitted. That keeps their `updated_at` (whole-second) values distinct
# so the list sort (`updated_at DESC, id`) is deterministic: session 2
# stays the newer top row, with session 1 directly below it.
sleep 4
printf '%s\n' '{{"type":"system","subtype":"init"}}'
sleep 1
printf '%s\n' '{assistant_event}'
sleep 1
printf '%s\n' '{result_event}'
"#
    );
    std::fs::write(&claude_path, &script)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&claude_path, std::fs::Permissions::from_mode(0o755))?;
    }

    Ok(())
}

/// Installs a scripted Codex app-server stub that completes bootstrap and
/// leaves the demo's second turn running until VHS exits.
fn install_scripted_codex_stub(env: &BuilderEnv) -> std::io::Result<()> {
    let codex_path = env.stub_bin.join("codex");
    let script = r#"#!/bin/sh
if [ "$1" = "update" ]; then
    exit 0
fi
if [ "$1" = "--version" ]; then
    printf '%s\n' 'codex-cli 0.114.0'
    exit 0
fi

extract_id() {
    printf '%s\n' "$1" | sed -n 's/.*"id":"\([^"]*\)".*/\1/p'
}

while IFS= read -r request; do
    case "$request" in
        *'"method":"initialize"'*)
            request_id=$(extract_id "$request")
            printf '{"id":"%s","result":{}}\n' "$request_id"
            ;;
        *'"method":"thread/start"'*)
            request_id=$(extract_id "$request")
            printf '{"id":"%s","result":{"thread":{"id":"demo-thread"}}}\n' "$request_id"
            ;;
        *'"method":"turn/start"'*)
            request_id=$(extract_id "$request")
            printf '{"id":"%s","result":{"turn":{"id":"demo-turn"}}}\n' "$request_id"
            printf '%s\n' '{"method":"turn/started","params":{"turn":{"id":"demo-turn"}}}'
            sleep 30
            ;;
    esac
done
"#;
    std::fs::write(&codex_path, script)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&codex_path, std::fs::Permissions::from_mode(0o755))?;
    }

    Ok(())
}

/// Installs an Antigravity (`agy`) stub with a deterministic version into
/// `stub_bin`.
///
/// Agent availability is probed purely by looking for each backend's
/// executable on `PATH` (`RealAgentAvailabilityProbe`), so placing these
/// stubs makes every agent kind — Antigravity, Claude, and Codex — appear in
/// the `/model` agent picker. The stub handles startup's update and version
/// probes but is never used for a session.
fn install_agent_availability_stubs(env: &BuilderEnv) -> std::io::Result<()> {
    let stub_path = env.stub_bin.join("agy");
    std::fs::write(
        &stub_path,
        "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then echo 'agy 0.42.0'; fi\nexit 0\n",
    )?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&stub_path, std::fs::Permissions::from_mode(0o755))?;
    }

    Ok(())
}

/// Symlinks the compiled `agentty` binary into `stub_bin` so that typing
/// `agentty` at the shell (inside the VHS recording) resolves to the real
/// binary through `PATH`.
fn symlink_agentty_into_stub_bin(env: &BuilderEnv) -> std::io::Result<()> {
    let real_binary = cargo_bin("agentty");
    let link_path = env.stub_bin.join("agentty");
    if link_path.exists() {
        std::fs::remove_file(&link_path)?;
    }
    #[cfg(unix)]
    {
        std::os::unix::fs::symlink(&real_binary, &link_path)?;
    }

    Ok(())
}

/// Seeds fake projects, pre-existing sessions in mixed statuses (`Done`,
/// `Review`) backed by different agent models, dashboard activity and usage,
/// and pins a `claude-fable-5` default model on the selected project.
///
/// The first live session explicitly selects the Fable default, while the
/// second selects Codex `gpt-5.6-sol`. The pre-seeded rows never run, so their
/// models are only ever read by the list renderer to decide the per-row agent
/// badge.
fn seed_database(
    env: &BuilderEnv,
    fake_project_paths: &[PathBuf],
    canonical_cwd: &Path,
) -> DemoResult {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?;

    runtime.block_on(async {
        let db_path = env.agentty_root.join(DB_DIR).join(DB_FILE);
        let database = Database::open(&db_path).await?;

        let selected_project_path = fake_project_paths
            .first()
            .ok_or("missing demo agentty project path")?;
        let selected_project_id = database
            .projects()
            .upsert_project(
                &selected_project_path.display().to_string(),
                Some("main".to_string()),
            )
            .await?;
        database
            .projects()
            .touch_project_last_opened(selected_project_id)
            .await?;

        // Pre-register the cwd project so Agentty's startup upsert reuses it
        // as the initially active first row.
        database
            .projects()
            .upsert_project(
                &canonical_cwd.display().to_string(),
                Some("main".to_string()),
            )
            .await?;

        // Model defaults are stored in `project_setting`, not the global
        // `setting` table. The repo helper is crate-private, so drive a
        // second connection directly against the same SQLite file.
        drop(database);
        let mut connection = SqliteConnectOptions::new()
            .filename(&db_path)
            .connect()
            .await?;
        for name in [
            "DefaultSmartModel",
            "DefaultFastModel",
            "DefaultReviewModel",
        ] {
            let query = sqlx::query!(
                r"
INSERT INTO project_setting (project_id, name, value)
VALUES (?, ?, ?)
ON CONFLICT(project_id, name) DO UPDATE SET value = excluded.value
",
                selected_project_id,
                name,
                "claude-fable-5"
            );
            connection.execute(query).await?;
        }

        seed_pre_existing_sessions(
            &mut connection,
            selected_project_id,
            &env.agentty_root,
            PINNED_CLOCK_UNIX_SECONDS,
        )
        .await?;
        seed_dashboard_activity(&mut connection, PINNED_CLOCK_UNIX_SECONDS).await?;

        connection.close().await?;

        Result::<(), Box<dyn std::error::Error>>::Ok(())
    })?;

    Ok(())
}

/// Inserts pre-existing fleet rows into `session` so the list renders with
/// a mix of agents and statuses the moment the demo lands on the Sessions
/// tab.
///
/// These rows are never executed by a worker — their sole purpose is visual
/// presence. Timestamps are anchored a few minutes in the past so the list
/// sort order stays stable and the "last updated" labels read plausibly.
///
/// Non-terminal statuses (`Review`, `Question`, etc.) are filtered by
/// `should_skip_missing_folder_session` unless their worktree folder exists
/// on disk, so this also creates empty placeholder directories under
/// `<AGENTTY_ROOT>/wt/<first-8-of-id>/` for every non-`Done`/`Canceled` row.
async fn seed_pre_existing_sessions(
    connection: &mut sqlx::SqliteConnection,
    cwd_project_id: i64,
    agentty_root: &Path,
    now_seconds: i64,
) -> DemoResult {
    // (id, title, model, status, base_branch, added_lines, deleted_lines,
    //  prompt, age_seconds)
    let rows: &[SeedSessionRow<'_>] = &[
        (
            "aaaa1111-aaaa-1111-aaaa-111111111111",
            "Refactor request handlers",
            "gemini-3.1-pro-preview",
            "Review",
            "main",
            89,
            45,
            "Refactor the request handler pipeline to share middleware.",
            600,
        ),
        (
            "bbbb2222-bbbb-2222-bbbb-222222222222",
            "Add dark mode",
            "gpt-5.6-terra",
            "Done",
            "main",
            127,
            33,
            "Add a dark theme with a toggle in settings.",
            3_600,
        ),
        (
            "cccc3333-cccc-3333-cccc-333333333333",
            "Fix auth token refresh",
            "claude-fable-5",
            "Done",
            "main",
            42,
            18,
            "Fix the token refresh race that logs users out.",
            7_200,
        ),
    ];

    let wt_base = agentty_root.join("wt");
    for (id, title, model, status, base_branch, added, deleted, prompt, age) in rows {
        let created = now_seconds - age;
        if !matches!(*status, "Done" | "Canceled") {
            let stub_worktree = wt_base.join(&id[..8]);
            std::fs::create_dir_all(&stub_worktree)?;
        }
        let query = sqlx::query!(
            r"
INSERT INTO session (
    id, base_branch, status, project_id, model, title, prompt,
    added_lines, deleted_lines, input_tokens, output_tokens, created_at, updated_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
",
            id,
            base_branch,
            status,
            cwd_project_id,
            model,
            title,
            prompt,
            added,
            deleted,
            8_400 + age,
            2_100 + age / 2,
            created,
            created
        );
        connection.execute(query).await?;
    }

    Ok(())
}

/// Seeds recent and historical session-creation events so the opening
/// activity heatmap and work-pace streaks are visibly populated.
async fn seed_dashboard_activity(
    connection: &mut sqlx::SqliteConnection,
    now_seconds: i64,
) -> DemoResult {
    let day_seconds = 86_400_i64;
    let active_day_offsets = [0_i64, 1, 2, 3, 5, 8, 9, 12, 16, 21, 27, 34, 41, 55, 69];

    for (index, day_offset) in active_day_offsets.into_iter().enumerate() {
        let events_for_day = index % 4 + 1;
        for event_index in 0..events_for_day {
            let timestamp = now_seconds
                .saturating_sub(day_offset.saturating_mul(day_seconds))
                .saturating_sub(i64::try_from(event_index).unwrap_or_default() * 1_800);
            let session_id = format!("demo-activity-{day_offset:02}-{event_index:02}");
            let query = sqlx::query!(
                r"
INSERT INTO session (
    id, agent, model, base_branch, status, title, prompt, created_at, updated_at
)
VALUES (?, 'codex', 'gpt-5.6-sol', 'main', 'Done', 'Dashboard activity seed', '', ?, ?)
ON CONFLICT(id) DO NOTHING
",
                &session_id,
                timestamp,
                timestamp
            );
            connection.execute(query).await?;

            let query = sqlx::query!(
                r"
INSERT INTO session_activity (session_id, created_at)
VALUES (?, ?)
ON CONFLICT(session_id) DO NOTHING
",
                session_id,
                timestamp
            );
            connection.execute(query).await?;
        }
    }

    Ok(())
}

#[tokio::test]
async fn dashboard_and_session_seeds_use_pinned_clock_and_stable_ids() -> DemoResult {
    // Arrange
    let temp = tempfile::TempDir::new()?;
    let db_path = temp.path().join("agentty.db");
    let database = Database::open(&db_path).await?;
    let project_id = database
        .projects()
        .upsert_project("/tmp/demo-project", Some("main".to_string()))
        .await?;
    drop(database);
    let mut connection = SqliteConnectOptions::new()
        .filename(&db_path)
        .connect()
        .await?;

    // Act
    seed_pre_existing_sessions(
        &mut connection,
        project_id,
        temp.path(),
        PINNED_CLOCK_UNIX_SECONDS,
    )
    .await?;
    seed_dashboard_activity(&mut connection, PINNED_CLOCK_UNIX_SECONDS).await?;
    seed_dashboard_activity(&mut connection, PINNED_CLOCK_UNIX_SECONDS).await?;

    // Assert
    let activity_count: i64 = sqlx::query_scalar!("SELECT COUNT(*) FROM session_activity")
        .fetch_one(&mut connection)
        .await?;
    let null_session_count: i64 =
        sqlx::query_scalar!("SELECT COUNT(*) FROM session_activity WHERE session_id IS NULL")
            .fetch_one(&mut connection)
            .await?;
    let latest_activity_timestamp: Option<i64> =
        sqlx::query_scalar!("SELECT MAX(created_at) FROM session_activity")
            .fetch_one(&mut connection)
            .await?;
    let latest_seeded_session_timestamp: i64 = sqlx::query_scalar!(
        "SELECT created_at FROM session WHERE id = ?",
        "aaaa1111-aaaa-1111-aaaa-111111111111"
    )
    .fetch_one(&mut connection)
    .await?;
    assert_eq!(activity_count, 36);
    assert_eq!(null_session_count, 0);
    assert_eq!(latest_activity_timestamp, Some(PINNED_CLOCK_UNIX_SECONDS));
    assert_eq!(
        latest_seeded_session_timestamp,
        PINNED_CLOCK_UNIX_SECONDS - 600
    );

    connection.close().await?;

    Ok(())
}

#[test]
fn demo_tape_pins_wall_clock_and_utc_offset() {
    // Arrange
    let env = BuilderEnv {
        agentty_root: PathBuf::from("/tmp/demo-agentty"),
        home_dir: PathBuf::from("/tmp/demo-home"),
        stub_bin: PathBuf::from("/tmp/demo-bin"),
        workdir: PathBuf::from("/tmp/demo-workdir"),
    };

    // Act
    let tape = build_demo_tape(&env, Path::new("/tmp/demo.gif"));

    // Assert
    assert!(tape.contains(&format!(
        "export {PINNED_CLOCK_ENV_VAR}='{PINNED_CLOCK_UNIX_SECONDS}'"
    )));
    assert!(tape.contains(&format!(
        "export {PINNED_CLOCK_UTC_OFFSET_ENV_VAR}='{PINNED_CLOCK_UTC_OFFSET_SECONDS}'"
    )));
}

/// Returns the on-disk destination directory for the marketing demo GIF.
fn repo_demo_dir() -> PathBuf {
    let manifest_dir = env!("CARGO_MANIFEST_DIR");

    Path::new(manifest_dir).join("../../docs/site/static/demo")
}

/// Hand-crafts a VHS tape that shows the user typing `agentty`, landing on
/// a Sessions list pre-seeded with a mixed-agent fleet, then spinning up
/// two sessions backed by different agents, returning to the list, and
/// opening the first session once it transitions to `Review`.
///
/// Each session starts from the `New Session` type picker (confirming
/// `Regular`). The first session explicitly keeps the current Claude default,
/// `claude-fable-5`. The second walks the `/model` picker to Codex and selects
/// `gpt-5.6-sol`, so two current agents work in parallel.
fn build_demo_tape(env: &BuilderEnv, gif_path: &Path) -> String {
    let agentty_root = env.agentty_root.display().to_string();
    let path_env = {
        let parts = [
            env.stub_bin.clone(),
            PathBuf::from("/usr/bin"),
            PathBuf::from("/bin"),
        ];
        std::env::join_paths(parts).map_or_else(
            |_| env.stub_bin.display().to_string(),
            |value| value.to_string_lossy().into_owned(),
        )
    };
    let workdir = env.workdir.display().to_string();
    let second_session = second_session_tape_steps();

    format!(
        r#"Set Shell "bash"
Set FontSize 20
Set Width 1600
Set Height 900
Set Padding 28
Set TypingSpeed 55ms
Set Framerate 30
Set Theme "Dracula"

Output "{gif}"

Hide
Type "export AGENTTY_ROOT='{root}'"
Enter
Sleep 80ms
Type "export {clock_env}='{clock_seconds}'"
Enter
Sleep 80ms
Type "export {clock_offset_env}='{clock_offset_seconds}'"
Enter
Sleep 80ms
Type "export PATH='{path}'"
Enter
Sleep 80ms
Type "export HOME='{root}'"
Enter
Sleep 80ms
Type "unset NO_COLOR"
Enter
Sleep 80ms
Type "cd '{cwd}'"
Enter
Sleep 80ms
Type "clear"
Enter
Sleep 200ms
Show

Sleep 600ms
Type "agentty"
Sleep 400ms
Enter
Sleep 2600ms

# Projects tab lands first; linger on its populated dashboard, move down to
# agentty, and select it. Enter opens that project's Sessions fleet.
Type "j"
Sleep 1300ms
Enter
Sleep 2200ms

# Session 1: New Session picker -> Regular.
Type "a"
Sleep 900ms
Enter
Sleep 500ms

# Open /model, choose Claude, and keep its default claude-fable-5 model.
Type "/model"
Sleep 500ms
Enter
Sleep 700ms

Down
Sleep 400ms
Enter
Sleep 700ms

Enter
Sleep 700ms

Type "Explain how agentty's stacked commits work"
Sleep 900ms
Enter
Sleep 2500ms

Type "q"
Sleep 2500ms

{second_session}

Hide
Type "q"
Sleep 400ms
"#,
        gif = gif_path.display(),
        root = agentty_root,
        clock_env = PINNED_CLOCK_ENV_VAR,
        clock_seconds = PINNED_CLOCK_UNIX_SECONDS,
        clock_offset_env = PINNED_CLOCK_UTC_OFFSET_ENV_VAR,
        clock_offset_seconds = PINNED_CLOCK_UTC_OFFSET_SECONDS,
        path = path_env,
        cwd = workdir,
        second_session = second_session,
    )
}

/// Returns the tape steps that launch the parallel Codex session and then
/// reopen the completed Fable session.
fn second_session_tape_steps() -> &'static str {
    r#"# Session 2: New Session picker -> Regular, then choose Codex gpt-5.6-sol.
Type "a"
Sleep 900ms
Enter
Sleep 500ms

Type "/model"
Sleep 500ms
Enter
Sleep 700ms

Down
Sleep 200ms
Down
Sleep 400ms
Enter
Sleep 700ms

Enter
Sleep 700ms

Type "Add pagination to the users list endpoint"
Sleep 900ms
Enter
Sleep 2500ms

Type "q"
Sleep 1500ms

# Session 2 (the newer row) sits at the top with the cursor on it; step
# down onto session 1 and open it once it reaches Review.
Type "j"
Sleep 400ms
Enter
Sleep 3500ms"#
}