feat(cli): add HTML session export with an interactive viewer (#11977)

This commit is contained in:
Salman Mohammed
2026-10-01 19:08:22 +00:00
committed by GitHub
parent bab8ff6410
commit 9012eac3b5
9 changed files with 2502 additions and 3 deletions
+1 -1
View File
@@ -571,7 +571,7 @@ enum SessionCommand {
#[arg(
long = "format",
value_name = "FORMAT",
help = "Output format (markdown, json, yaml)",
help = "Output format (markdown, json, yaml, html)",
default_value = "markdown"
)]
format: String,
+4 -2
View File
@@ -3,8 +3,8 @@ use anyhow::{Context, Result};
use cliclack::{confirm, multiselect, select};
use etcetera::home_dir;
use goose::session::{
export_session_to_markdown, generate_diagnostics, DiagnosticsLevel, Session, SessionManager,
SessionType,
export_session_to_html, export_session_to_markdown, generate_diagnostics, DiagnosticsLevel,
Session, SessionManager, SessionType,
};
use goose::utils::safe_truncate;
use regex::Regex;
@@ -313,9 +313,11 @@ pub async fn handle_session_export(
"markdown" => {
let conversation = session
.conversation
.clone()
.ok_or_else(|| anyhow::anyhow!("Session has no messages"))?;
export_session_to_markdown(conversation.user_visible_messages(), &session.name)
}
"html" => export_session_to_html(&session)?,
_ => return Err(anyhow::anyhow!("Unsupported format: {}", format)),
};
@@ -0,0 +1,90 @@
use base64::{engine::general_purpose::STANDARD, Engine};
use crate::session::session_manager::Session;
const TEMPLATE_HTML: &str = include_str!("template.html");
const TEMPLATE_CSS: &str = include_str!("template.css");
const TEMPLATE_JS: &str = include_str!("template.js");
const MARKED_JS: &str = include_str!("vendor/marked.min.js");
const HIGHLIGHT_JS: &str = include_str!("vendor/highlight.min.js");
/// Render a session to a self-contained HTML file.
///
/// The session is serialized to JSON, base64-encoded, and embedded in the
/// template. Rendering happens client-side in the browser using the bundled
/// `template.js`, `marked` (markdown), and `highlight.js` (syntax highlighting).
pub fn export_session_to_html(session: &Session) -> anyhow::Result<String> {
let session_json = serde_json::to_string(session)?;
let session_base64 = STANDARD.encode(session_json.as_bytes());
let html = TEMPLATE_HTML
.replace("{{CSS}}", TEMPLATE_CSS)
.replace("{{MARKED_JS}}", MARKED_JS)
.replace("{{HIGHLIGHT_JS}}", HIGHLIGHT_JS)
.replace("{{JS}}", TEMPLATE_JS)
.replace("{{SESSION_DATA}}", &session_base64);
Ok(html)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::conversation::message::Message;
use crate::conversation::Conversation;
use crate::session::session_manager::SessionType;
use base64::Engine;
use chrono::Utc;
use std::path::PathBuf;
fn sample_session() -> Session {
let conversation = Conversation::new_unvalidated(vec![
Message::user().with_text("hello"),
Message::assistant().with_text("hi there"),
]);
Session {
id: "20260910_1".to_string(),
working_dir: PathBuf::from("/tmp/proj"),
name: "Greeting".to_string(),
user_set_name: false,
session_type: SessionType::User,
created_at: Utc::now(),
updated_at: Utc::now(),
extension_data: Default::default(),
usage: Default::default(),
accumulated_usage: Default::default(),
accumulated_cost: Some(0.01),
schedule_id: None,
recipe: None,
user_recipe_values: None,
conversation: Some(conversation),
message_count: 2,
last_message_at: None,
provider_name: Some("databricks".to_string()),
model_config: None,
goose_mode: Default::default(),
archived_at: None,
project_id: None,
parent_session_id: None,
last_message_snippet: None,
}
}
#[test]
fn embeds_session_json_as_base64() {
let session = sample_session();
let html = export_session_to_html(&session).unwrap();
assert!(html.contains("<script id=\"session-data\""));
assert!(!html.contains("{{SESSION_DATA}}"));
assert!(!html.contains("{{CSS}}"));
assert!(!html.contains("{{JS}}"));
let (_, session_data) = html.split_once("application/json\">").unwrap();
let (session_base64, _) = session_data.split_once("</script>").unwrap();
let decoded = STANDARD.decode(session_base64).unwrap();
let value: serde_json::Value = serde_json::from_slice(&decoded).unwrap();
assert_eq!(value["id"], "20260910_1");
assert_eq!(value["conversation"].as_array().unwrap().len(), 2);
}
}
@@ -0,0 +1,446 @@
:root {
/* Slate-ink base with a single warm amber signature (goose). */
--bg: #14161b;
--panel: #1b1e26;
--panel-inset: #191c23;
--rule: #2a2e38;
--text: #e6e7ea;
--muted: #8b8f9a;
--dim: #676b76;
--signature: #e8a33d;
--signature-quiet: #b98536;
--ok: #5fa568;
--err: #d16b6b;
--run: #8b8f9a;
--link: #86a9e0;
/* Syntax: lower-chroma hues tuned to the slate base. */
--syn-comment: #676b76;
--syn-keyword: #c58fd8;
--syn-number: #e0a458;
--syn-string: #8fbf7f;
--syn-function: #86a9e0;
--syn-type: #6fc2c9;
--syn-variable: #d88f8f;
--syn-operator: #9fb4d0;
--syn-punct: #8b8f9a;
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--mono: ui-monospace, "SF Mono", "Cascadia Code", "Source Code Pro", Menlo, Consolas, "DejaVu Sans Mono", monospace;
--measure: 76ch;
--gap: 12px;
--toc-width: 260px;
}
html { scroll-behavior: smooth; }
* { margin: 0; padding: 0; box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body {
font-family: var(--sans);
font-size: 13.5px;
line-height: 1.5;
color: var(--text);
background: var(--bg);
-webkit-font-smoothing: antialiased;
}
::selection { background: rgba(232, 163, 61, 0.28); }
#app { display: flex; align-items: flex-start; }
/* ---- Table of contents ---- */
#toc {
flex: 0 0 var(--toc-width);
width: var(--toc-width);
position: sticky;
top: 0;
height: 100vh;
overflow-y: auto;
border-right: 1px solid var(--rule);
padding: 24px 0;
}
.toc-head {
font-family: var(--mono);
font-size: 12px;
color: var(--dim);
padding: 0 20px 12px;
}
#toc-list { display: flex; flex-direction: column; }
.toc-item {
display: flex;
align-items: baseline;
gap: 8px;
padding: 5px 20px 5px 18px;
border-left: 2px solid transparent;
font-family: var(--mono);
font-size: 12px;
line-height: 1.35;
color: var(--muted);
text-decoration: none;
cursor: pointer;
}
.toc-item:hover { background: var(--panel); color: var(--text); }
.toc-item.active { border-left-color: var(--signature); background: var(--panel); }
.toc-item.active .toc-text { color: var(--text); }
.toc-item.internal { opacity: 0.5; }
.toc-role { flex: 0 0 auto; color: var(--dim); }
.toc-item.user .toc-role { color: var(--signature-quiet); }
.toc-text {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--muted);
}
#toc-toggle, #toc-overlay { display: none; }
#content {
flex: 1 1 auto;
min-width: 0;
max-width: 860px;
margin: 0 auto;
padding: 32px 28px 80px;
}
/* ---- Header (hero) ---- */
.header { margin-bottom: 24px; }
.header h1 {
font-size: 24px;
line-height: 1.15;
font-weight: 600;
letter-spacing: -0.015em;
color: var(--text);
}
.header .header-dir {
font-family: var(--mono);
font-size: 12px;
color: var(--muted);
margin-top: 6px;
word-break: break-all;
}
.header-info {
display: grid;
grid-template-columns: max-content 1fr;
column-gap: 16px;
row-gap: 2px;
margin-top: 16px;
padding-top: 14px;
border-top: 1px solid var(--rule);
font-size: 12px;
}
.info-label { color: var(--dim); }
.info-value { color: var(--text); font-family: var(--mono); word-break: break-word; }
.header-actions { margin-top: 24px; }
.toggle-btn {
font: inherit;
font-size: 13px;
color: var(--muted);
background: none;
border: none;
border-bottom: 1px dashed var(--rule);
padding: 0 0 1px;
cursor: pointer;
}
.toggle-btn:hover { color: var(--signature); border-bottom-color: var(--signature-quiet); }
/* ---- Turns ---- */
#messages { display: flex; flex-direction: column; gap: var(--gap); }
.role-label {
font-family: var(--mono);
font-size: 11px;
color: var(--muted);
margin-bottom: 3px;
}
.role-label.user { color: var(--signature); }
.message-timestamp {
font-family: var(--mono);
font-size: 11px;
color: var(--dim);
margin-bottom: 5px;
}
/* User: raised panel marked with an amber input rule. */
.user-message {
background: var(--panel);
border-left: 2px solid var(--signature);
border-radius: 0 6px 6px 0;
padding: 10px 14px;
}
.user-message.internal { opacity: 0.55; border-left-style: dashed; }
/* Assistant: open prose, no chrome. */
.assistant-message { padding: 0 2px; }
.markdown-content > *:first-child { margin-top: 0; }
/* ---- Thinking ---- */
.thinking-block {
font-family: var(--mono);
font-size: 12px;
color: var(--dim);
cursor: pointer;
padding: 1px 0;
}
.thinking-label { color: var(--signature-quiet); }
.thinking-collapsed { font-style: italic; }
.thinking-content {
display: none;
font-style: italic;
white-space: pre-wrap;
margin-top: 6px;
line-height: 1.5;
}
.thinking-block.expanded .thinking-collapsed { display: none; }
.thinking-block.expanded .thinking-content { display: block; }
/* ---- Tool execution: a status-gutter log line ---- */
.tool-execution {
font-family: var(--mono);
font-size: 12px;
line-height: 1.45;
background: var(--panel-inset);
border-left: 3px solid var(--run);
padding: 8px 12px;
margin-top: 8px;
}
.tool-execution.success { border-left-color: var(--ok); }
.tool-execution.error { border-left-color: var(--err); }
.assistant-message .tool-execution:first-child { margin-top: 0; }
.tool-header { color: var(--muted); }
.tool-ns { color: var(--dim); }
.tool-name { color: var(--text); font-weight: 600; }
.tool-path { color: var(--signature-quiet); word-break: break-all; }
.tool-count { color: var(--dim); }
.tool-command {
color: var(--text);
white-space: pre-wrap;
word-break: break-word;
margin-top: 4px;
}
.tool-command.shell::before { content: "$ "; color: var(--signature); }
.tool-args {
color: var(--muted);
white-space: pre-wrap;
word-break: break-word;
margin-top: 4px;
}
/* Code body of write / read output */
pre.code {
margin: 6px 0 0;
white-space: pre-wrap;
word-break: break-word;
overflow-x: auto;
line-height: 1.45;
}
pre.code code { padding: 0; background: none; color: var(--text); }
.tool-output {
color: var(--muted);
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid var(--rule);
}
.tool-output pre.code { margin-top: 0; }
.tool-output code { color: var(--muted); }
/* Collapsed content with a "show more" button */
.collapsible .col-full { display: none; }
.collapsible.expanded .col-preview { display: none; }
.collapsible.expanded .col-full { display: block; }
.show-more {
font: inherit;
font-family: var(--mono);
font-size: 11px;
color: var(--signature-quiet);
background: none;
border: none;
padding: 4px 0 0;
margin: 0;
cursor: pointer;
}
.show-more:hover { color: var(--signature); text-decoration: underline; }
.tool-error {
color: var(--err);
white-space: pre-wrap;
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid var(--rule);
}
.tool-image { max-width: 100%; max-height: 500px; border-radius: 4px; margin: 8px 0 0; }
/* ---- Diff ---- */
.tool-diff { font-family: var(--mono); font-size: 12px; overflow-x: auto; white-space: pre-wrap; word-break: break-word; margin-top: 6px; }
.tool-diff > div { padding: 0 4px; }
.diff-add { color: var(--ok); background: rgba(95, 165, 104, 0.08); }
.diff-del { color: var(--err); background: rgba(209, 107, 107, 0.08); }
.diff-ctx { color: var(--dim); }
/* ---- Misc content ---- */
.error-text { color: var(--err); white-space: pre-wrap; padding: 0 2px; }
.system-notification { font-family: var(--mono); font-size: 12px; color: var(--dim); font-style: italic; padding: 0 2px; }
.message-image { max-width: 100%; max-height: 400px; border-radius: 4px; margin: 8px 0 0; }
.document-block { font-family: var(--mono); font-size: 13px; color: var(--muted); padding: 0 2px; }
/* ---- Markdown (dialogue prose) ---- */
.markdown-content { max-width: var(--measure); }
.markdown-content h1, .markdown-content h2, .markdown-content h3,
.markdown-content h4, .markdown-content h5, .markdown-content h6 {
color: var(--text);
font-weight: 600;
line-height: 1.3;
margin: 1em 0 0.3em;
}
.markdown-content h1 { font-size: 1.3em; }
.markdown-content h2 { font-size: 1.15em; }
.markdown-content h3 { font-size: 1.05em; }
.markdown-content h4, .markdown-content h5, .markdown-content h6 { font-size: 1em; }
.markdown-content p { margin: 0; }
.markdown-content p + p { margin-top: 0.55em; }
.markdown-content a { color: var(--link); text-decoration: none; border-bottom: 1px solid rgba(134, 169, 224, 0.4); }
.markdown-content a:hover { border-bottom-color: var(--link); }
.markdown-content code {
font-family: var(--mono);
font-size: 0.88em;
background: var(--panel);
color: var(--signature);
padding: 1px 5px;
border-radius: 3px;
}
.markdown-content pre {
font-family: var(--mono);
background: var(--panel-inset);
border: 1px solid var(--rule);
border-radius: 6px;
padding: 10px 13px;
margin: 0.6em 0;
overflow-x: auto;
line-height: 1.45;
}
.markdown-content pre code {
font-size: 13px;
background: none;
color: var(--text);
padding: 0;
border-radius: 0;
}
.markdown-content blockquote {
border-left: 2px solid var(--rule);
padding-left: 16px;
margin: 0.9em 0;
color: var(--muted);
}
.markdown-content ul, .markdown-content ol { margin: 0.4em 0; padding-left: 1.5em; }
.markdown-content li { margin: 0.1em 0; }
.markdown-content li::marker { color: var(--dim); }
.markdown-content hr { border: none; border-top: 1px solid var(--rule); margin: 1.4em 0; }
.markdown-content table { border-collapse: collapse; margin: 0.9em 0; width: 100%; font-size: 0.95em; }
.markdown-content th, .markdown-content td { border: 1px solid var(--rule); padding: 7px 11px; text-align: left; }
.markdown-content th { background: var(--panel); font-weight: 600; }
.markdown-content img { max-width: 100%; border-radius: 4px; }
/* ---- Syntax highlighting ---- */
.hljs { background: transparent; color: var(--text); }
.hljs-comment, .hljs-quote { color: var(--syn-comment); font-style: italic; }
.hljs-keyword, .hljs-selector-tag { color: var(--syn-keyword); }
.hljs-number, .hljs-literal { color: var(--syn-number); }
.hljs-string, .hljs-doctag { color: var(--syn-string); }
.hljs-function, .hljs-title, .hljs-title.function_, .hljs-section, .hljs-name { color: var(--syn-function); }
.hljs-type, .hljs-class, .hljs-title.class_, .hljs-built_in { color: var(--syn-type); }
.hljs-attr, .hljs-variable, .hljs-variable.language_, .hljs-params, .hljs-property { color: var(--syn-variable); }
.hljs-meta, .hljs-meta .hljs-keyword, .hljs-meta .hljs-string { color: var(--syn-keyword); }
.hljs-operator { color: var(--syn-operator); }
.hljs-punctuation { color: var(--syn-punct); }
.hljs-subst { color: var(--text); }
/* ---- Footer ---- */
.footer {
margin-top: 64px;
padding-top: 20px;
border-top: 1px solid var(--rule);
font-family: var(--mono);
font-size: 12px;
color: var(--dim);
}
.empty-state { color: var(--muted); font-style: italic; }
@media (max-width: 900px) {
#toc {
position: fixed;
top: 0;
left: 0;
z-index: 30;
width: min(var(--toc-width), 82vw);
flex-basis: auto;
background: var(--bg);
transform: translateX(-100%);
transition: transform 0.2s ease;
}
#toc.open { transform: translateX(0); }
#toc-overlay {
display: block;
position: fixed;
inset: 0;
z-index: 20;
background: rgba(0, 0, 0, 0.5);
opacity: 0;
pointer-events: none;
transition: opacity 0.2s ease;
}
#toc-overlay.open { opacity: 1; pointer-events: auto; }
#toc-toggle {
display: block;
position: fixed;
top: 12px;
left: 12px;
z-index: 40;
font: inherit;
font-family: var(--mono);
font-size: 12px;
color: var(--text);
background: var(--panel);
border: 1px solid var(--rule);
border-radius: 6px;
padding: 6px 12px;
cursor: pointer;
}
#content { padding: 56px 20px 64px; }
}
@media (max-width: 640px) {
body { font-size: 14px; }
.header h1 { font-size: 24px; }
}
@media (prefers-reduced-motion: reduce) {
html { scroll-behavior: auto; }
* { transition: none !important; animation: none !important; }
}
@media print {
body { background: #fff; color: #111; }
#toc, #toc-toggle, #toc-overlay, .toggle-btn, .header-actions { display: none; }
#content { max-width: none; }
.tool-execution, .user-message, .markdown-content pre { background: #f6f6f4; }
}
@@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Goose Session Export</title>
<style>
{{CSS}}
</style>
</head>
<body>
<button id="toc-toggle" aria-label="Toggle contents" aria-expanded="false">Contents</button>
<div id="toc-overlay"></div>
<div id="app">
<aside id="toc" aria-label="Session contents">
<div class="toc-head">Contents</div>
<nav id="toc-list"></nav>
</aside>
<main id="content">
<div id="header-container"></div>
<div id="messages"></div>
<div class="footer">Exported from goose</div>
</main>
</div>
<script id="session-data" type="application/json">{{SESSION_DATA}}</script>
<!-- Vendored libraries -->
<script>{{MARKED_JS}}</script>
<script>{{HIGHLIGHT_JS}}</script>
<!-- Main application code -->
<script>
{{JS}}
</script>
</body>
</html>
@@ -0,0 +1,631 @@
(function () {
'use strict';
// ============================================================
// DATA LOADING
// ============================================================
const base64 = document.getElementById('session-data').textContent;
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
const session = JSON.parse(new TextDecoder('utf-8').decode(bytes));
const allMessages = Array.isArray(session.conversation) ? session.conversation : [];
let showInternal = false;
// ============================================================
// HELPERS
// ============================================================
function escapeHtml(text) {
if (text == null) return '';
return String(text)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
function sanitizeUrl(url) {
if (!url) return null;
const cleaned = String(url).replace(/[\u0000-\u001f]/g, '').trim();
if (/^(https?:|mailto:|#|\/|\.)/i.test(cleaned)) return cleaned;
if (/^[^:]+$/.test(cleaned)) return cleaned;
return null;
}
const MILLISECOND_TIMESTAMP_THRESHOLD = 10000000000;
function formatTimestamp(timestamp) {
if (!timestamp) return '';
const unixSeconds = timestamp > MILLISECOND_TIMESTAMP_THRESHOLD ? timestamp / 1000 : timestamp;
const d = new Date(unixSeconds * 1000);
if (isNaN(d.getTime())) return '';
return d.toLocaleString();
}
function shortenPath(p) {
if (!p) return '';
const cwd = session.working_dir;
if (cwd && p.startsWith(cwd)) {
const rest = p.slice(cwd.length).replace(/^\//, '');
return rest || p;
}
return p;
}
function isUserAudience(block) {
const audience = block && block.annotations && block.annotations.audience;
return !Array.isArray(audience) || audience.includes('user');
}
function userVisibleContentBlock(block) {
if (!block || typeof block !== 'object') return null;
if ((block.type === 'text' || block.type === 'image') && !isUserAudience(block)) return null;
if (block.type !== 'toolResponse') return block;
const result = block.toolResult;
const value = result && result.status === 'success' && result.value;
if (!value || !Array.isArray(value.content)) return block;
return {
...block,
toolResult: {
...result,
value: { ...value, content: value.content.filter(isUserAudience) },
},
};
}
function userVisibleMessage(msg) {
const content = Array.isArray(msg.content)
? msg.content.map(userVisibleContentBlock).filter((block) => block)
: [];
return { ...msg, content };
}
function hasAssistantOnlyContent(block) {
if (!block || typeof block !== 'object') return false;
if ((block.type === 'text' || block.type === 'image') && !isUserAudience(block)) return true;
if (block.type !== 'toolResponse') return false;
const result = block.toolResult;
const value = result && result.status === 'success' && result.value;
return !!(value && Array.isArray(value.content) && value.content.some((item) => !isUserAudience(item)));
}
// ============================================================
// MARKDOWN
// ============================================================
marked.use({
breaks: true,
gfm: true,
tokenizer: {
html() { return undefined; },
tag() { return undefined; }
},
renderer: {
link(token) {
const href = sanitizeUrl(token.href);
if (href === null) return this.parser.parseInline(token.tokens);
let out = '<a href="' + escapeHtml(href) + '"';
if (token.title) out += ' title="' + escapeHtml(token.title) + '"';
out += '>' + this.parser.parseInline(token.tokens) + '</a>';
return out;
},
image(token) {
const href = sanitizeUrl(token.href);
if (href === null) return escapeHtml(token.text || '');
let out = '<img src="' + escapeHtml(href) + '" alt="' + escapeHtml(token.text || '') + '"';
if (token.title) out += ' title="' + escapeHtml(token.title) + '"';
out += '>';
return out;
},
code(token) {
const code = token.text;
const lang = token.lang;
let highlighted;
if (lang && hljs.getLanguage(lang)) {
try { highlighted = hljs.highlight(code, { language: lang }).value; }
catch { highlighted = escapeHtml(code); }
} else {
try { highlighted = hljs.highlightAuto(code).value; }
catch { highlighted = escapeHtml(code); }
}
return '<pre><code class="hljs">' + highlighted + '</code></pre>';
},
codespan(token) {
return '<code>' + escapeHtml(token.text) + '</code>';
}
}
});
function renderMarkdown(text) {
try { return marked.parse(text || ''); }
catch { return escapeHtml(text || ''); }
}
// ============================================================
// TOOL RENDERING
// ============================================================
// Split "extension__tool" into { namespace, tool }, mirroring goose's own
// tool-name convention (see ToolNameParts / markdown export).
function toolNameParts(name) {
if (!name) return { namespace: null, tool: 'tool' };
const idx = name.indexOf('__');
if (idx >= 0) {
return { namespace: name.slice(0, idx), tool: name.slice(idx + 2) };
}
if (name === 'shell' || name === 'write' || name === 'edit') {
return { namespace: 'developer', tool: name };
}
return { namespace: null, tool: name };
}
function firstString(args, keys) {
if (!args || typeof args !== 'object') return null;
for (const k of keys) {
if (typeof args[k] === 'string' && args[k].length) return args[k];
}
return null;
}
const LANG_BY_EXT = {
rs: 'rust', js: 'javascript', mjs: 'javascript', ts: 'typescript', tsx: 'typescript',
jsx: 'javascript', py: 'python', go: 'go', rb: 'ruby', java: 'java', c: 'c', h: 'c',
cpp: 'cpp', cc: 'cpp', hpp: 'cpp', cs: 'csharp', php: 'php', swift: 'swift', kt: 'kotlin',
sh: 'bash', bash: 'bash', zsh: 'bash', json: 'json', yaml: 'yaml', yml: 'yaml', toml: 'ini',
ini: 'ini', xml: 'xml', html: 'xml', css: 'css', scss: 'scss', sql: 'sql', md: 'markdown',
};
function langFromPath(path) {
if (!path) return null;
const ext = path.split('.').pop().toLowerCase();
return LANG_BY_EXT[ext] || null;
}
function highlight(text, lang) {
if (lang && hljs.getLanguage(lang)) {
try { return hljs.highlight(text, { language: lang }).value; } catch {}
}
return escapeHtml(text);
}
// Render the header line for a tool call based on its name/arguments.
// Namespace is shown path-style (developer/shell) to encode the real
// extension -> tool hierarchy.
function renderToolHeader(name, args) {
const parts = toolNameParts(name);
const command = firstString(args, ['command', 'cmd']);
const path = firstString(args, ['path', 'file_path', 'filePath', 'file']);
const isShell = parts.tool === 'shell';
// Tools whose `content` arg is a full file/document body (shown like write).
const showsContent = (parts.tool === 'write' || parts.tool === 'todo_write') &&
args && typeof args.content === 'string';
const ns = parts.namespace ? '<span class="tool-ns">' + escapeHtml(parts.namespace) + '/</span>' : '';
let html = '<div class="tool-header">' + ns + '<span class="tool-name">' + escapeHtml(parts.tool) + '</span>';
if (path) html += ' <span class="tool-path">' + escapeHtml(shortenPath(path)) + '</span>';
if (showsContent) {
const n = args.content.split('\n').length;
html += ' <span class="tool-count">(' + n + (n === 1 ? ' line' : ' lines') + ')</span>';
}
html += '</div>';
if (showsContent) {
html += collapsibleCode(args.content, langFromPath(path));
} else if (parts.tool === 'edit' && args && typeof args.before === 'string' && typeof args.after === 'string') {
html += renderDiff(args.before, args.after);
} else if (command) {
html += '<div class="tool-command' + (isShell ? ' shell' : '') + '">' + escapeHtml(command) + '</div>';
} else if (args && typeof args === 'object' && Object.keys(args).length && !path) {
html += '<div class="tool-args">' + escapeHtml(JSON.stringify(args, null, 2)) + '</div>';
}
return html;
}
// Render an rmcp content block array (tool result payload) to HTML.
function renderResultContent(content, outputClass = 'tool-output') {
if (!Array.isArray(content)) return '';
let html = '';
let textParts = [];
for (const block of content) {
if (!block || typeof block !== 'object') continue;
if (block.type === 'text') {
textParts.push(block.text || '');
} else if (block.type === 'image') {
html += '<img class="tool-image" src="data:' + escapeHtml(block.mimeType || 'image/png') +
';base64,' + escapeHtml(block.data || '') + '" />';
} else if (block.type === 'resource' && block.resource) {
if (typeof block.resource.text === 'string') textParts.push(block.resource.text);
}
}
const text = textParts.join('\n').replace(/\n+$/, '');
if (text) {
html = '<div class="' + outputClass + '">' + collapsibleCode(text, null) + '</div>' + html;
}
return html;
}
const PREVIEW_LINES = 12;
// A syntax-highlighted code block, collapsed to PREVIEW_LINES with a
// "show N more lines" toggle when longer.
function collapsibleCode(text, lang) {
const fullHtml = highlight(text, lang);
const lines = text.split('\n');
if (lines.length <= PREVIEW_LINES) {
return '<pre class="code"><code class="hljs">' + fullHtml + '</code></pre>';
}
const more = lines.length - PREVIEW_LINES;
const label = 'show ' + more + ' more lines';
const previewHtml = highlight(lines.slice(0, PREVIEW_LINES).join('\n'), lang);
return '<div class="collapsible">' +
'<pre class="code col-preview"><code class="hljs">' + previewHtml + '</code></pre>' +
'<pre class="code col-full"><code class="hljs">' + fullHtml + '</code></pre>' +
'<button class="show-more" data-label="' + escapeHtml(label) + '">' + escapeHtml(label) + '</button>' +
'</div>';
}
// Compact line diff: trim common head/tail, show the changed middle as
// removed/added lines with a little surrounding context.
function renderDiff(before, after) {
const a = before.split('\n');
const b = after.split('\n');
let head = 0;
while (head < a.length && head < b.length && a[head] === b[head]) head++;
let tail = 0;
while (tail < a.length - head && tail < b.length - head &&
a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail++;
const ctx = 2;
const rows = [];
for (let i = Math.max(0, head - ctx); i < head; i++) rows.push(['ctx', a[i]]);
for (let i = head; i < a.length - tail; i++) rows.push(['del', a[i]]);
for (let i = head; i < b.length - tail; i++) rows.push(['add', b[i]]);
const tailStart = a.length - tail;
for (let i = tailStart; i < Math.min(a.length, tailStart + ctx); i++) rows.push(['ctx', a[i]]);
const line = ([kind, text]) => {
const mark = kind === 'del' ? '-' : kind === 'add' ? '+' : ' ';
return '<div class="diff-' + kind + '">' + escapeHtml(mark + ' ' + (text || '')) + '</div>';
};
if (rows.length <= PREVIEW_LINES) {
return '<div class="tool-diff">' + rows.map(line).join('') + '</div>';
}
const more = rows.length - PREVIEW_LINES;
const label = 'show ' + more + ' more lines';
return '<div class="collapsible">' +
'<div class="tool-diff col-preview">' + rows.slice(0, PREVIEW_LINES).map(line).join('') + '</div>' +
'<div class="tool-diff col-full">' + rows.map(line).join('') + '</div>' +
'<button class="show-more" data-label="' + escapeHtml(label) + '">' + escapeHtml(label) + '</button>' +
'</div>';
}
function renderToolResult(response) {
const result = response.toolResult;
if (!result) return '';
if (result.status === 'error') {
return '<div class="tool-error">' + escapeHtml(result.error || 'Error') + '</div>';
}
const value = result.value || {};
const content = value.content || value;
return renderResultContent(content, value.isError === true ? 'tool-error' : 'tool-output');
}
function toolResultIsError(result) {
return !!(result && (result.status === 'error' ||
(result.value && result.value.isError === true)));
}
// ============================================================
// MESSAGE RENDERING
// ============================================================
// Collect all tool responses keyed by tool call id.
let responsesById = new Map();
function collectToolResponses(messages) {
const responses = new Map();
for (const msg of messages) {
if (!Array.isArray(msg.content)) continue;
for (const block of msg.content) {
if (block && block.type === 'toolResponse' && block.id) {
responses.set(block.id, block);
}
}
}
return responses;
}
function isInternal(msg) {
return msg.metadata && msg.metadata.userVisible === false;
}
// A message is skippable when it only carries tool responses (rendered inline
// with their originating tool request).
function isOnlyToolResponses(msg) {
if (!Array.isArray(msg.content) || msg.content.length === 0) return false;
return msg.content.every((b) => b && b.type === 'toolResponse');
}
function renderContentBlock(block) {
switch (block.type) {
case 'text':
return '<div class="markdown-content">' + renderMarkdown(block.text) + '</div>';
case 'thinking': {
const text = block.thinking || '';
const firstLine = text.split('\n')[0].slice(0, 120);
return '<div class="thinking-block" onclick="this.classList.toggle(\'expanded\')">' +
'<span class="thinking-label">thinking</span> ' +
'<span class="thinking-collapsed">' + escapeHtml(firstLine) + '…</span>' +
'<div class="thinking-content">' + escapeHtml(text) + '</div></div>';
}
case 'redactedThinking':
return '<div class="thinking-block"><span class="thinking-label">thinking</span> ' +
'<span class="thinking-collapsed">[redacted]</span></div>';
case 'toolRequest': {
const call = block.toolCall || {};
let status = 'pending';
let inner = '';
if (call.status === 'error') {
status = 'error';
inner = '<div class="tool-header"><span class="tool-name">tool</span></div>' +
'<div class="tool-error">' + escapeHtml(call.error || 'Error') + '</div>';
} else {
const value = call.value || {};
const tool = toolNameParts(value.name).tool;
inner = renderToolHeader(value.name, value.arguments);
const response = responsesById.get(block.id);
if (response) {
const result = response.toolResult;
status = toolResultIsError(result) ? 'error' : 'success';
// write/edit/todo_write already show their content/diff; the
// success confirmation text is redundant, so suppress it.
const suppress = status === 'success' &&
(tool === 'write' || tool === 'edit' || tool === 'todo_write');
if (!suppress) inner += renderToolResult(response);
}
}
return '<div class="tool-execution ' + status + '">' + inner + '</div>';
}
case 'toolResponse':
return '';
case 'image':
return '<img class="message-image" src="data:' + escapeHtml(block.mimeType || 'image/png') +
';base64,' + escapeHtml(block.data || '') + '" />';
case 'document':
return '<div class="document-block">[Document: ' +
escapeHtml(block.name || block.mimeType || 'attachment') + ']</div>';
case 'error':
return '<div class="error-text">' + escapeHtml(block.message || 'Error') + '</div>';
case 'systemNotification':
return '<div class="system-notification">' + escapeHtml(block.msg || '') + '</div>';
default:
return '';
}
}
function renderMessage(msg, id) {
const blocks = Array.isArray(msg.content) ? msg.content : [];
const bodyParts = blocks.map(renderContentBlock).filter((h) => h);
if (bodyParts.length === 0) return '';
const role = msg.role === 'user' ? 'user' : 'assistant';
const internalClass = isInternal(msg) ? ' internal' : '';
const timestamp = formatTimestamp(msg.created);
const tsHtml = timestamp ? '<div class="message-timestamp">' + escapeHtml(timestamp) + '</div>' : '';
if (role === 'user') {
return '<div class="user-message' + internalClass + '" id="' + id + '">' +
'<div class="role-label user">you</div>' + tsHtml + bodyParts.join('') + '</div>';
}
return '<div class="assistant-message" id="' + id + '">' +
'<div class="role-label assistant">goose</div>' + tsHtml +
bodyParts.join('') + '</div>';
}
// Condensed one-line summary of a message for the table of contents.
function tocLabel(msg) {
const blocks = Array.isArray(msg.content) ? msg.content : [];
const text = blocks.find((b) => b && b.type === 'text' && (b.text || '').trim());
if (text) return text.text.trim().split('\n').find((l) => l.trim()) || '';
const call = blocks.find((b) => b && b.type === 'toolRequest');
if (call) {
const value = (call.toolCall && call.toolCall.value) || {};
const parts = toolNameParts(value.name);
const detail = firstString(value.arguments, ['command', 'cmd', 'path', 'file_path', 'filePath', 'file']);
return detail ? parts.tool + ': ' + shortenPath(detail) : parts.tool;
}
if (blocks.some((b) => b && (b.type === 'thinking' || b.type === 'redactedThinking'))) return 'thinking';
if (blocks.some((b) => b && b.type === 'image')) return 'image';
if (blocks.some((b) => b && b.type === 'error')) return 'error';
return blocks.length ? blocks[0].type : '';
}
function truncate(text, max) {
if (text.length <= max) return text;
return text.slice(0, max - 1).trimEnd() + '\u2026';
}
function renderToc(entries) {
const list = document.getElementById('toc-list');
if (entries.length === 0) {
list.innerHTML = '';
return;
}
list.innerHTML = entries
.map((e) => {
const role = e.role === 'user' ? 'user' : 'assistant';
return '<a class="toc-item ' + role + (e.internal ? ' internal' : '') +
'" href="#' + e.id + '" data-target="' + e.id + '">' +
'<span class="toc-role">' + (role === 'user' ? 'you' : 'goose') + '</span>' +
'<span class="toc-text">' + escapeHtml(truncate(e.label, 52)) + '</span></a>';
})
.join('');
for (const link of list.querySelectorAll('.toc-item')) {
link.addEventListener('click', (ev) => {
ev.preventDefault();
const target = document.getElementById(link.dataset.target);
if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });
closeTocOnMobile();
});
}
observeTurns(entries);
}
let turnObserver = null;
function observeTurns(entries) {
if (turnObserver) turnObserver.disconnect();
if (!('IntersectionObserver' in window)) return;
const visible = new Set();
turnObserver = new IntersectionObserver(
(records) => {
for (const r of records) {
if (r.isIntersecting) visible.add(r.target.id);
else visible.delete(r.target.id);
}
const active = entries.find((e) => visible.has(e.id)) || entries[0];
for (const link of document.querySelectorAll('.toc-item')) {
link.classList.toggle('active', link.dataset.target === (active && active.id));
}
},
{ rootMargin: '0px 0px -70% 0px' },
);
for (const e of entries) {
const el = document.getElementById(e.id);
if (el) turnObserver.observe(el);
}
}
function renderMessages() {
const container = document.getElementById('messages');
const parts = [];
const tocEntries = [];
let index = 0;
const messages = showInternal
? allMessages
: allMessages.filter((msg) => !isInternal(msg)).map(userVisibleMessage);
responsesById = collectToolResponses(messages);
for (const msg of messages) {
if (isOnlyToolResponses(msg)) continue;
if (!showInternal && isInternal(msg)) continue;
const id = 'turn-' + index;
const html = renderMessage(msg, id);
if (html) {
parts.push(html);
tocEntries.push({ id, role: msg.role, label: tocLabel(msg), internal: isInternal(msg) });
index++;
}
}
container.innerHTML = parts.length
? parts.join('')
: '<div class="empty-state">No messages to display.</div>';
renderToc(tocEntries);
}
// ============================================================
// HEADER
// ============================================================
function infoItem(label, value) {
if (value == null || value === '') return '';
return '<div class="info-label">' + escapeHtml(label) + '</div>' +
'<div class="info-value">' + escapeHtml(value) + '</div>';
}
function renderHeader() {
const model = session.model_config && session.model_config.model_name;
const usage = session.usage || {};
const tokens = usage.total_tokens != null ? usage.total_tokens.toLocaleString() : null;
const cost = session.accumulated_cost != null ? '$' + session.accumulated_cost.toFixed(4) : null;
let info = '';
info += infoItem('session', session.id);
info += infoItem('created', session.created_at);
info += infoItem('updated', session.updated_at);
info += infoItem('provider', session.provider_name);
info += infoItem('model', model);
info += infoItem('messages', session.message_count);
info += infoItem('tokens', tokens);
info += infoItem('cost', cost);
const title = session.name && session.name.length ? session.name : 'Untitled session';
const dir = session.working_dir
? '<div class="header-dir">' + escapeHtml(session.working_dir) + '</div>'
: '';
const hasInternal = allMessages.some((msg) =>
isInternal(msg) || (Array.isArray(msg.content) && msg.content.some(hasAssistantOnlyContent)));
const toggle = hasInternal
? '<div class="header-actions"><button class="toggle-btn" id="toggle-internal">Show internal messages</button></div>'
: '';
document.getElementById('header-container').innerHTML =
'<div class="header"><h1>' + escapeHtml(title) + '</h1>' + dir +
'<div class="header-info">' + info + '</div>' + toggle + '</div>';
const btn = document.getElementById('toggle-internal');
if (btn) {
btn.addEventListener('click', () => {
showInternal = !showInternal;
btn.classList.toggle('active', showInternal);
btn.textContent = showInternal ? 'Hide internal messages' : 'Show internal messages';
renderMessages();
});
}
}
// ============================================================
// INIT
// ============================================================
// ============================================================
// MOBILE TOC TOGGLE
// ============================================================
const toc = document.getElementById('toc');
const tocToggle = document.getElementById('toc-toggle');
const tocOverlay = document.getElementById('toc-overlay');
function closeTocOnMobile() {
if (window.matchMedia('(max-width: 900px)').matches) {
toc.classList.remove('open');
tocOverlay.classList.remove('open');
tocToggle.setAttribute('aria-expanded', 'false');
}
}
tocToggle.addEventListener('click', () => {
const open = toc.classList.toggle('open');
tocOverlay.classList.toggle('open', open);
tocToggle.setAttribute('aria-expanded', String(open));
});
tocOverlay.addEventListener('click', closeTocOnMobile);
// "show more" expanders (delegated so it survives re-renders).
document.getElementById('messages').addEventListener('click', (ev) => {
const btn = ev.target.closest('.show-more');
if (!btn) return;
const block = btn.closest('.collapsible');
if (!block) return;
const expanded = block.classList.toggle('expanded');
btn.textContent = expanded ? 'show less' : btn.dataset.label;
});
// ============================================================
// INIT
// ============================================================
document.title = 'goose · ' + (session.name || session.id || 'session');
renderHeader();
renderMessages();
})();
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2
View File
@@ -1,5 +1,6 @@
mod chat_history_search;
mod diagnostics;
mod export_html;
mod export_markdown;
pub mod extension_data;
pub mod import_formats;
@@ -14,6 +15,7 @@ pub use diagnostics::{
DiagnosticsLevel, DiagnosticsLogs, DiagnosticsPrompt, DiagnosticsReport,
DiagnosticsScheduledRecipe, DiagnosticsTextFile, SystemInfo,
};
pub use export_html::export_session_to_html;
pub use export_markdown::{
export_session_to_markdown, message_to_markdown, user_projected_message_to_markdown,
};