wryme 1.2.0

wryme • that small, calm window where agents come to meet you
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
// Rendering. Three regions:
//
//   ┌──────────────────────────────────────┐
//   │ > input here                         │   top: input bar
//   ├──────────────────────────────────────┤
//   │ assistant • streaming                │   middle: messages,
//   │ newest message text                  │           newest at top,
//   │                                      │           older below it
//   │ you                                  │
//   │ older question                       │
//   ├──────────────────────────────────────┤
//   │ model • N msgs • status              │   bottom: status
//   └──────────────────────────────────────┘

use ratatui::{
    layout::{Constraint, Direction, Layout, Position},
    style::{Color, Modifier, Style},
    text::{Line, Span, Text},
    widgets::{Block, Borders, Paragraph, Wrap},
    Frame,
};
use unicode_width::UnicodeWidthStr;

use crate::app::{App, Message, Phase, Role, ViewMode};
use crate::input::Input;
use crate::popup;
use crate::shop::Protocol;

pub fn draw(f: &mut Frame, app: &mut App, input: &Input) {
    let area = f.area();
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // input box
            Constraint::Min(1),    // messages
            Constraint::Length(1), // status
        ])
        .split(area);

    // ---- input bar (top) ----
    let prompt = "";
    let input_block = Block::default()
        .borders(Borders::ALL)
        .border_style(if app.in_flight {
            Style::default().fg(Color::DarkGray)
        } else {
            Style::default().fg(Color::Cyan)
        })
        .title(if app.in_flight {
            " streaming… (Esc cancel) "
        } else {
            " write. Enter to send, Ctrl-C to quit "
        });

    // The prompt stays fixed on the left; only the text scrolls, so the
    // caret (and the letters being typed) stay pinned at the right edge
    // instead of running past it, while old text slides out the left side.
    let inner = ratatui::layout::Rect {
        x: chunks[0].x + 1,
        y: chunks[0].y + 1,
        width: chunks[0].width.saturating_sub(2),
        height: chunks[0].height.saturating_sub(2),
    };
    let visible_width = (inner.width as usize).saturating_sub(prompt.len());
    let h_scroll = input.scroll_offset(visible_width);

    // Draw the border + title.
    f.render_widget(Paragraph::new(Line::from("")).block(input_block), chunks[0]);
    // Draw the fixed prompt at the inner-left.
    f.render_widget(
        Paragraph::new(Line::from(Span::styled(
            prompt,
            Style::default().fg(Color::Cyan),
        ))),
        ratatui::layout::Rect {
            x: inner.x,
            y: inner.y,
            width: prompt.len() as u16,
            height: inner.height,
        },
    );
    // Draw the text, scrolled so the caret hugs the right edge.
    let text_area = ratatui::layout::Rect {
        x: inner.x + prompt.len() as u16,
        y: inner.y,
        width: visible_width as u16,
        height: inner.height,
    };
    f.render_widget(
        Paragraph::new(Line::from(Span::raw(&input.text))).scroll((0, h_scroll as u16)),
        text_area,
    );

    // Place the terminal cursor inside the input box.
    let cursor_x = text_area.x + input.display_col() - h_scroll as u16;
    let cursor_y = text_area.y;
    if cursor_x < text_area.x + text_area.width {
        f.set_cursor_position(Position {
            x: cursor_x,
            y: cursor_y,
        });
    }

    // ---- messages (middle, newest first, paged) ----
    let mut lines: Vec<Line> = Vec::new();
    let msg_width = chunks[1].width;
    for msg in app.messages.iter().rev() {
        push_message(&mut lines, msg, msg_width);
        lines.push(Line::from(""));
    }
    if lines.is_empty() {
        lines.push(Line::from(Span::styled(
            "no messages yet. type above and hit Enter",
            Style::default()
                .fg(Color::DarkGray)
                .add_modifier(Modifier::ITALIC),
        )));
    }
    let messages_para = Paragraph::new(Text::from(lines.clone()))
        .wrap(Wrap { trim: false })
        .block(Block::default().borders(Borders::NONE));

    let viewport_h = chunks[1].height as usize;
    app.last_viewport_h = viewport_h;
    let total_rows = wrapped_row_count(&lines, chunks[1].width);
    let n_pages = if total_rows == 0 || viewport_h == 0 {
        1
    } else {
        total_rows.div_ceil(viewport_h)
    };
    let page = app.current_page.min(n_pages.saturating_sub(1));
    // Write the clamped page back so navigation can never accumulate
    // phantom pages past the end (issue #6: scrolling past the last page
    // then reversing used to cost the same amount of extra scrolling).
    app.current_page = page;

    // Clamp the scroll offset to the last legal row so the user can't page
    // off into the empty void beyond the oldest line.
    let max_scroll = total_rows.saturating_sub(1);
    let scroll_offset = match app.view_mode {
        ViewMode::Page => page * viewport_h,
        ViewMode::Scroll => {
            // Same clamp-back as above: keep scroll_row inside the legal
            // range so reversing direction never has to eat phantom rows.
            app.scroll_row = app.scroll_row.min(max_scroll);
            app.scroll_row
        }
    };
    let scroll_y = scroll_offset.min(u16::MAX as usize) as u16;

    f.render_widget(messages_para.scroll((scroll_y, 0)), chunks[1]);

    // ---- status bar ----
    let dot = "";
    let is_demo = app.active_shop.protocol == Protocol::Demo;
    let dirty = app.is_dirty();
    let station_label = match (&app.active_origin, dirty) {
        (Some(origin), true) => format!("tuned from {}", origin),
        (Some(origin), false) => origin.clone(),
        (None, _) => app.active_station.name.clone(),
    };
    let station_color = if is_demo {
        Color::Yellow
    } else if dirty {
        Color::Magenta
    } else {
        Color::Cyan
    };
    let mut pieces = vec![
        Span::styled("wryme", Style::default().fg(Color::Cyan)),
        Span::raw(dot),
        Span::styled(
            format!("station: {}", station_label),
            Style::default().fg(station_color),
        ),
        Span::raw(dot),
        Span::raw(app.active_station.model.clone()),
        Span::raw(dot),
        Span::styled(
            format!("via {}", app.active_shop.name),
            Style::default().fg(Color::DarkGray),
        ),
        Span::raw(dot),
        Span::raw(format!("{} msg", app.messages.len())),
    ];
    if !app.messages.is_empty() {
        pieces.push(Span::raw(dot));
        match app.view_mode {
            ViewMode::Page => {
                pieces.push(Span::styled(
                    format!("page {}/{}", page + 1, n_pages),
                    Style::default().fg(if n_pages > 1 {
                        Color::Cyan
                    } else {
                        Color::DarkGray
                    }),
                ));
            }
            ViewMode::Scroll => {
                pieces.push(Span::styled(
                    if scroll_offset == 0 {
                        "scroll (top)".to_string()
                    } else {
                        format!("scroll +{}", scroll_offset)
                    },
                    Style::default().fg(Color::Cyan),
                ));
            }
        }
    }
    pieces.push(Span::raw(dot));
    pieces.push(Span::styled(
        app.status.clone(),
        Style::default().fg(
            if app.status.starts_with("error") || app.status.starts_with("upstream") {
                Color::Red
            } else {
                Color::Gray
            },
        ),
    ));
    let status = Paragraph::new(Line::from(pieces)).style(Style::default().fg(Color::Gray));
    f.render_widget(status, chunks[2]);

    // ---- station popup overlay ----
    if app.popup.mode != popup::Mode::Closed {
        crate::popup_ui::draw(f, app);
    }
}


fn push_message(out: &mut Vec<Line<'static>>, msg: &Message, area_width: u16) {
    let (role_color, role_text) = match msg.role {
        Role::User => (Color::Green, "you"),
        Role::Assistant => (Color::Magenta, "assistant"),
    };

    let mut header: Vec<Span<'static>> = vec![Span::styled(
        role_text.to_string(),
        Style::default()
            .fg(role_color)
            .add_modifier(Modifier::BOLD),
    )];
    if msg.streaming {
        // Hidden tools (the bookkeeper and the phantom async checker) are
        // treated visually, not as tools: the bookkeeper shows a quiet
        // "reminiscing…" and no tool name; the checker is fully invisible.
        // The app phase is still `Tinkering` — this is purely presentation.
        let hidden = msg
            .current_tool
            .as_ref()
            .map(|n| crate::tools::is_hidden_tool(n))
            .unwrap_or(false);
        let bookish = msg
            .current_tool
            .as_ref()
            .map(|n| crate::tools::is_book_tool(n))
            .unwrap_or(false);
        let label = match msg.phase {
            Phase::Writing => Some("  writing…"),
            Phase::Thinking => Some("  thinking…"),
            Phase::Tinkering => {
                if hidden {
                    if bookish {
                        Some("  reminiscing…")
                    } else {
                        None
                    }
                } else {
                    Some("  tinkering…")
                }
            }
            // Initial state. No chunk has arrived yet. Suppress the
            // generic "streaming…" filler; the empty header reads as
            // "waiting" cleanly enough.
            Phase::Streaming => None,
        };
        if let Some(l) = label {
            header.push(Span::styled(
                l.to_string(),
                Style::default().fg(Color::DarkGray),
            ));
        }
    }

    // Build the right side of the header. Tool name (if any, while streaming)
    // sits just to the left of the timestamp with two spaces between them.
    // Hidden tools (bookkeeper / phantom checker) never show a name.
    let tool_span: Option<Span<'static>> = if msg.streaming {
        msg.current_tool
            .as_ref()
            .filter(|name| !crate::tools::is_hidden_tool(name))
            .map(|name| {
                Span::styled(
                    name.clone(),
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                )
            })
    } else {
        None
    };
    let ts_span = Span::styled(
        msg.timestamp.clone(),
        Style::default().fg(Color::DarkGray),
    );

    // Width math. Pad with spaces between the header's left content and the
    // right cluster (tool name + timestamp).
    let left_width: usize = header
        .iter()
        .map(|s| UnicodeWidthStr::width(s.content.as_ref()))
        .sum();
    let tool_width = tool_span
        .as_ref()
        .map(|s| UnicodeWidthStr::width(s.content.as_ref()) + 2)
        .unwrap_or(0);
    let ts_width = UnicodeWidthStr::width(msg.timestamp.as_str());
    let pad = (area_width as usize)
        .saturating_sub(left_width + tool_width + ts_width)
        .max(1);
    header.push(Span::raw(" ".repeat(pad)));
    if let Some(t) = tool_span {
        header.push(t);
        header.push(Span::raw("  "));
    }
    header.push(ts_span);
    out.push(Line::from(header));

    let has_reply = !msg.content.is_empty();
    let has_brain = !msg.brain.is_empty();
    let cursor_in_reply = msg.streaming && has_reply;
    let cursor_in_brain = msg.streaming && !has_reply && has_brain;
    let cursor_orphan = msg.streaming && !has_reply && !has_brain;

    if cursor_orphan {
        out.push(Line::from(Span::styled(
            "",
            Style::default().fg(Color::DarkGray),
        )));
    }

    // Reply (newest in time, sits at the top of this message's block).
    if has_reply {
        match msg.role {
            Role::Assistant => {
                out.extend(crate::md::render(&msg.content, cursor_in_reply));
            }
            Role::User => {
                for img in &msg.images {
                    out.push(Line::from(Span::styled(
                        format!("📷 attached: {img}"),
                        Style::default().fg(Color::DarkGray),
                    )));
                }
                let last_idx = msg.content.split('\n').count().saturating_sub(1);
                for (i, raw) in msg.content.split('\n').enumerate() {
                    if i == last_idx && cursor_in_reply {
                        out.push(Line::from(vec![
                            Span::raw(raw.to_string()),
                            Span::styled("", Style::default().fg(Color::DarkGray)),
                        ]));
                    } else {
                        out.push(Line::from(raw.to_string()));
                    }
                }
            }
        }
    }

    // Brain (older in time, sits beneath the reply as a footnote).
    if has_brain {
        if has_reply {
            out.push(Line::from(""));
        }
        let brain_style = Style::default()
            .fg(Color::DarkGray)
            .add_modifier(Modifier::ITALIC);
        out.push(Line::from(Span::styled(
            "brain",
            brain_style.add_modifier(Modifier::BOLD),
        )));
        let last_idx = msg.brain.split('\n').count().saturating_sub(1);
        for (i, raw) in msg.brain.split('\n').enumerate() {
            if i == last_idx && cursor_in_brain {
                out.push(Line::from(vec![
                    Span::styled(raw.to_string(), brain_style),
                    Span::styled("", Style::default().fg(Color::DarkGray)),
                ]));
            } else {
                out.push(Line::from(Span::styled(raw.to_string(), brain_style)));
            }
        }
    }
}

/// Approximate visual row count after wrapping. Sums each Line's display
/// width and rounds up by area width. Not exact (ratatui's word-boundary
/// wrap may add a row here or there) but close enough to count pages.
fn wrapped_row_count(lines: &[Line<'_>], area_width: u16) -> usize {
    let aw = (area_width as usize).max(1);
    let mut total = 0usize;
    for line in lines {
        let w: usize = line
            .spans
            .iter()
            .map(|s| UnicodeWidthStr::width(s.content.as_ref()))
            .sum();
        total += if w == 0 { 1 } else { w.div_ceil(aw) };
    }
    total
}