daat-locus 0.1.1

A long-running local agent runtime with memory, workflows, apps, and sleep-time self-improvement.
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
use ratatui::{
    style::{Color, Modifier, Style},
    text::{Line, Span},
};
use serde::{Deserialize, Serialize};

use crate::tool_ui::{
    PatchDiffLineKind, PatchDiffLineUiData, PatchFileUiData, PatchUiData, ReplyDisposition,
    ReplySubject, ReplyUiData, TelegramUiAction, TelegramUiData, glyph,
};

use super::highlight::{diff_scope_backgrounds, highlight_patch_lines};
use super::primitives::{Cell, render_message_activity_lines};

#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PatchActivityCell {
    pub summary_line: String,
    pub files: Vec<PatchFileUiData>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TelegramActivityCell {
    pub title: String,
    pub detail_lines: Vec<String>,
    pub message_lines: Vec<String>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ReplyActivityCell {
    pub disposition: ReplyDisposition,
    pub subject: ReplySubject,
    pub message_lines: Vec<String>,
}

impl Cell for PatchActivityCell {
    fn render_lines(&self) -> Vec<Line<'static>> {
        let visible_files = limit_patch_files(&self.files, 4);
        let diff_backgrounds = diff_scope_backgrounds();
        let old_lineno_width = visible_files
            .iter()
            .flat_map(|file| file.diff_lines.iter().filter_map(|line| line.old_lineno))
            .max()
            .unwrap_or(0)
            .to_string()
            .len()
            .max(1);
        let new_lineno_width = visible_files
            .iter()
            .flat_map(|file| file.diff_lines.iter().filter_map(|line| line.new_lineno))
            .max()
            .unwrap_or(0)
            .to_string()
            .len()
            .max(1);
        let file_noun = if self.files.len() == 1 {
            "File"
        } else {
            "Files"
        };

        let mut lines = vec![Line::from(vec![
            Span::styled(
                glyph::PATCH,
                Style::default()
                    .fg(Color::Magenta)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw("  "),
            Span::styled(
                format!("Edited {} {}", self.files.len(), file_noun),
                Style::default()
                    .fg(Color::Magenta)
                    .add_modifier(Modifier::BOLD),
            ),
        ])];
        if !visible_files.is_empty() {
            lines.push(Line::from(""));
        }
        for (index, file) in visible_files.iter().enumerate() {
            if index > 0 {
                lines.push(Line::from(""));
            }
            lines.push(render_patch_file_header(file));
            lines.extend(render_patch_file_diff_lines(
                file,
                diff_backgrounds,
                old_lineno_width,
                new_lineno_width,
                18,
            ));
        }
        if self.files.len() > visible_files.len() {
            lines.push(Line::from(""));
            lines.push(Line::from(vec![Span::styled(
                format!("{} more files", self.files.len() - visible_files.len()),
                Style::default().fg(Color::DarkGray),
            )]));
        }
        lines
    }
}

impl Cell for TelegramActivityCell {
    fn render_lines(&self) -> Vec<Line<'static>> {
        render_message_activity_lines(
            glyph::TELEGRAM,
            Color::Cyan,
            &self.title,
            &self.detail_lines,
            &self.message_lines,
            6,
            6,
        )
    }
}

impl Cell for ReplyActivityCell {
    fn render_lines(&self) -> Vec<Line<'static>> {
        let (title, color) = match self.disposition {
            ReplyDisposition::Resolved => (self.resolved_title(), Color::LightGreen),
            ReplyDisposition::Dismissed => ("Dismissed", Color::DarkGray),
            ReplyDisposition::Failed => ("Failed", Color::Red),
        };
        let mut lines = vec![Line::from(vec![
            Span::styled(
                glyph::REPLY,
                Style::default().fg(color).add_modifier(Modifier::BOLD),
            ),
            Span::raw("  "),
            Span::styled(
                title,
                Style::default().fg(color).add_modifier(Modifier::BOLD),
            ),
        ])];
        for line in self.message_lines.iter().take(8) {
            lines.push(Line::from(vec![Span::styled(
                line.to_string(),
                Style::default().fg(Color::White),
            )]));
        }
        lines
    }
}

impl ReplyActivityCell {
    fn resolved_title(&self) -> &'static str {
        match self.subject {
            ReplySubject::Message => "Resolved Message",
            ReplySubject::Notice => "Resolved Notice",
        }
    }
}

impl From<PatchUiData> for PatchActivityCell {
    fn from(data: PatchUiData) -> Self {
        PatchActivityCell {
            summary_line: data.summary_line,
            files: data.files,
        }
    }
}

impl From<TelegramUiData> for TelegramActivityCell {
    fn from(data: TelegramUiData) -> Self {
        let mut detail_lines = data.detail_lines;
        if detail_lines.is_empty() {
            detail_lines.push(match data.action {
                TelegramUiAction::ListChats => "list chats".to_string(),
                TelegramUiAction::ReadHistory => "read history".to_string(),
                TelegramUiAction::SelectChat => "select chat".to_string(),
                TelegramUiAction::SendMessage => "send message".to_string(),
                TelegramUiAction::ResolveChat => "resolve chat".to_string(),
            });
        }
        TelegramActivityCell {
            title: data.title,
            detail_lines,
            message_lines: data.message_lines,
        }
    }
}

impl From<ReplyUiData> for ReplyActivityCell {
    fn from(data: ReplyUiData) -> Self {
        ReplyActivityCell {
            disposition: data.disposition,
            subject: data.subject,
            message_lines: data.message_lines,
        }
    }
}

fn limit_patch_files(files: &[PatchFileUiData], limit: usize) -> Vec<PatchFileUiData> {
    if files.len() <= limit {
        return files.to_vec();
    }
    files.iter().take(limit).cloned().collect()
}

fn render_patch_file_header(file: &PatchFileUiData) -> Line<'static> {
    let mut spans = Vec::new();
    spans.push(Span::styled(
        file.path.clone(),
        Style::default().add_modifier(Modifier::BOLD),
    ));
    spans.push(Span::raw(" "));
    spans.push(Span::styled("(", Style::default().fg(Color::DarkGray)));
    spans.push(Span::styled(
        format!("+{}", file.added_lines),
        Style::default().fg(Color::LightGreen),
    ));
    spans.push(Span::raw(" "));
    spans.push(Span::styled(
        format!("-{}", file.removed_lines),
        Style::default().fg(Color::LightRed),
    ));
    spans.push(Span::styled(")", Style::default().fg(Color::DarkGray)));
    Line::from(spans)
}

fn render_patch_file_diff_lines(
    file: &PatchFileUiData,
    diff_backgrounds: super::highlight::DiffScopeBackgrounds,
    old_lineno_width: usize,
    new_lineno_width: usize,
    line_limit: usize,
) -> Vec<Line<'static>> {
    let highlighted = highlight_patch_lines(&file.path, &file.diff_lines);
    let visible_lines = file.diff_lines.iter().take(line_limit).collect::<Vec<_>>();
    let mut lines = visible_lines
        .iter()
        .enumerate()
        .map(|(index, line)| {
            render_patch_diff_line(
                line,
                highlighted
                    .get(index)
                    .and_then(|spans| spans.as_ref())
                    .cloned(),
                diff_backgrounds,
                old_lineno_width,
                new_lineno_width,
            )
        })
        .collect::<Vec<_>>();
    if file.diff_lines.len() > visible_lines.len() {
        lines.push(Line::from(vec![
            Span::styled("", Style::default().fg(Color::DarkGray)),
            Span::raw(" "),
            Span::styled(
                format!(
                    "{} more line(s)",
                    file.diff_lines.len() - visible_lines.len()
                ),
                Style::default().fg(Color::DarkGray),
            ),
        ]));
    }
    lines
}

fn render_patch_diff_line(
    line: &PatchDiffLineUiData,
    highlighted_spans: Option<Vec<Span<'static>>>,
    diff_backgrounds: super::highlight::DiffScopeBackgrounds,
    old_lineno_width: usize,
    new_lineno_width: usize,
) -> Line<'static> {
    if matches!(line.kind, PatchDiffLineKind::HunkBreak) {
        return Line::from(vec![Span::styled(
            format!(
                "{:>old_width$} {:>new_width$} ⋮",
                "",
                "",
                old_width = old_lineno_width,
                new_width = new_lineno_width
            ),
            Style::default().fg(Color::DarkGray),
        )]);
    }

    let (gutter, text_style, background) = match line.kind {
        PatchDiffLineKind::Context => (" ", Style::default().fg(Color::Gray), None),
        PatchDiffLineKind::Delete => (
            "-",
            Style::default().fg(Color::LightRed),
            diff_backgrounds.deleted.or(Some(Color::Rgb(58, 24, 24))),
        ),
        PatchDiffLineKind::Add => (
            "+",
            Style::default().fg(Color::LightGreen),
            diff_backgrounds.inserted.or(Some(Color::Rgb(22, 44, 30))),
        ),
        PatchDiffLineKind::HunkBreak => unreachable!(),
    };
    let old_lineno = line
        .old_lineno
        .map(|lineno| lineno.to_string())
        .unwrap_or_default();
    let new_lineno = line
        .new_lineno
        .map(|lineno| lineno.to_string())
        .unwrap_or_default();

    let mut spans = vec![
        Span::styled(
            format!("{old_lineno:>old_width$}", old_width = old_lineno_width),
            Style::default().fg(Color::DarkGray),
        ),
        Span::raw(" "),
        Span::styled(
            format!("{new_lineno:>new_width$}", new_width = new_lineno_width),
            Style::default().fg(Color::DarkGray),
        ),
        Span::raw(" "),
        Span::styled(gutter, text_style.add_modifier(Modifier::BOLD)),
        Span::raw(" "),
    ];
    if let Some(highlighted_spans) = highlighted_spans {
        for span in highlighted_spans {
            let style = match background {
                Some(color) => span.style.bg(color),
                None => span.style,
            };
            spans.push(Span::styled(span.content.to_string(), style));
        }
    } else {
        let style = match background {
            Some(color) => text_style.bg(color),
            None => text_style,
        };
        spans.push(Span::styled(line.text.clone(), style));
    }
    Line::from(spans)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tool_ui::PatchFileOperation;

    fn line_text(line: &Line<'static>) -> String {
        line.spans
            .iter()
            .map(|span| span.content.as_ref())
            .collect::<String>()
    }

    #[test]
    fn patch_activity_cell_renders_diff_lines() {
        let cell = PatchActivityCell {
            summary_line: "1 file(s) changed (+1 -1)".to_string(),
            files: vec![PatchFileUiData {
                path: "src/app.rs".to_string(),
                operation: PatchFileOperation::Update,
                added_lines: 1,
                removed_lines: 1,
                diff_lines: vec![
                    PatchDiffLineUiData {
                        kind: PatchDiffLineKind::Context,
                        old_lineno: Some(1),
                        new_lineno: Some(1),
                        text: "fn main() {".to_string(),
                    },
                    PatchDiffLineUiData {
                        kind: PatchDiffLineKind::Delete,
                        old_lineno: Some(2),
                        new_lineno: None,
                        text: "    println!(\"old\");".to_string(),
                    },
                    PatchDiffLineUiData {
                        kind: PatchDiffLineKind::Add,
                        old_lineno: None,
                        new_lineno: Some(2),
                        text: "    println!(\"new\");".to_string(),
                    },
                ],
            }],
        };

        let lines = cell.render_lines();
        let rendered = lines.iter().map(line_text).collect::<Vec<_>>();

        assert!(
            rendered
                .iter()
                .any(|line| line.contains("∂  Edited 1 File"))
        );
        assert!(
            rendered
                .iter()
                .any(|line| line.contains("src/app.rs (+1 -1)"))
        );
        assert!(
            rendered
                .iter()
                .any(|line| line.contains('-') && line.contains("println!(\"old\");"))
        );
        assert!(
            rendered
                .iter()
                .any(|line| line.contains('+') && line.contains("println!(\"new\");"))
        );
    }

    #[test]
    fn reply_activity_cell_distinguishes_message_and_notice_resolution() {
        let message = ReplyActivityCell {
            disposition: ReplyDisposition::Resolved,
            subject: ReplySubject::Message,
            message_lines: Vec::new(),
        }
        .render_lines()
        .into_iter()
        .map(|line| line_text(&line))
        .collect::<Vec<_>>();
        assert!(message.iter().any(|line| line.contains("Resolved Message")));

        let notice = ReplyActivityCell {
            disposition: ReplyDisposition::Resolved,
            subject: ReplySubject::Notice,
            message_lines: Vec::new(),
        }
        .render_lines()
        .into_iter()
        .map(|line| line_text(&line))
        .collect::<Vec<_>>();
        assert!(notice.iter().any(|line| line.contains("Resolved Notice")));
    }
}