Skip to main content

eclipse_core/
naming.rs

1//! Naming a session: a name derived from the opening message, and the one bounded model call that
2//! may replace it.
3//!
4//! Two stages, and the order matters. The first is deterministic and cannot fail — the first line
5//! of what the user typed, whitespace collapsed, capped — so a list of sessions is never a column
6//! of `null`s waiting for a provider to answer. The second is a small-model call that only ever
7//! replaces the first, and only if its answer survives [`clean_reply`]: a reply that reads like an
8//! explanation rather than a name is thrown away whole, because a name is not a summary and a
9//! truncated summary is worse than the first line the user wrote.
10//!
11//! Nothing here touches the store or a provider. Both stages are pure functions of text so that
12//! the interesting part — what counts as a usable name — is testable without a model.
13
14use crate::message::Message;
15
16/// Longest derived name, in characters. The sidebar is narrow and the terminal's column is
17/// narrower; past this a name is a paragraph with the ending cut off.
18pub const MAX_NAME_CHARS: usize = 60;
19
20/// How much of the opening message the small call reads. Enough for the ask and the reason for it,
21/// which is what a name is made of; the rest of a long paste is the same request in more words.
22pub const UPGRADE_INPUT_CHARS: usize = 1_000;
23
24/// The name to show before any model has been asked: the first line of the opening message, with
25/// runs of whitespace collapsed and the cap applied at a word boundary where there is one.
26///
27/// `None` when the message has nothing to name — an empty prompt, or one that is only whitespace
28/// and punctuation. The caller keeps the preview then rather than inventing a placeholder.
29pub fn derive(opening: &str) -> Option<String> {
30    let line = opening
31        .lines()
32        .map(str::trim)
33        .find(|l| !l.is_empty())?
34        // Leading markdown noise is not part of anyone's name.
35        .trim_start_matches(['#', '>', '-', '*', '`', ' ']);
36    let one_line = line.split_whitespace().collect::<Vec<_>>().join(" ");
37    let one_line = one_line.trim();
38    if one_line.is_empty() {
39        return None;
40    }
41    // A trailing full stop is punctuation on a sentence, not part of a name; a message that is
42    // nothing but punctuation has no name in it at all.
43    let trimmed = one_line.trim_end_matches(['.', ',', ';', ':', '-', '?', '!']);
44    if trimmed.is_empty() {
45        return None;
46    }
47    Some(cap(trimmed))
48}
49
50/// Cut to [`MAX_NAME_CHARS`], preferring the last space at or after the halfway point so a name
51/// does not end mid-word when it does not have to. Never splits a character.
52fn cap(text: &str) -> String {
53    if text.chars().count() <= MAX_NAME_CHARS {
54        return text.to_string();
55    }
56    let mut cut = text
57        .char_indices()
58        .nth(MAX_NAME_CHARS)
59        .map(|(i, _)| i)
60        .unwrap_or(text.len());
61    let head = &text[..cut];
62    let halfway = text.chars().count() / 2;
63    if let Some(space) = head.rfind(' ') {
64        if head[..space].chars().count() >= halfway {
65            cut = space;
66        }
67    }
68    text[..cut].trim_end().to_string()
69}
70
71/// The prompt the small call is given. It asks for one JSON object and nothing else, and says so
72/// twice, because the shape is what [`clean_reply`] enforces and a model that ignores the second
73/// half of a long instruction is the normal case.
74pub fn upgrade_prompt(opening: &str) -> Vec<Message> {
75    const SYSTEM: &str = "\
76You name conversations. Given the opening message of one, answer with a JSON object of exactly \
77one key: {\"title\": \"...\"}. The title is 3 to 7 words, lowercase unless a name needs capitals, \
78and says what the work is about — not that it is a conversation, not a summary of the whole \
79thing, no trailing full stop, no quotes inside. Answer with the JSON object and nothing else.";
80
81    let excerpt: String = opening.chars().take(UPGRADE_INPUT_CHARS).collect();
82    vec![
83        Message::system(SYSTEM),
84        Message::user(format!("OPENING MESSAGE:\n{excerpt}")),
85    ]
86}
87
88/// What survives of the small call's answer, or why nothing does.
89///
90/// The answer is parsed as JSON rather than scanned for a name: a backend that ignored the shape
91/// and wrote a sentence gets its sentence thrown away, and the derived name stays. Every rule here
92/// is about the difference between a name and an explanation — a name is one short line that does
93/// not end in a full stop.
94pub fn clean_reply(reply: &str, opening: &str) -> std::result::Result<String, String> {
95    let text = reply.trim();
96    if text.is_empty() {
97        return Err("the reply was empty".into());
98    }
99    let value: serde_json::Value = serde_json::from_str(text)
100        .map_err(|_| format!("the reply was not a JSON object: {}", head(text)))?;
101    let raw = match &value {
102        // The asked-for shape, and the shape a stricter backend may wrap the string in.
103        serde_json::Value::Object(map) => map
104            .get("title")
105            .and_then(|v| v.as_str())
106            .ok_or_else(|| "the reply had no `title` string".to_string())?,
107        serde_json::Value::String(s) => s.as_str(),
108        other => return Err(format!("the reply was a {}, not an object", kind(other))),
109    };
110    // Before tidying: the collapse below would turn a two-line answer into one line, and a name
111    // that arrived as a paragraph is an explanation with the newline removed.
112    if raw.chars().any(char::is_control) {
113        return Err("the reply's title had control characters".into());
114    }
115    let name = tidy(raw);
116    if name.is_empty() {
117        return Err("the reply's title was empty".into());
118    }
119    let chars = name.chars().count();
120    if chars > MAX_NAME_CHARS {
121        return Err(format!("the reply's title was {chars} characters"));
122    }
123    let words = name.split_whitespace().count();
124    if words > 8 {
125        return Err(format!(
126            "the reply's title was {words} words, which is a summary"
127        ));
128    }
129    if name.ends_with('.') || name.ends_with(',') || name.ends_with(';') {
130        return Err("the reply's title ended like a sentence".into());
131    }
132    // The opening message handed back with the edges trimmed is not a name: it is the derived one
133    // in more characters, and spending a call to get it is the failure this check exists for.
134    if let Some(derived) = derive(opening) {
135        let same = name.to_lowercase();
136        let derived_lower = derived.to_lowercase();
137        if same == derived_lower || (words <= 2 && derived_lower.starts_with(&same)) {
138            return Err("the reply's title was the opening message again".into());
139        }
140    }
141    Ok(name)
142}
143
144/// Strip what a model wraps a name in when it is being helpful: quotes, backticks, bold asterisks,
145/// and a `Title:` label.
146fn tidy(raw: &str) -> String {
147    let mut text = raw.trim();
148    for prefix in ["title:", "name:", "session:", "title -", "title \u{2013}"] {
149        // Compared in bytes because every prefix here is ASCII, and skipping `prefix.len()` bytes
150        // only lands on a character boundary if the text's head is ASCII too — which the
151        // comparison just proved it is.
152        if text.len() > prefix.len()
153            && text.is_char_boundary(prefix.len())
154            && text[..prefix.len()].eq_ignore_ascii_case(prefix)
155        {
156            text = &text[prefix.len()..];
157            break;
158        }
159    }
160    let text = text
161        .trim()
162        .trim_matches([
163            '"', '\'', '`', '*', '\u{201c}', '\u{201d}', '\u{2018}', '\u{2019}',
164        ])
165        .trim();
166    text.split_whitespace().collect::<Vec<_>>().join(" ")
167}
168
169fn head(text: &str) -> String {
170    let short: String = text.chars().take(40).collect();
171    if text.chars().count() > 40 {
172        format!("{short}…")
173    } else {
174        short
175    }
176}
177
178fn kind(value: &serde_json::Value) -> &'static str {
179    match value {
180        serde_json::Value::Null => "null",
181        serde_json::Value::Bool(_) => "boolean",
182        serde_json::Value::Number(_) => "number",
183        serde_json::Value::String(_) => "string",
184        serde_json::Value::Array(_) => "array",
185        serde_json::Value::Object(_) => "object",
186    }
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    /// The first line, not the first paragraph: a prompt opens with its ask, and the rest of the
194    /// paste is why. Whitespace is collapsed because a name is displayed on one line.
195    #[test]
196    fn the_first_line_is_the_name() {
197        assert_eq!(
198            derive("fix the gateway   restart loop\nit happens on boot").as_deref(),
199            Some("fix the gateway restart loop")
200        );
201        assert_eq!(
202            derive("\n\n  ## rename sessions  \n").as_deref(),
203            Some("rename sessions")
204        );
205        assert_eq!(derive("   "), None, "nothing to name");
206        assert_eq!(derive("..."), None, "punctuation only is not a name");
207    }
208
209    /// A sentence's full stop is not part of a name, and a long opening is cut at a word so the
210    /// last thing on the row is a word rather than half of one.
211    #[test]
212    fn a_name_loses_the_full_stop_and_cuts_at_a_word() {
213        assert_eq!(
214            derive("add a title column to the store.").as_deref(),
215            Some("add a title column to the store")
216        );
217        let long = "word ".repeat(40);
218        let name = derive(&long).unwrap();
219        assert!(name.chars().count() <= MAX_NAME_CHARS, "{name}");
220        assert!(!name.ends_with(' '), "{name:?}");
221        assert!(name.ends_with("word"), "cut at a word boundary: {name:?}");
222        // A single word longer than the cap has no space to cut at, and must not be split inside
223        // a character.
224        let huge = "é".repeat(200);
225        assert_eq!(derive(&huge).unwrap().chars().count(), MAX_NAME_CHARS);
226    }
227
228    /// The reply is JSON, and what comes out of it is one short line. A model that answered with a
229    /// sentence, a summary or an essay gets nothing: stage 1 has a name already, and a truncated
230    /// explanation is worse than the user's own first line.
231    #[test]
232    fn only_a_short_object_becomes_a_name() {
233        let opening = "the dashboard's session list is unreadable at a hundred sessions";
234        let ok = |r: &str| clean_reply(r, opening);
235        assert_eq!(
236            ok("{\"title\": \"session names from the model\"}").as_deref(),
237            Ok("session names from the model")
238        );
239        assert_eq!(
240            ok("{\"title\": \"Title: session names\"}").as_deref(),
241            Ok("session names"),
242            "a label is noise, not a name"
243        );
244        assert_eq!(
245            ok("  \"quoted name\"  ").as_deref(),
246            Ok("quoted name"),
247            "a bare string still works"
248        );
249        assert!(
250            ok("Sure! Here is a title: session names").is_err(),
251            "prose is not JSON"
252        );
253        assert!(
254            ok("{\"name\": \"session names\"}").is_err(),
255            "the wrong key"
256        );
257        assert!(ok("{\"title\": \"\"}").is_err(), "an empty name");
258        assert!(ok("{\"title\": 42}").is_err(), "a number is not a name");
259        assert!(
260            ok("{\"title\": \"rename the sessions and add a title column to the store and then\"}")
261                .is_err(),
262            "eleven words is a summary"
263        );
264        assert!(
265            ok("{\"title\": \"a name that ends like a sentence.\"}").is_err(),
266            "a full stop"
267        );
268        assert!(
269            ok("{\"title\": \"two\\nlines\"}").is_err(),
270            "control characters"
271        );
272    }
273
274    /// Handing the opening message back is not an upgrade: it is the derived name with different
275    /// edges, and it must not count as the model having named anything.
276    #[test]
277    fn an_echo_of_the_opening_is_not_an_upgrade() {
278        let opening = "fix the gateway restart loop";
279        assert!(clean_reply("{\"title\": \"fix the gateway restart loop\"}", opening).is_err());
280        assert_eq!(
281            clean_reply("{\"title\": \"gateway restart loop\"}", opening).as_deref(),
282            Ok("gateway restart loop"),
283            "fewer words is a name, and not an echo"
284        );
285    }
286
287    /// The prompt carries the opening message, capped, and asks for the one object the parser
288    /// expects.
289    #[test]
290    fn the_prompt_asks_for_one_object_and_sends_a_bounded_excerpt() {
291        let long = "x".repeat(5_000);
292        let asked = upgrade_prompt(&long);
293        assert_eq!(asked.len(), 2);
294        assert!(asked[0].content.as_deref().unwrap().contains("{\"title\""));
295        let sent = asked[1].content.as_deref().unwrap();
296        assert_eq!(
297            sent.chars().count(),
298            "OPENING MESSAGE:\n".chars().count() + UPGRADE_INPUT_CHARS
299        );
300    }
301}