rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
//! The file list `rho/fs/files` streams: what git lists in a work tree,
//! less the files it tracks that are gone, or every file under a folder
//! outside one, ported from rho-ui's Files panel (`right_panel/files.rs`).

use std::{
    collections::{HashSet, VecDeque},
    fs::ReadDir,
    path::PathBuf,
    process::{ExitStatus, Output},
};

use rho_protocol::{
    methods::{HostStreamId, HOST_STREAM_FAILURE_MAX_BYTES},
    Caller, ClientEnvironment, HostStreamClosed, HostStreamWriter, RpcError,
};
use tokio::{
    io::{AsyncBufReadExt as _, BufReader},
    process::Command,
};

use super::{blocking, failed, spawn_stream};
use crate::git::{did_not_start, git_failure, output_within, NoOutput, Running, UNTRACKED_FILES};

/// The most entries a walk outside git reads from a folder in one hop to
/// the blocking pool, so a folder of a million entries is read a batch at a
/// time and a small limit stops the walk after one batch.
//
// Here (2026-12-03, Linux) reading a folder of 100,000 entries took 189
// `getdents64` calls, about 530 entries each, and Python's `os.scandir`
// read 1024 entries with each one's kind in 0.2 ms: a batch is about two
// system calls, against a hop that costs a thread wake-up, and a limit
// that stops the walk early stops it within 0.2 ms of reading.
const WALK_BATCH: usize = 1024;

/// Opens the stream of the files in `folder`, a folder, and starts writing
/// it, at most `limit` bytes: the paths git lists, run with the login's
/// `environment`, in a work tree; every file under it elsewhere. Fails
/// before opening it when git cannot say what is gone, or doesn't answer.
pub(super) async fn list_files(
    caller: &Caller,
    folder: PathBuf,
    environment: ClientEnvironment,
    limit: u64,
) -> Result<HostStreamId, RpcError> {
    let git = Git {
        folder,
        environment,
    };
    if git.inside_work_tree().await? {
        let deleted = git.deleted().await?;
        return spawn_stream(caller, move |writer| {
            stream_git(git, deleted, writer, limit)
        });
    }
    spawn_stream(caller, move |writer| stream_walk(git.folder, writer, limit))
}

/// git, as `files` runs it in `folder` ([`crate::git::host_command`]).
struct Git {
    folder: PathBuf,
    environment: ClientEnvironment,
}

impl Git {
    fn command(&self, args: &[&str]) -> Command {
        let mut command = crate::git::host_command(&self.folder, &self.environment);
        command.args(args);
        command
    }

    /// What git printed, run to its end within [`crate::git::GIT_DEADLINE`]:
    /// for what `files` asks before it opens the stream.
    async fn output(&self, args: &[&str]) -> Result<Output, NoOutput> {
        output_within(&mut self.command(args), &self.folder).await
    }

    /// Whether the folder is in a git work tree: not when git fails or is
    /// missing, so the folder is walked instead, as rho-ui did. Fails only
    /// when git doesn't answer in time.
    async fn inside_work_tree(&self) -> Result<bool, RpcError> {
        match self.output(&["rev-parse", "--is-inside-work-tree"]).await {
            Ok(output) => Ok(output.status.success() && output.stdout.trim_ascii() == b"true"),
            Err(NoOutput::DidNotStart(_)) => Ok(false),
            Err(late @ NoOutput::Late) => Err(failed(late.message(&self.folder))),
        }
    }

    /// The tracked files missing from the work tree, which
    /// `ls-files --stage` still lists.
    async fn deleted(&self) -> Result<HashSet<Vec<u8>>, RpcError> {
        let output = self
            .output(&["ls-files", "-z", "--deleted"])
            .await
            .map_err(|no_output| failed(no_output.message(&self.folder)))?;
        if !output.status.success() {
            return Err(failed(git_failure(&output.stderr, output.status)));
        }
        Ok(output
            .stdout
            .split(|&byte| byte == 0)
            .filter(|path| !path.is_empty())
            .map(<[u8]>::to_vec)
            .collect())
    }
}

/// One of the two `git ls-files` runs `files` streams, one after the
/// other, in the order git lists them when asked for both at once:
/// `--stage`, which tells a submodule from a file, can't be asked with
/// `--others`.
#[derive(Clone, Copy)]
enum Listing {
    /// The untracked files git doesn't ignore.
    Untracked,
    /// The files git tracks, each as `<mode> <object> <stage>\t<path>`.
    Tracked,
}

impl Listing {
    const BOTH: [Self; 2] = [Self::Untracked, Self::Tracked];

    fn args(self) -> &'static [&'static str] {
        match self {
            Self::Untracked => &UNTRACKED_FILES,
            Self::Tracked => &["ls-files", "-z", "--stage"],
        }
    }

    /// The path of the file one record of this listing names; none when it
    /// names no file: a submodule's commit (mode `160000`), or a folder, as
    /// an untracked repository inside the work tree is listed (`dir/`).
    fn file(self, record: &[u8]) -> Option<&[u8]> {
        let path = match self {
            Self::Untracked => record,
            Self::Tracked => {
                let tab = record.iter().position(|&byte| byte == b'\t')?;
                if record.starts_with(b"160000 ") {
                    return None;
                }
                &record[tab + 1..]
            }
        };
        (!path.is_empty() && !path.ends_with(b"/")).then_some(path)
    }
}

/// How one listing ended.
enum Listed {
    /// Git listed everything; what fit is held or streamed.
    All,
    /// A path would take the stream past its limit.
    Full,
    /// Git failed, for the reason given.
    Failed(String),
    /// The stream closed, so nothing more is written.
    Closed,
}

/// The paths a `files` stream carries: each ended by a NUL and counted
/// against the call's limit, held until flushed to the stream.
struct Paths {
    limit: u64,
    counted: u64,
    held: Vec<u8>,
}

/// What [`Paths::push`] did with a path.
enum Pushed {
    Held,
    /// It is not UTF-8, so it cannot travel: left out.
    Skipped,
    /// It would take the stream past its limit: left out, and the stream
    /// ends truncated.
    Full,
}

impl Paths {
    fn new(limit: u64) -> Self {
        Self {
            limit,
            counted: 0,
            held: Vec::new(),
        }
    }

    /// Holds `path`, unless it cannot travel or would not fit.
    fn push(&mut self, path: &[u8]) -> Pushed {
        if std::str::from_utf8(path).is_err() {
            return Pushed::Skipped;
        }
        let counted = self.counted.saturating_add(path.len() as u64 + 1);
        if counted > self.limit {
            return Pushed::Full;
        }
        self.counted = counted;
        self.held.extend_from_slice(path);
        self.held.push(0);
        Pushed::Held
    }

    /// Hands the stream the paths held.
    async fn flush(&mut self, writer: &mut HostStreamWriter) -> Result<(), HostStreamClosed> {
        if self.held.is_empty() {
            return Ok(());
        }
        writer.write(std::mem::take(&mut self.held)).await
    }

    /// Ends the stream done, once the paths held are in it.
    async fn finish(mut self, mut writer: HostStreamWriter) {
        if self.flush(&mut writer).await.is_ok() {
            writer.finish();
        }
    }

    /// Ends the stream truncated, once the paths held are in it.
    async fn truncate(mut self, mut writer: HostStreamWriter) {
        if self.flush(&mut writer).await.is_ok() {
            writer.truncate();
        }
    }

    /// Ends the stream failed, once the paths held are in it.
    async fn fail(mut self, mut writer: HostStreamWriter, message: String) {
        if self.flush(&mut writer).await.is_ok() {
            writer.fail(message);
        }
    }
}

/// Streams what git lists in its work tree ([`Listing::BOTH`]), less the
/// `deleted` paths and what isn't a file. Kills git, by dropping it, once
/// the stream is cut at `limit` or closed.
async fn stream_git(git: Git, deleted: HashSet<Vec<u8>>, mut writer: HostStreamWriter, limit: u64) {
    let mut paths = Paths::new(limit);
    for listing in Listing::BOTH {
        let started = Running::start(
            &mut git.command(listing.args()),
            HOST_STREAM_FAILURE_MAX_BYTES,
        );
        let listed = match started {
            Ok(running) => read_listing(running, listing, &deleted, &mut paths, &mut writer).await,
            Err(error) => Listed::Failed(did_not_start(&git.folder, &error)),
        };
        match listed {
            Listed::All => {}
            Listed::Full => return paths.truncate(writer).await,
            Listed::Failed(why) => return paths.fail(writer, why).await,
            Listed::Closed => return,
        }
    }
    paths.finish(writer).await;
}

/// Reads what `git`, listing `listing`, prints into `paths`, handing the
/// stream what is held before each wait on git, less the `deleted` paths
/// and the repeats it lists for a file a merge left in conflict, one per
/// stage. Returning before git is done drops it, which kills it.
async fn read_listing(
    mut git: Running,
    listing: Listing,
    deleted: &HashSet<Vec<u8>>,
    paths: &mut Paths,
    writer: &mut HostStreamWriter,
) -> Listed {
    let mut stdout = BufReader::new(&mut git.stdout);
    let mut record = Vec::new();
    let mut previous = Vec::new();
    loop {
        if stdout.buffer().is_empty() && paths.flush(writer).await.is_err() {
            return Listed::Closed;
        }
        record.clear();
        let read = tokio::select! {
            read = stdout.read_until(0, &mut record) => read,
            () = writer.closed() => return Listed::Closed,
        };
        match read {
            Ok(0) => break,
            Ok(_) => {}
            Err(error) => return Listed::Failed(format!("Couldn't read what git listed: {error}")),
        }
        if record.last() == Some(&0) {
            record.pop();
        }
        let Some(path) = listing.file(&record) else {
            continue;
        };
        if path == previous || deleted.contains(path) {
            continue;
        }
        if matches!(paths.push(path), Pushed::Full) {
            return Listed::Full;
        }
        previous.clear();
        previous.extend_from_slice(path);
    }
    drop(stdout);
    match git.finish(ExitStatus::success).await {
        Ok(()) => Listed::All,
        Err(why) => Listed::Failed(why),
    }
}

/// One entry of a folder `files` walks.
struct Entry {
    path: PathBuf,
    /// Its path from the folder walked, `/` between its parts.
    relative: Vec<u8>,
    is_dir: bool,
}

/// A folder the walk is in.
struct Folder {
    entries: Entries,
    /// Its path from the folder walked, ending in `/` unless it is that one.
    prefix: Vec<u8>,
    /// Entries read and not yet visited, in the order read.
    unvisited: VecDeque<Entry>,
}

/// What is left to read of a folder the walk is in.
enum Entries {
    /// Not opened yet.
    Unopened(PathBuf),
    /// Open, with more to read.
    Open(ReadDir),
    /// All read, or it can't be.
    Read,
}

impl Folder {
    fn new(path: PathBuf, prefix: Vec<u8>) -> Self {
        Self {
            entries: Entries::Unopened(path),
            prefix,
            unvisited: VecDeque::new(),
        }
    }
}

/// Streams the path of every file under `folder` that isn't a folder, as
/// `files` answers outside a git work tree. It goes as `find` lists them,
/// depth first, each folder's entries in the order the system reads them,
/// so a list cut at `limit` keeps the files rho-ui's own walk kept. Like
/// `find`, it doesn't follow symlinks, listing each as a file, and skips
/// folders it can't read. It holds open the folders it is in, reading
/// each [`WALK_BATCH`] entries at a time.
async fn stream_walk(folder: PathBuf, mut writer: HostStreamWriter, limit: u64) {
    let mut paths = Paths::new(limit);
    // Innermost last.
    let mut folders = vec![Folder::new(folder, Vec::new())];
    while let Some(innermost) = folders.last_mut() {
        if let Some(entry) = innermost.unvisited.pop_front() {
            if entry.is_dir {
                let mut prefix = entry.relative;
                prefix.push(b'/');
                folders.push(Folder::new(entry.path, prefix));
                continue;
            }
            match paths.push(&entry.relative) {
                Pushed::Held | Pushed::Skipped => continue,
                Pushed::Full => return paths.truncate(writer).await,
            }
        }
        let entries = std::mem::replace(&mut innermost.entries, Entries::Read);
        if matches!(entries, Entries::Read) {
            folders.pop();
            continue;
        }
        // Hand the stream what is held before reading more.
        if paths.flush(&mut writer).await.is_err() {
            return;
        }
        let prefix = innermost.prefix.clone();
        let read = tokio::select! {
            read = blocking(move || read_batch(entries, &prefix)) => read,
            () = writer.closed() => return,
        };
        (innermost.entries, innermost.unvisited) =
            read.unwrap_or_else(|_| (Entries::Read, VecDeque::new()));
    }
    paths.finish(writer).await;
}

/// Reads up to [`WALK_BATCH`] more of a folder's `entries`, opening it
/// first when it isn't yet, each named from the folder walked by `prefix`
/// and its name; what is left to read after them.
fn read_batch(entries: Entries, prefix: &[u8]) -> (Entries, VecDeque<Entry>) {
    let mut read_dir = match entries {
        Entries::Unopened(dir) => match std::fs::read_dir(dir) {
            Ok(read_dir) => read_dir,
            Err(_) => return (Entries::Read, VecDeque::new()),
        },
        Entries::Open(read_dir) => read_dir,
        Entries::Read => return (Entries::Read, VecDeque::new()),
    };
    let batch: VecDeque<Entry> = read_dir
        .by_ref()
        .flatten()
        .take(WALK_BATCH)
        .map(|entry| {
            let mut relative = prefix.to_vec();
            relative.extend_from_slice(entry.file_name().as_encoded_bytes());
            Entry {
                // Not through a symlink.
                is_dir: entry.file_type().is_ok_and(|kind| kind.is_dir()),
                path: entry.path(),
                relative,
            }
        })
        .collect();
    let left = if batch.len() < WALK_BATCH {
        Entries::Read
    } else {
        Entries::Open(read_dir)
    };
    (left, batch)
}