croft-software 0.2.182

VSCode-style TUI written in Rust
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//! Inline AI completions (#607): ghost text at the caret, accepted with Tab.
//!
//! After a pause in typing the editor asks a model for the text that belongs
//! at the caret, given the lines before and after it (fill-in-the-middle),
//! and paints the answer as dim ghost text. `Tab` inserts it, `Esc` drops it,
//! and any edit makes it stale, since it answered for text that no longer
//! reads the same.
//!
//! # Where the model comes from
//!
//! The navigator's configuration, when the workspace seats a local one
//! (`croft pair` with an Anthropic-compatible endpoint such as Ollama);
//! otherwise the Claude API with `ANTHROPIC_API_KEY`. Either can be
//! overridden with `CROFT_COMPLETE_URL` / `CROFT_COMPLETE_MODEL`. Nothing is
//! sent until the user turns suggestions on: this ships code off the machine.
//!
//! A language server that offers inline completions (LSP 3.18
//! `textDocument/inlineCompletion`, e.g. Copilot's) answers for its own
//! files instead, and needs no model. Its answer may replace part of the
//! caret's line rather than add at the caret: [`Ghost::replacing`] turns
//! the common "finish the word you typed" kind back into plain ghost text,
//! and keeps the rest as a replacement Tab applies whole, so taking it
//! always leaves the line as the server's edit would.
//!
//! # Why one blocking request per pause, on its own thread
//!
//! A suggestion is a few dozen tokens, so a non-streaming request is simplest
//! and fastest to first paint. The worker only ever runs the newest request:
//! typing outpaces the network, and an answer for text the user has since
//! changed is thrown away on arrival anyway.

use std::ops::Range;
use std::sync::mpsc::{Receiver, Sender};
use std::time::Duration;

/// The name of the inline suggestion worker's thread, which the crash
/// notice names.
pub const THREAD: &str = "croft-inline-complete";

use crate::jobs::{Start, WorkerPoll};

use serde_json::{Value, json};

/// The default model on the Claude API. `CROFT_COMPLETE_MODEL` overrides it.
pub const DEFAULT_MODEL: &str = "claude-opus-5";

/// Quiet time after the last edit before a suggestion is asked for.
pub const DEBOUNCE: Duration = Duration::from_millis(500);

/// Lines of context sent before and after the caret.
const LINES_BEFORE: usize = 80;
const LINES_AFTER: usize = 30;

/// A suggestion is short; the model is told so, and this bounds it.
const MAX_TOKENS: u64 = 256;

/// The whole request's wall-clock budget: a suggestion later than this is
/// no longer wanted.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(8);

const SYSTEM: &str = "You are a code completion engine inside a text editor. The user message is a file with the marker <CURSOR> where the caret is. Reply with ONLY the text to insert at <CURSOR>: no explanation, no code fences, no repetition of text already before or after the marker. Prefer completing the current line; continue onto following lines only when the next lines are obvious. If nothing should be inserted, reply with nothing.";

/// Which backend answers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Backend {
    /// The Claude API.
    Claude { base_url: String, api_key: String },
    /// A local Anthropic-compatible endpoint (Ollama, LM Studio, ...).
    Local { base_url: String },
}

/// A resolved backend and model.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
    pub backend: Backend,
    pub model: String,
}

/// Resolve where suggestions come from, or say why none can: a local
/// navigator first, then the Claude API key, then nothing.
pub fn resolve(
    local: Option<(String, Option<String>)>,
    env: impl Fn(&str) -> Option<String>,
) -> Result<Config, String> {
    let model_override = env("CROFT_COMPLETE_MODEL").filter(|m| !m.is_empty());
    let url_override = env("CROFT_COMPLETE_URL").filter(|u| !u.is_empty());
    if let Some((base_url, model)) = local {
        let Some(model) = model_override.or(model) else {
            return Err(String::from(
                "the local navigator names no model; set CROFT_COMPLETE_MODEL",
            ));
        };
        return Ok(Config {
            backend: Backend::Local {
                base_url: url_override.unwrap_or(base_url),
            },
            model,
        });
    }
    let Some(api_key) = env("ANTHROPIC_API_KEY").filter(|k| !k.is_empty()) else {
        return Err(String::from(
            "set ANTHROPIC_API_KEY, or seat a local model with croft pair",
        ));
    };
    let base_url = url_override.unwrap_or_else(|| String::from("https://api.anthropic.com"));
    // The key rides every request, so it goes only where pair's own token
    // may: https anywhere, plain http only to this machine (#1927). The URL
    // is not echoed back, since its userinfo can hold a credential too.
    if !crate::pair::local::credential_allowed(&base_url) {
        return Err(String::from(
            "ANTHROPIC_API_KEY is sent only over https or to this machine, and CROFT_COMPLETE_URL is neither",
        ));
    }
    Ok(Config {
        backend: Backend::Claude { base_url, api_key },
        model: model_override.unwrap_or_else(|| String::from(DEFAULT_MODEL)),
    })
}

/// The prompt: the window of lines around the caret with `<CURSOR>` at it.
/// `row` and `col` are 0-based, `col` in characters.
pub fn prompt(lines: &[String], row: usize, col: usize) -> String {
    let start = row.saturating_sub(LINES_BEFORE);
    let end = (row + LINES_AFTER + 1).min(lines.len());
    let mut out = String::new();
    for (i, line) in lines.iter().enumerate().take(end).skip(start) {
        if i == row {
            let byte = line
                .char_indices()
                .nth(col)
                .map(|(b, _)| b)
                .unwrap_or(line.len());
            out.push_str(&line[..byte]);
            out.push_str("<CURSOR>");
            out.push_str(&line[byte..]);
        } else {
            out.push_str(line);
        }
        out.push('\n');
    }
    out
}

/// The request body for `config`.
pub fn request_body(config: &Config, prompt: &str) -> Value {
    let mut body = json!({
        "model": config.model,
        "max_tokens": MAX_TOKENS,
        "system": SYSTEM,
        "messages": [{ "role": "user", "content": prompt }],
    });
    if matches!(config.backend, Backend::Claude { .. }) {
        // Low effort: a completion wants speed, not deliberation. A refusal
        // re-runs server-side on Anthropic's recommended model instead of
        // coming back as no suggestion for no visible reason.
        body["output_config"] = json!({ "effort": "low" });
        body["fallbacks"] = json!("default");
    }
    body
}

/// The suggestion in a response, cleaned: the text blocks joined, a code
/// fence the model added anyway removed, and `None` for a refusal, an error
/// or an empty answer.
pub fn parse_response(body: &Value) -> Option<String> {
    if body.get("stop_reason").and_then(Value::as_str) == Some("refusal") {
        return None;
    }
    let text: String = body
        .get("content")?
        .as_array()?
        .iter()
        .filter(|b| b.get("type").and_then(Value::as_str) == Some("text"))
        .filter_map(|b| b.get("text").and_then(Value::as_str))
        .collect();
    let cleaned = strip_fence(&text);
    (!cleaned.trim().is_empty()).then(|| cleaned.to_string())
}

/// How much of a suggestion Ctrl+Right takes (#1625), as a byte length:
/// any leading whitespace, line breaks included, then one word (a run of
/// letters, digits and `_`) or one run of other symbols. VS Code's accept
/// next word.
pub fn next_word_len(text: &str) -> usize {
    let is_word = |c: char| c.is_alphanumeric() || c == '_';
    let body = text.trim_start();
    let lead = text.len() - body.len();
    let Some(first) = body.chars().next() else {
        return text.len();
    };
    let word = is_word(first);
    let run = body
        .char_indices()
        .find(|&(_, c)| c.is_whitespace() || is_word(c) != word)
        .map_or(body.len(), |(i, _)| i);
    lead + run
}

/// How much of a suggestion Ctrl+Down takes (#1625), as a byte length: the
/// rest of the caret's line, or, when the suggestion starts a new line,
/// that line break and the line after it.
pub fn next_line_len(text: &str) -> usize {
    let skip = usize::from(text.starts_with('\n'));
    text[skip..].find('\n').map_or(text.len(), |i| skip + i)
}

/// A suggestion where it was asked for: the caret's `row` and `col` (chars)
/// and the buffer's `edit_seq` then. It is live while all three still hold.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ghost {
    pub row: usize,
    pub col: usize,
    pub seq: u64,
    pub text: String,
    /// The columns of `row` that `text` takes the place of when accepted:
    /// a language server's replacement that is not plain typing ahead, such
    /// as a typo fixed with the rest of the line. `None` adds `text` at the
    /// caret, the only kind a model gives.
    pub replaces: Option<Range<usize>>,
}

impl Ghost {
    /// Ghost text added at the caret.
    pub fn insert(row: usize, col: usize, seq: u64, text: String) -> Self {
        Ghost {
            row,
            col,
            seq,
            text,
            replaces: None,
        }
    }

    /// A language server's answer that replaces columns `range` of the
    /// caret's `line` with `text`. When `text` starts with what the range
    /// already holds before the caret and ends with what it holds after it,
    /// only the new middle is ghost text at the caret, as for a model. Even
    /// blanks after the caret count: dropping them is the server's edit too.
    /// `None` when the answer changes nothing, or its range does not hold
    /// the caret or runs past the line.
    pub fn replacing(
        row: usize,
        col: usize,
        seq: u64,
        line: &str,
        range: Range<usize>,
        text: String,
    ) -> Option<Self> {
        if range.start > col || col > range.end || range.end > line.chars().count() {
            return None;
        }
        let typed: String = line.chars().take(col).skip(range.start).collect();
        let after: String = line.chars().take(range.end).skip(col).collect();
        let ahead = text
            .strip_prefix(typed.as_str())
            .and_then(|rest| rest.strip_suffix(after.as_str()));
        let (text, replaces) = match ahead {
            Some(middle) => (middle.to_string(), None),
            None => (text, Some(range)),
        };
        (!text.trim().is_empty()).then_some(Ghost {
            row,
            col,
            seq,
            text,
            replaces,
        })
    }
}

fn strip_fence(text: &str) -> &str {
    let t = text.trim_end();
    let Some(rest) = t.strip_prefix("```") else {
        return text.trim_end_matches('\n');
    };
    let body = rest.split_once('\n').map(|(_, b)| b).unwrap_or("");
    body.strip_suffix("```")
        .unwrap_or(body)
        .trim_end_matches('\n')
}

/// One suggestion request, tagged with what it answers for.
#[derive(Debug, Clone)]
pub struct Job {
    pub id: u64,
    pub config: Config,
    pub prompt: String,
}

/// The worker's answer to [`Job`] `id`.
#[derive(Debug)]
pub struct Done {
    pub id: u64,
    pub result: Result<Option<String>, String>,
}

/// The background requester: one thread, newest job wins. A thread that
/// crashed is started again, and one that crashes again soon after stops
/// until inline suggestions are next turned on (#2598).
pub struct Worker {
    worker: crate::jobs::Worker<Job, Done>,
}

impl Worker {
    pub fn spawn() -> Self {
        Self::spawn_with(send)
    }

    /// A worker whose thread answers each job with `ask`: [`send`] outside
    /// tests.
    fn spawn_with(
        ask: impl Fn(&Config, &str) -> Result<Option<String>, String> + Send + Sync + 'static,
    ) -> Self {
        let worker = crate::jobs::Worker::spawn(THREAD, Start::Now, move |job_rx, done_tx| {
            serve(&job_rx, &done_tx, &ask)
        })
        .expect("spawn inline-complete thread");
        Worker { worker }
    }

    /// A worker whose first `crashes` threads panic on their first job, and
    /// whose later ones suggest `text` for every job (#2598).
    #[cfg(test)]
    pub fn crashing(crashes: usize, text: &'static str) -> Self {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let asked = AtomicUsize::new(0);
        Self::spawn_with(move |_, _| {
            if asked.fetch_add(1, Ordering::SeqCst) < crashes {
                panic!("the inline suggestion worker crashed (on purpose, in a test)");
            }
            Ok(Some(text.to_string()))
        })
    }

    pub fn submit(&self, job: Job) {
        self.worker.send(job);
    }

    /// An answer, nothing more for now, or what happened to a thread that
    /// ended (see [`WorkerPoll`]).
    pub fn poll(&mut self) -> WorkerPoll<Done> {
        self.worker.poll()
    }

    /// Whether it stopped after crashing twice: nothing is sent to it then.
    pub fn is_stopped(&self) -> bool {
        self.worker.is_stopped()
    }

    /// Start the worker again as suggestions are turned on, if it stopped
    /// after crashing twice or its thread has ended where no tick saw it
    /// yet; true when a fresh thread started.
    pub fn restart_if_down(&mut self) -> std::io::Result<bool> {
        self.worker.restart_if_down()
    }

    /// Whether its thread has ended, for a test that must see a crash no
    /// tick has seen.
    #[cfg(test)]
    pub fn has_ended(&mut self) -> bool {
        self.worker.has_ended()
    }
}

/// What asks for one suggestion: [`send`] outside tests.
type Ask = dyn Fn(&Config, &str) -> Result<Option<String>, String>;

/// The worker thread's loop: only the newest request is asked, as typing
/// outpaces the network.
fn serve(job_rx: &Receiver<Job>, done_tx: &Sender<Done>, ask: &Ask) {
    while let Ok(mut job) = job_rx.recv() {
        while let Ok(newer) = job_rx.try_recv() {
            job = newer;
        }
        let result = ask(&job.config, &job.prompt);
        if done_tx.send(Done { id: job.id, result }).is_err() {
            return;
        }
    }
}

/// POST one request and parse the suggestion out of the answer.
fn send(config: &Config, prompt: &str) -> Result<Option<String>, String> {
    let agent = ureq3::Agent::config_builder()
        .timeout_global(Some(REQUEST_TIMEOUT))
        // A redirect would replay the API key to wherever it points.
        .max_redirects(0)
        .http_status_as_error(false)
        .build()
        .new_agent();
    let (base_url, key) = match &config.backend {
        Backend::Claude { base_url, api_key } => (base_url.as_str(), Some(api_key.as_str())),
        Backend::Local { base_url } => (base_url.as_str(), None),
    };
    let mut req = agent
        .post(format!("{}/v1/messages", base_url.trim_end_matches('/')))
        .header("content-type", "application/json")
        .header("anthropic-version", "2023-06-01");
    if let Some(key) = key {
        req = req
            .header("x-api-key", key)
            .header("anthropic-beta", "server-side-fallback-2026-07-01");
    }
    let mut resp = req
        .send(request_body(config, prompt).to_string())
        .map_err(|e| format!("request failed: {e}"))?;
    let status = resp.status();
    let text = resp
        .body_mut()
        .read_to_string()
        .map_err(|e| format!("reading the answer: {e}"))?;
    if !status.is_success() {
        let why = serde_json::from_str::<Value>(&text)
            .ok()
            .and_then(|v| {
                v.pointer("/error/message")
                    .and_then(Value::as_str)
                    .map(str::to_string)
            })
            .unwrap_or_else(|| text.chars().take(200).collect());
        return Err(format!("{status}: {why}"));
    }
    let body: Value = serde_json::from_str(&text).map_err(|e| format!("unreadable answer: {e}"))?;
    Ok(parse_response(&body))
}

#[cfg(test)]
mod tests {
    /// #1625: Ctrl+Right takes the line break and indent with the first
    /// word, then one symbol run or word at a time.
    #[test]
    fn next_word_takes_leading_space_and_one_word() {
        let text = "\n    total = a + b\n    return total";
        assert_eq!(&text[..next_word_len(text)], "\n    total");
        let rest = &text[next_word_len(text)..];
        assert_eq!(&rest[..next_word_len(rest)], " =");
        assert_eq!(next_word_len("foo_bar(1)"), 7);
        assert_eq!(next_word_len("();"), 3);
    }

    /// #1625 negative: whitespace alone, or nothing, is taken whole, so a
    /// word accept never leaves an all-blank remainder behind.
    #[test]
    fn next_word_of_blank_text_takes_it_all() {
        assert_eq!(next_word_len("   \n  "), 6);
        assert_eq!(next_word_len(""), 0);
    }

    /// #1625: Ctrl+Down takes the rest of the line, or a whole next line
    /// when the suggestion starts with a line break, never the break after.
    #[test]
    fn next_line_takes_one_line_without_the_break_after_it() {
        let text = "\n    total = a + b\n    return total";
        assert_eq!(&text[..next_line_len(text)], "\n    total = a + b");
        assert_eq!(next_line_len("1 + 1;"), 6);
        assert_eq!(&"x)\ny"[..next_line_len("x)\ny")], "x)");
    }

    use super::*;

    /// A server's answer that re-sends the word typed so far, and what
    /// its range holds after the caret, is plain ghost text for the rest.
    #[test]
    fn a_replacement_that_types_ahead_is_ghost_text_at_the_caret() {
        let line = "    let x = pri";
        let g = Ghost::replacing(0, 15, 7, line, 12..15, String::from("println!()")).unwrap();
        assert_eq!(g, Ghost::insert(0, 15, 7, String::from("ntln!()")));
        let closing = Ghost::replacing(0, 4, 1, "foo()", 0..5, String::from("foo(bar)"));
        assert_eq!(closing.map(|g| g.text).as_deref(), Some("bar"));
    }

    /// An answer that rewrites what was typed keeps its range, so Tab
    /// replaces those columns.
    #[test]
    fn a_replacement_that_rewrites_the_typed_text_keeps_its_range() {
        let line = "let x = pritn";
        let g = Ghost::replacing(0, 13, 2, line, 8..13, String::from("println!()")).unwrap();
        assert_eq!(g.text, "println!()");
        assert_eq!(g.replaces, Some(8..13));
        let dropped = Ghost::replacing(0, 4, 1, "foo()", 0..5, String::from("foo(x, y"));
        assert_eq!(
            dropped.and_then(|g| g.replaces),
            Some(0..5),
            "the `)` after the caret is not kept, so it is replaced"
        );
        let blanks = Ghost::replacing(0, 7, 1, "x = \"ab  ", 4..9, String::from("\"abc\""));
        assert_eq!(
            blanks.and_then(|g| g.replaces),
            Some(4..9),
            "blanks the answer drops are replaced, not left after it"
        );
    }

    /// Negative: a range away from the caret or past the line, and an
    /// answer that changes nothing, give no suggestion.
    #[test]
    fn a_replacement_off_the_caret_or_changing_nothing_is_dropped() {
        let line = "let x = 1";
        let text = || String::from("let y = 2");
        assert_eq!(Ghost::replacing(0, 9, 0, line, 0..3, text()), None);
        assert_eq!(Ghost::replacing(0, 9, 0, line, 0..12, text()), None);
        assert_eq!(
            Ghost::replacing(0, 9, 0, line, 8..9, String::from("1")),
            None
        );
        let wide = "é = ";
        let g = Ghost::replacing(0, 4, 0, wide, 0..4, String::from("é = 1")).unwrap();
        assert_eq!(g.text, "1", "columns are chars, not bytes");
    }

    fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
        let owned: Vec<(String, String)> = pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        move |k| {
            owned
                .iter()
                .find(|(key, _)| key == k)
                .map(|(_, v)| v.clone())
        }
    }

    #[test]
    fn a_local_navigator_wins_then_the_api_key_then_nothing() {
        let local = Some((
            String::from("http://localhost:11434"),
            Some(String::from("qwen")),
        ));
        assert_eq!(
            resolve(local, env_of(&[("ANTHROPIC_API_KEY", "k")])),
            Ok(Config {
                backend: Backend::Local {
                    base_url: String::from("http://localhost:11434")
                },
                model: String::from("qwen"),
            })
        );
        assert_eq!(
            resolve(None, env_of(&[("ANTHROPIC_API_KEY", "k")])).map(|c| c.model),
            Ok(String::from(DEFAULT_MODEL))
        );
        assert!(resolve(None, env_of(&[])).is_err());
        assert_eq!(
            resolve(
                None,
                env_of(&[("ANTHROPIC_API_KEY", "k"), ("CROFT_COMPLETE_MODEL", "m")])
            )
            .map(|c| c.model),
            Ok(String::from("m"))
        );
    }

    /// #1927: the API key never rides plain http to another machine. An
    /// https override and a loopback one still resolve.
    #[test]
    fn the_api_key_goes_only_to_https_or_this_machine() {
        let with_url = |url: &str| {
            resolve(
                None,
                env_of(&[("ANTHROPIC_API_KEY", "k"), ("CROFT_COMPLETE_URL", url)]),
            )
        };
        for remote in [
            "http://proxy.lan:8080",
            "http://10.0.0.5",
            "http://localhost:pass@evil.example",
            "ftp://api.example",
            "not a url",
        ] {
            let refused = with_url(remote);
            assert!(refused.is_err(), "{remote} must not receive the key");
            assert!(!refused.unwrap_err().contains(remote));
        }
        for allowed in [
            "https://gateway.example",
            "http://localhost:8080",
            "http://127.0.0.1:9000",
            "http://[::1]:9000",
        ] {
            assert_eq!(
                with_url(allowed).map(|c| c.backend),
                Ok(Backend::Claude {
                    base_url: String::from(allowed),
                    api_key: String::from("k"),
                }),
                "{allowed} may receive the key"
            );
        }
    }

    #[test]
    fn the_prompt_marks_the_caret_in_a_window_of_lines() {
        let lines: Vec<String> = ["fn main() {", "    let x = ", "}"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        assert_eq!(
            prompt(&lines, 1, 12),
            "fn main() {\n    let x = <CURSOR>\n}\n"
        );
    }

    #[test]
    fn the_claude_request_asks_for_low_effort_and_server_side_fallbacks() {
        let claude = Config {
            backend: Backend::Claude {
                base_url: String::from("https://api.anthropic.com"),
                api_key: String::from("k"),
            },
            model: String::from(DEFAULT_MODEL),
        };
        let body = request_body(&claude, "p");
        assert_eq!(body["output_config"]["effort"], "low");
        assert_eq!(body["fallbacks"], "default");
        assert_eq!(body["messages"][0]["content"], "p");
        let local = Config {
            backend: Backend::Local {
                base_url: String::from("http://localhost:11434"),
            },
            model: String::from("qwen"),
        };
        let body = request_body(&local, "p");
        assert!(
            body.get("fallbacks").is_none(),
            "local servers get the minimal payload"
        );
    }

    #[test]
    fn responses_are_cleaned_and_refusals_give_nothing() {
        let ok = json!({"stop_reason": "end_turn", "content": [
            {"type": "thinking", "thinking": ""},
            {"type": "text", "text": "42;\n"}
        ]});
        assert_eq!(parse_response(&ok).as_deref(), Some("42;"));
        let fenced = json!({"content": [{"type": "text", "text": "```rust\nfoo()\n```"}]});
        assert_eq!(parse_response(&fenced).as_deref(), Some("foo()"));
        let refused = json!({"stop_reason": "refusal", "content": []});
        assert_eq!(parse_response(&refused), None);
        let empty = json!({"content": [{"type": "text", "text": "  "}]});
        assert_eq!(parse_response(&empty), None);
    }
}