adbrent 0.2.2

One Android device per AI agent: an adb device lock for parallel Claude Code, Codex and other agent sessions
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
//! The `adbrent` management commands.

use crate::adb::{self, Device};
use crate::desk::{self, Claim};
use crate::store::{self, Lease};
use crate::{hook, install};
use std::time::{Duration, Instant};

const HELP: &str = "\
adbrent - a rental desk for Android devices shared between AI agents

USAGE
  adbrent status [--json]          Devices and who rents each one
  adbrent rent [SERIAL] [--wait[=SECONDS]] [--force]
                                   Rent a device (a free one if none is named)
                                   and print its serial; --wait queues for one;
                                   --force takes a device that looks in use
                                   outside adbrent
  adbrent release [SERIAL...]      Hand back your devices (all of them by default)
  adbrent release --force SERIAL   Take a device back from whoever holds it
  adbrent release --force --all    Clear every rental
  adbrent ignore [TEXT]            Stop counting on-device commands containing TEXT
                                   as outside use (no TEXT: list; --remove TEXT)
  adbrent log [-n N] [--json]      Recent refusals, forced rentals and feedback
  adbrent feedback [TEXT]          Record a problem or a suggestion (no TEXT: list them)
  adbrent feedback --issue         Print a GitHub issue link filled in from the latest one
  adbrent env                      Shell line that puts the adb stand-in on PATH
  adbrent install [--shim-only]    Set up ~/.adbrent and the Claude Code plugin
  adbrent uninstall                Remove both

Agents do not need these to work: with the stand-in on PATH, plain `adb`
rents a free device on first use and keeps it until the session ends.
";

pub fn run(args: Vec<String>) -> i32 {
    let rest = args.get(1..).unwrap_or_default();
    match args.first().map(String::as_str) {
        Some("status" | "ls") => status(rest),
        Some("rent") => rent(rest),
        Some("release") => release(rest),
        Some("ignore") => ignore(rest),
        Some("log") => log(rest),
        Some("feedback") => feedback(rest),
        Some("env") => {
            println!("{}", install::env_lines(None));
            0
        }
        Some("hook") => hook::run(rest.first().map(String::as_str)),
        Some("install") => install::install(rest.iter().any(|a| a == "--shim-only")),
        Some("uninstall") => install::uninstall(),
        Some("version" | "--version" | "-V") => {
            println!("adbrent {}", env!("CARGO_PKG_VERSION"));
            0
        }
        Some("help" | "--help" | "-h") | None => {
            print!("{HELP}");
            0
        }
        Some(other) => {
            eprintln!("adbrent: unknown command `{other}`\n\n{HELP}");
            2
        }
    }
}

fn connected() -> Vec<Device> {
    adb::real_adb()
        .map(|real| adb::devices(&real, &[]))
        .unwrap_or_default()
}

fn status(args: &[String]) -> i32 {
    let _ = store::release(|_| false); // sweep rentals whose owner is gone
    let me = store::me();
    let leases = store::leases();
    let mut rows: Vec<(String, String, String, Option<&Lease>)> = connected()
        .into_iter()
        .map(|d| {
            let lease = leases.iter().find(|l| l.serial == d.serial);
            (d.serial, d.model.replace('_', " "), d.state, lease)
        })
        .collect();
    for l in &leases {
        if !rows.iter().any(|r| r.0 == l.serial) {
            rows.push((l.serial.clone(), String::new(), "absent".into(), Some(l)));
        }
    }

    // Ask each unrented device, all at once, whether something else is using it.
    let outside: Vec<(String, Vec<String>)> = match adb::real_adb() {
        None => Vec::new(),
        Some(real) => std::thread::scope(|scope| {
            let probes: Vec<_> = rows
                .iter()
                .filter(|r| r.3.is_none() && r.2 == "device")
                .map(|r| {
                    (
                        r.0.clone(),
                        scope.spawn(|| desk::outside(&real, &r.0).streams),
                    )
                })
                .collect();
            probes
                .into_iter()
                .map(|(serial, probe)| (serial, probe.join().unwrap_or_default()))
                .collect()
        }),
    };
    let outside = |serial: &str| {
        outside
            .iter()
            .find(|o| o.0 == serial)
            .map(|o| o.1.clone())
            .unwrap_or_default()
    };

    if args.iter().any(|a| a == "--json") {
        let json: Vec<_> = rows
            .iter()
            .map(|(serial, model, state, lease)| {
                serde_json::json!({
                    "serial": serial,
                    "model": model,
                    "state": state,
                    "rented_by": lease.map(|l| &l.label),
                    "since": lease.map(|l| l.since),
                    "mine": lease.is_some_and(|l| l.owner == me.owner),
                    "in_use_outside_adbrent": outside(serial),
                })
            })
            .collect();
        println!(
            "{}",
            serde_json::to_string_pretty(&json).unwrap_or_default()
        );
        return 0;
    }
    if rows.is_empty() {
        println!("No devices connected.");
        return 0;
    }
    let w0 = rows.iter().map(|r| r.0.len()).max().unwrap_or(0).max(6);
    let w1 = rows.iter().map(|r| r.1.len()).max().unwrap_or(0).max(5);
    let w2 = rows.iter().map(|r| r.2.len()).max().unwrap_or(0).max(5);
    println!(
        "{:w0$}  {:w1$}  {:w2$}  RENTED BY",
        "SERIAL", "MODEL", "STATE"
    );
    for (serial, model, state, lease) in &rows {
        let renter = match lease {
            None => match outside(serial) {
                streams if streams.is_empty() => "-".to_string(),
                streams => format!(
                    "nobody, but in use outside adbrent ({})",
                    streams.join("; ")
                ),
            },
            Some(l) if l.owner == me.owner => format!("you ({}, {})", l.label, l.age()),
            Some(l) => format!("{}, {}", l.label, l.age()),
        };
        println!("{serial:w0$}  {model:w1$}  {state:w2$}  {renter}");
    }
    0
}

fn ago(event: &serde_json::Value) -> String {
    let s = store::now().saturating_sub(event["t"].as_u64().unwrap_or(0));
    match s {
        0..=59 => format!("{s}s ago"),
        60..=3599 => format!("{}m ago", s / 60),
        3600..=86_399 => format!("{}h ago", s / 3600),
        _ => format!("{}d ago", s / 86_400),
    }
}

fn describe(event: &serde_json::Value) -> String {
    let text = |key: &str| event[key].as_str().unwrap_or_default();
    let device = if text("serial").is_empty() {
        String::new()
    } else {
        format!(" {}", text("serial"))
    };
    format!(
        "{:>8}  {}{device}  [{}]  {}",
        ago(event),
        text("kind"),
        text("who"),
        text("detail")
    )
}

fn log(args: &[String]) -> i32 {
    let count = args
        .iter()
        .position(|a| a == "-n")
        .and_then(|i| args.get(i + 1))
        .and_then(|n| n.parse().ok())
        .unwrap_or(30);
    let events = store::events();
    let recent = &events[events.len().saturating_sub(count)..];
    if args.iter().any(|a| a == "--json") {
        println!(
            "{}",
            serde_json::to_string_pretty(recent).unwrap_or_default()
        );
    } else if recent.is_empty() {
        println!("Nothing logged yet.");
    } else {
        recent.iter().for_each(|e| println!("{}", describe(e)));
    }
    0
}

/// Percent-encode for a URL query value.
fn encode(text: &str) -> String {
    text.bytes()
        .map(|b| match b {
            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                (b as char).to_string()
            }
            _ => format!("%{b:02X}"),
        })
        .collect()
}

fn feedback(args: &[String]) -> i32 {
    let events = store::events();
    let notes: Vec<(usize, &serde_json::Value)> = events
        .iter()
        .enumerate()
        .filter(|(_, e)| e["kind"] == "feedback")
        .collect();
    if args.iter().any(|a| a == "--issue") {
        let Some(&(at, note)) = notes.last() else {
            eprintln!("adbrent: no feedback recorded yet");
            return 1;
        };
        // The note, plus what adbrent did just before it. Printed for a person to
        // read and submit; nothing is sent from here.
        let before: Vec<String> = events[at.saturating_sub(5)..at]
            .iter()
            .map(describe)
            .collect();
        let body = format!(
            "{}\n\nadbrent {} on {}\n\nWhat adbrent logged just before:\n```\n{}\n```\n",
            note["detail"].as_str().unwrap_or_default(),
            note["version"].as_str().unwrap_or_default(),
            std::env::consts::OS,
            before.join("\n")
        );
        let title: String = note["detail"]
            .as_str()
            .unwrap_or_default()
            .chars()
            .take(70)
            .collect();
        println!(
            "https://github.com/iammosab/adbrent/issues/new?title={}&body={}",
            encode(&title),
            encode(&body)
        );
        return 0;
    }
    let text = args
        .iter()
        .filter(|a| !a.starts_with("--"))
        .cloned()
        .collect::<Vec<_>>()
        .join(" ");
    if text.trim().is_empty() {
        if notes.is_empty() {
            println!("No feedback recorded yet.");
        }
        notes.iter().for_each(|(_, e)| println!("{}", describe(e)));
        return 0;
    }
    store::log_event("feedback", &store::me(), "", text.trim());
    println!("Recorded. The user can read it with `adbrent feedback`.");
    0
}

fn ignore(args: &[String]) -> i32 {
    let remove = args.iter().any(|a| a == "--remove");
    let text: Vec<&String> = args.iter().filter(|a| !a.starts_with("--")).collect();
    let mut list = store::ignored();
    match text.first() {
        None if remove => {
            eprintln!("adbrent: --remove needs the text to stop ignoring");
            return 2;
        }
        None => {
            if list.is_empty() {
                println!("Nothing is ignored.");
            }
            list.iter().for_each(|p| println!("{p}"));
            return 0;
        }
        Some(text) if remove => list.retain(|p| p != *text),
        Some(text) => {
            if !list.contains(text) {
                list.push((*text).clone());
            }
        }
    }
    match store::set_ignored(&list) {
        Ok(()) => 0,
        Err(e) => {
            eprintln!("adbrent: cannot save the ignore list: {e}");
            1
        }
    }
}

fn rent(args: &[String]) -> i32 {
    let mut serial = None;
    let mut wait = None;
    let mut force = false;
    for a in args {
        if a == "--wait" {
            wait = Some(u64::MAX);
        } else if let Some(secs) = a.strip_prefix("--wait=") {
            match secs.parse() {
                Ok(s) => wait = Some(s),
                Err(_) => {
                    eprintln!("adbrent: --wait takes a number of seconds");
                    return 2;
                }
            }
        } else if a == "--force" {
            force = true;
        } else if a.starts_with('-') {
            eprintln!("adbrent: unknown option `{a}`");
            return 2;
        } else {
            serial = Some(a.clone());
        }
    }
    let Some(real) = adb::real_adb() else {
        eprintln!("adbrent: cannot find the real adb on PATH (set ADBRENT_REAL_ADB to its path)");
        return 1;
    };
    let me = store::me();
    let started = Instant::now();
    let mut announced = false;
    loop {
        let devs = adb::devices(&real, &[]);
        let outcome = match &serial {
            Some(s) if !devs.iter().any(|d| &d.serial == s) => {
                eprintln!("adbrent: {s} is not connected. `adbrent status` lists devices.");
                return 1;
            }
            Some(s) => match desk::claim(&real, s, &me, &devs, force) {
                Claim::Rented { .. } => Ok(s.clone()),
                Claim::Refused(msg) => Err(msg),
                Claim::Unrecorded(e) => {
                    eprintln!("adbrent: cannot record the rental: {e}");
                    return 1;
                }
            },
            None => {
                // Keep a device this session already holds; otherwise pick a free one.
                let leases = store::leases();
                let held = devs.iter().find(|d| {
                    leases
                        .iter()
                        .any(|l| l.serial == d.serial && l.owner == me.owner)
                });
                let pool: Vec<&Device> = devs.iter().collect();
                match held {
                    Some(d) => Ok(d.serial.clone()),
                    None => desk::pick(&real, &me, &pool, &devs).map(|d| d.serial.clone()),
                }
            }
        };
        let blocker = match outcome {
            Ok(serial) => {
                println!("{serial}");
                return 0;
            }
            Err(msg) => msg,
        };
        let limit = match wait {
            Some(limit) => limit,
            None => {
                eprintln!("{blocker}");
                return 1;
            }
        };
        if started.elapsed().as_secs() >= limit {
            eprintln!(
                "adbrent: gave up waiting after {limit}s. `adbrent status` shows who holds what."
            );
            return 1;
        }
        if !announced {
            eprintln!("adbrent: waiting for a device to become free...");
            announced = true;
        }
        std::thread::sleep(Duration::from_secs(1));
    }
}

fn release(args: &[String]) -> i32 {
    let force = args.iter().any(|a| a == "--force");
    let all = args.iter().any(|a| a == "--all");
    let serials: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect();
    if force && !all && serials.is_empty() {
        eprintln!("adbrent: --force needs a serial, or --all to clear every rental");
        return 2;
    }
    let me = store::me();
    let named = |l: &Lease| serials.is_empty() || serials.iter().any(|s| **s == l.serial);
    let result = store::release(|l| named(l) && (force || l.owner == me.owner));
    match result {
        Ok(done) if done.is_empty() => {
            // Naming a device someone else holds is the one case worth an error.
            let others: Vec<String> = serials
                .iter()
                .filter_map(|s| store::held_by_other(s, &me))
                .map(|l| format!("{} ({})", l.serial, l.label))
                .collect();
            if others.is_empty() {
                println!("Nothing to release.");
                0
            } else {
                eprintln!(
                    "adbrent: rented by another agent: {}. Use --force to take it back.",
                    others.join(", ")
                );
                1
            }
        }
        Ok(done) => {
            println!("Released {}.", done.join(", "));
            0
        }
        Err(e) => {
            eprintln!("adbrent: cannot release: {e}");
            1
        }
    }
}