i-self 0.4.3

Personal developer-companion CLI: scans your repos, indexes code semantically, watches your activity, and moves AI-agent sessions between tools (Claude Code, Aider, Goose, OpenAI Codex CLI, Continue.dev, OpenCode).
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
//! Render `SharedSession` to a portable format.
//!
//! - `markdown`: human-readable, paste-friendly. Keeps tool calls and thinking
//!   blocks visible so a reader can audit what the agent actually did.
//! - `json`: machine-readable, lossless round-trip via `serde`. Useful for
//!   piping into other tooling.
//!
//! HTML rendering is intentionally omitted. A consumer with the JSON can
//! generate any HTML they want; baking a styled HTML template into this
//! crate would compound versioning surface for marginal value.

use super::{MessageRole, SharedSession};
use anyhow::Result;

#[derive(Debug, Clone, Copy)]
pub enum RenderFormat {
    Markdown,
    Json,
    Html,
}

impl RenderFormat {
    pub fn from_str_lossy(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "json" => RenderFormat::Json,
            "html" => RenderFormat::Html,
            _ => RenderFormat::Markdown,
        }
    }

    pub fn content_type(&self) -> &'static str {
        match self {
            RenderFormat::Markdown => "text/markdown; charset=utf-8",
            RenderFormat::Json => "application/json",
            RenderFormat::Html => "text/html; charset=utf-8",
        }
    }

    pub fn extension(&self) -> &'static str {
        match self {
            RenderFormat::Markdown => "md",
            RenderFormat::Json => "json",
            RenderFormat::Html => "html",
        }
    }
}

pub fn render(session: &SharedSession, format: RenderFormat) -> Result<String> {
    match format {
        RenderFormat::Markdown => Ok(render_markdown(session)),
        RenderFormat::Json => Ok(serde_json::to_string_pretty(session)?),
        RenderFormat::Html => Ok(render_html(session)),
    }
}

fn render_markdown(session: &SharedSession) -> String {
    let mut out = String::new();
    out.push_str(&format!("# {} session — {}\n\n", session.provider, session.id));
    if let Some(p) = &session.project_path {
        out.push_str(&format!("**Project:** `{}`\n\n", p.display()));
    }
    if let Some(t) = session.started_at {
        out.push_str(&format!("**Started:** {}\n\n", t.to_rfc3339()));
    }
    out.push_str(&format!("**Messages:** {}\n\n", session.messages.len()));
    out.push_str("---\n\n");

    for (i, msg) in session.messages.iter().enumerate() {
        let header = match msg.role {
            MessageRole::User => "👤 User".to_string(),
            MessageRole::Assistant => {
                if let Some(model) = msg.metadata.get("model") {
                    format!("🤖 Assistant ({})", model)
                } else {
                    "🤖 Assistant".to_string()
                }
            }
            MessageRole::System => "⚙️ System".to_string(),
            MessageRole::ToolUse => {
                if let Some(name) = msg.metadata.get("tool_name") {
                    format!("🔧 Tool call: `{}`", name)
                } else {
                    "🔧 Tool call".to_string()
                }
            }
            MessageRole::ToolResult => "📤 Tool result".to_string(),
        };

        let timestamp_suffix = msg
            .timestamp
            .map(|t| format!(" *— {}*", t.to_rfc3339()))
            .unwrap_or_default();

        out.push_str(&format!("## {}. {}{}\n\n", i + 1, header, timestamp_suffix));

        // Tool use is most readable as a fenced JSON-ish block; everything
        // else gets blockquoted so embedded markdown in the message renders
        // sensibly. (Code fences inside an assistant reply still render.)
        match msg.role {
            MessageRole::ToolUse => {
                out.push_str("```\n");
                out.push_str(&msg.content);
                out.push_str("\n```\n\n");
            }
            MessageRole::ToolResult => {
                out.push_str("```\n");
                out.push_str(&msg.content);
                out.push_str("\n```\n\n");
            }
            _ => {
                out.push_str(&msg.content);
                if !msg.content.ends_with('\n') {
                    out.push('\n');
                }
                out.push('\n');
            }
        }
    }

    out
}

/// Render a session as a single self-contained HTML file with embedded CSS.
/// No external resources, no JavaScript — opens cleanly from any browser, an
/// email attachment, or a github-pages bucket.
///
/// The renderer escapes HTML in message content (`html_escape`) and parses
/// triple-backtick code fences into `<pre><code>` blocks so syntax-aware
/// browser extensions or pastes into other tools survive intact. Inline
/// styling uses a built-in dark theme that matches the dashboard.
fn render_html(session: &SharedSession) -> String {
    let mut out = String::with_capacity(8 * 1024);
    out.push_str("<!DOCTYPE html>\n<html lang=\"en\" data-theme=\"dark\">\n<head>\n<meta charset=\"utf-8\">\n");
    out.push_str(&format!(
        "<title>{} session — {}</title>\n",
        html_escape(&session.provider),
        html_escape(&session.id)
    ));
    out.push_str("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n");
    out.push_str("<style>\n");
    out.push_str(EMBEDDED_CSS);
    out.push_str("</style>\n</head>\n<body>\n<main>\n");

    out.push_str(&format!(
        "<header class=\"session-meta\">\n<h1>{} session</h1>\n",
        html_escape(&session.provider)
    ));
    out.push_str(&format!(
        "<p class=\"session-id\"><code>{}</code></p>\n",
        html_escape(&session.id)
    ));
    if let Some(p) = &session.project_path {
        out.push_str(&format!(
            "<p><strong>Project:</strong> <code>{}</code></p>\n",
            html_escape(&p.display().to_string())
        ));
    }
    if let Some(t) = session.started_at {
        out.push_str(&format!(
            "<p><strong>Started:</strong> {}</p>\n",
            html_escape(&t.to_rfc3339())
        ));
    }
    out.push_str(&format!(
        "<p><strong>Messages:</strong> {}</p>\n</header>\n",
        session.messages.len()
    ));

    for msg in &session.messages {
        let (role_class, role_label): (&'static str, String) = match msg.role {
            MessageRole::User => ("user", "👤 User".to_string()),
            MessageRole::Assistant => {
                let label = match msg.metadata.get("model") {
                    Some(m) => format!("🤖 Assistant ({})", html_escape(m)),
                    None => "🤖 Assistant".to_string(),
                };
                ("assistant", label)
            }
            MessageRole::System => ("system", "⚙️ System".to_string()),
            MessageRole::ToolUse => {
                let label = match msg.metadata.get("tool_name") {
                    Some(name) => format!("🔧 Tool call: <code>{}</code>", html_escape(name)),
                    None => "🔧 Tool call".to_string(),
                };
                ("tool-use", label)
            }
            MessageRole::ToolResult => ("tool-result", "📤 Tool result".to_string()),
        };

        out.push_str(&format!("<article class=\"msg msg-{}\">\n", role_class));
        out.push_str(&format!("<header><span class=\"role\">{}</span>", role_label));
        if let Some(t) = msg.timestamp {
            out.push_str(&format!(
                " <time datetime=\"{}\">{}</time>",
                html_escape(&t.to_rfc3339()),
                html_escape(&t.to_rfc3339())
            ));
        }
        out.push_str("</header>\n<div class=\"content\">\n");

        // For tool calls/results we always wrap in <pre> for monospaced
        // structure; for natural text we run a small markdown-fence parser
        // to keep code blocks distinguishable.
        match msg.role {
            MessageRole::ToolUse | MessageRole::ToolResult => {
                out.push_str(&format!("<pre><code>{}</code></pre>\n", html_escape(&msg.content)));
            }
            _ => {
                render_text_with_code_fences(&msg.content, &mut out);
            }
        }
        out.push_str("</div>\n</article>\n");
    }

    out.push_str("<footer>Generated by <code>i-self share render --format html</code>. Self-contained — no external assets.</footer>\n</main>\n</body>\n</html>\n");
    out
}

fn html_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            _ => out.push(ch),
        }
    }
    out
}

/// Walk a string and turn ```...``` fenced blocks into <pre><code>; everything
/// else becomes <p>-wrapped, html-escaped, with newlines as <br>. Not a full
/// CommonMark renderer — just enough for transcripts to read sensibly.
fn render_text_with_code_fences(text: &str, out: &mut String) {
    let mut in_fence = false;
    let mut fence_lang: Option<String> = None;
    let mut fence_buf = String::new();
    let mut prose_buf = String::new();

    let flush_prose = |buf: &mut String, out: &mut String| {
        if buf.is_empty() {
            return;
        }
        out.push_str("<p>");
        let escaped = html_escape(buf.trim_end_matches('\n'));
        // Preserve line breaks within a paragraph for chat-style messages.
        out.push_str(&escaped.replace('\n', "<br>\n"));
        out.push_str("</p>\n");
        buf.clear();
    };

    for line in text.split_inclusive('\n') {
        let stripped = line.strip_suffix('\n').unwrap_or(line);
        if !in_fence && stripped.starts_with("```") {
            flush_prose(&mut prose_buf, out);
            in_fence = true;
            let lang = stripped.trim_start_matches('`').trim();
            fence_lang = if lang.is_empty() { None } else { Some(lang.to_string()) };
            continue;
        }
        if in_fence && stripped.trim_end() == "```" {
            in_fence = false;
            let lang_attr = fence_lang
                .as_deref()
                .map(|l| format!(" data-lang=\"{}\"", html_escape(l)))
                .unwrap_or_default();
            out.push_str(&format!(
                "<pre{}><code>{}</code></pre>\n",
                lang_attr,
                html_escape(fence_buf.trim_end_matches('\n'))
            ));
            fence_buf.clear();
            fence_lang = None;
            continue;
        }
        if in_fence {
            fence_buf.push_str(line);
        } else {
            prose_buf.push_str(line);
        }
    }
    if in_fence {
        // Unterminated fence — fall back to dumping it as a code block so we
        // don't lose content.
        out.push_str(&format!(
            "<pre><code>{}</code></pre>\n",
            html_escape(&fence_buf)
        ));
    }
    flush_prose(&mut prose_buf, out);
}

const EMBEDDED_CSS: &str = r#"
:root {
    --bg: #0f1419;
    --bg-soft: #1a2028;
    --fg: #d3d7de;
    --fg-soft: #8a93a3;
    --accent: #7aa2f7;
    --user: #2d3748;
    --assistant: #1e2935;
    --tool: #2a2330;
    --result: #1e2a1e;
    --code-bg: #0a0e13;
    --border: #2c3340;
}
* { box-sizing: border-box; }
body {
    margin: 0;
    background: var(--bg);
    color: var(--fg);
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
    line-height: 1.55;
}
main { max-width: 880px; margin: 2rem auto; padding: 0 1.25rem; }
.session-meta {
    border-bottom: 1px solid var(--border);
    padding-bottom: 1rem;
    margin-bottom: 1.5rem;
}
.session-meta h1 { margin: 0 0 .25rem; font-size: 1.6rem; color: var(--accent); }
.session-meta p { margin: .25rem 0; color: var(--fg-soft); font-size: .92rem; }
.session-id code { background: var(--bg-soft); padding: .15rem .4rem; border-radius: 4px; }
.msg { background: var(--bg-soft); border-left: 3px solid var(--border); margin: 1rem 0; padding: .9rem 1.1rem; border-radius: 6px; }
.msg-user      { border-left-color: var(--accent);  background: var(--user); }
.msg-assistant { border-left-color: #98c379;        background: var(--assistant); }
.msg-tool-use  { border-left-color: #d19a66;        background: var(--tool); }
.msg-tool-result { border-left-color: #56b6c2;      background: var(--result); }
.msg-system    { border-left-color: #c678dd;        background: var(--bg-soft); }
.msg header { font-size: .85rem; color: var(--fg-soft); margin-bottom: .5rem; }
.msg .role { font-weight: 600; color: var(--fg); }
.msg time { margin-left: .5rem; opacity: .7; }
.msg .content p { margin: .4rem 0; }
.msg pre {
    background: var(--code-bg);
    color: #e8eaef;
    padding: .75rem 1rem;
    border-radius: 4px;
    overflow-x: auto;
    margin: .5rem 0;
    font-size: .85rem;
}
.msg code {
    font-family: ui-monospace, SFMono-Regular, "Menlo", monospace;
    font-size: .9em;
}
.msg p code { background: var(--code-bg); padding: .1rem .3rem; border-radius: 3px; }
footer {
    margin: 3rem 0 1rem;
    padding-top: 1rem;
    border-top: 1px solid var(--border);
    color: var(--fg-soft);
    font-size: .82rem;
    text-align: center;
}
"#;

#[cfg(test)]
mod tests {
    use super::*;
    use super::super::{SessionMessage, MessageRole};
    use std::collections::HashMap;

    fn sample() -> SharedSession {
        SharedSession {
            provider: "claude-code".into(),
            id: "test-session".into(),
            project_path: Some(std::path::PathBuf::from("/Users/foo/proj")),
            started_at: Some(chrono::Utc::now()),
            messages: vec![
                SessionMessage {
                    role: MessageRole::User,
                    content: "Refactor auth.rs".into(),
                    timestamp: None,
                    metadata: HashMap::new(),
                },
                SessionMessage {
                    role: MessageRole::Assistant,
                    content: "Sure, here's the plan…".into(),
                    timestamp: None,
                    metadata: HashMap::from([("model".into(), "claude-opus-4-7".into())]),
                },
                SessionMessage {
                    role: MessageRole::ToolUse,
                    content: "Read({\"path\":\"src/auth.rs\"})".into(),
                    timestamp: None,
                    metadata: HashMap::from([("tool_name".into(), "Read".into())]),
                },
            ],
        }
    }

    #[test]
    fn markdown_includes_session_metadata() {
        let s = render_markdown(&sample());
        assert!(s.contains("# claude-code session"));
        assert!(s.contains("test-session"));
        assert!(s.contains("/Users/foo/proj"));
        assert!(s.contains("**Messages:** 3"));
    }

    #[test]
    fn markdown_renders_each_role_distinctly() {
        let s = render_markdown(&sample());
        assert!(s.contains("👤 User"));
        assert!(s.contains("🤖 Assistant (claude-opus-4-7)"));
        assert!(s.contains("🔧 Tool call: `Read`"));
        // Tool calls are inside a code fence
        assert!(s.contains("```\nRead({\"path\":\"src/auth.rs\"})\n```"));
    }

    #[test]
    fn json_round_trips() {
        let session = sample();
        let json = render(&session, RenderFormat::Json).unwrap();
        let back: SharedSession = serde_json::from_str(&json).unwrap();
        assert_eq!(back.id, session.id);
        assert_eq!(back.messages.len(), session.messages.len());
    }

    #[test]
    fn format_lookup_is_case_insensitive() {
        assert!(matches!(RenderFormat::from_str_lossy("JSON"), RenderFormat::Json));
        assert!(matches!(RenderFormat::from_str_lossy("Markdown"), RenderFormat::Markdown));
        assert!(matches!(RenderFormat::from_str_lossy("HTML"), RenderFormat::Html));
        assert!(matches!(RenderFormat::from_str_lossy("???"), RenderFormat::Markdown));
    }

    #[test]
    fn html_render_is_self_contained_and_dark_themed() {
        let s = render(&sample(), RenderFormat::Html).unwrap();
        // Must declare itself HTML5
        assert!(s.starts_with("<!DOCTYPE html>"));
        // CSS is embedded — no external stylesheets
        assert!(s.contains("<style>"));
        assert!(!s.contains("rel=\"stylesheet\""));
        // No external scripts either
        assert!(!s.contains("<script"));
        // Dark theme markers
        assert!(s.contains("data-theme=\"dark\""));
        assert!(s.contains("--bg: #0f1419"));
    }

    #[test]
    fn html_render_renders_each_role_with_distinct_class() {
        let s = render(&sample(), RenderFormat::Html).unwrap();
        assert!(s.contains("msg-user"));
        assert!(s.contains("msg-assistant"));
        assert!(s.contains("msg-tool-use"));
        // Model hint surfaces in the assistant header
        assert!(s.contains("claude-opus-4-7"));
    }

    #[test]
    fn html_escape_handles_dangerous_chars() {
        assert_eq!(
            html_escape("<script>alert('x')</script> & co"),
            "&lt;script&gt;alert(&#39;x&#39;)&lt;/script&gt; &amp; co"
        );
    }

    #[test]
    fn html_render_escapes_user_content() {
        let mut s = sample();
        s.messages[0].content = "<img src=x onerror=alert(1)>".to_string();
        let html = render(&s, RenderFormat::Html).unwrap();
        // The dangerous string should appear escaped, never as a real tag.
        assert!(!html.contains("<img src=x onerror"));
        assert!(html.contains("&lt;img src=x onerror=alert(1)&gt;"));
    }

    #[test]
    fn html_render_promotes_fenced_blocks_to_pre_code() {
        let mut s = sample();
        s.messages[1].content = "Here's the diff:\n\n```rust\nfn main() {}\n```\n\nThat's it.".to_string();
        let html = render(&s, RenderFormat::Html).unwrap();
        // Code fence becomes <pre data-lang="rust"><code>fn main() {}</code></pre>
        assert!(html.contains("data-lang=\"rust\""));
        assert!(html.contains("<pre"));
        assert!(html.contains("fn main() {}"));
        // Surrounding prose stays in <p>
        assert!(html.contains("<p>Here&#39;s the diff:</p>") || html.contains("<p>Here's the diff:</p>"));
    }

    #[test]
    fn html_render_handles_unterminated_fence_without_losing_content() {
        let mut s = sample();
        s.messages[1].content = "Output:\n\n```\nrunning forever".to_string();
        let html = render(&s, RenderFormat::Html).unwrap();
        // Even without a closing ```, the content survives in a <pre> block
        assert!(html.contains("running forever"));
    }
}