mindfork 0.10.1

A terminal AI chat written in Rust: local models via llama.cpp or OpenAI, Anthropic, Gemini and Grok in the cloud, with persistent memory, notes, RAG and tools.
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! An HTTP client to the native Google Gemini API (`POST …:streamGenerateContent?alt=sse`),
//! implementing [`EngineBackend`]. A protocol separate from the OpenAI-compatible Chat
//! Completions path (`OpenAiClient` + the Gemini dialect, now replaced by this client): "thought"
//! summaries (`thinkingConfig.includeThoughts`), depth (`thinkingLevel`/
//! `thinkingBudget`), `thoughtsTokenCount`. See ADR 0004, docs/research/gemini-native-client.md.
//!
//! This client gives no embeddings — RAG in Gemini mode takes a separate source
//! (the OpenAI-compatible `…/v1beta/openai/embeddings`, see the supervisor), like Anthropic.

use anyhow::Result;
use async_stream::stream;
use eventsource_stream::Eventsource;
use futures_util::StreamExt;
use tokio_util::sync::CancellationToken;

use super::wire::{self, GenResponse};
use crate::shared::api::contract::{
    ChatChunk, ChatRequest, ChatStream, EngineBackend, FinishReason, TokenUsage, ToolCallDelta,
    VisionSupport,
};
use crate::shared::api::error::{self, SUBJECT_GEMINI};
use crate::shared::api::http;

/// A client to the native Gemini API.
pub struct GeminiClient {
    http: reqwest::Client,
    /// The base URL with a `/v1beta` suffix (the client appends
    /// `/models/{model}:streamGenerateContent`), e.g.
    /// `https://generativelanguage.googleapis.com/v1beta`.
    base_url: String,
    api_key: String,
    model: String,
}

impl GeminiClient {
    pub fn new(
        base_url: impl Into<String>,
        api_key: impl Into<String>,
        model: impl Into<String>,
    ) -> Self {
        let base_url = base_url.into().trim_end_matches('/').to_string();
        // The model name may arrive with a `models/` prefix — the path already carries it.
        let model = model
            .into()
            .trim_start_matches("models/")
            .trim()
            .to_string();
        Self {
            http: http::engine_client(),
            base_url,
            api_key: api_key.into(),
            model,
        }
    }
}

/// Gemini's string `finishReason` → the domain reason. The presence of tool calls
/// (`saw_tool_call`) gives `ToolCalls` even on `STOP` (Gemini returns `STOP` with
/// `functionCall` parts), and over a filter reason too — the calls are what the model
/// asked for. `MAX_TOKENS` → `Length`; a filter reason ([`is_filter_reason`]) →
/// `Filtered`; anything else — `Stop`, so as not to fail ([`is_block_reason`]
/// recognizes the other blocking reasons and surfaces a note).
fn map_finish(reason: &str, saw_tool_call: bool) -> FinishReason {
    match reason {
        "MAX_TOKENS" => FinishReason::Length,
        _ if saw_tool_call => FinishReason::ToolCalls,
        _ if is_filter_reason(reason) => FinishReason::Filtered,
        _ => FinishReason::Stop,
    }
}

/// A finish reason saying the provider's content filter stopped the reply. It ends
/// the turn as [`FinishReason::Filtered`], whose note the feed shows in the
/// interface's language — it used to be an English sentence yielded as reply text,
/// stored in the chat and sent back to the model as its own words
/// ([docs/research/content-filter-finish.md](../../../../docs/research/content-filter-finish.md), fork C3).
fn is_filter_reason(reason: &str) -> bool {
    matches!(
        reason,
        "SAFETY" | "RECITATION" | "BLOCKLIST" | "PROHIBITED_CONTENT" | "SPII" | "IMAGE_SAFETY"
    )
}

/// A blocking finish reason that is **not** a filter: a malformed call, or `OTHER`.
/// Such a reply arrives empty — without an explanation the user would see a silently
/// empty turn, so it's surfaced as a note (see [`block_note`]).
fn is_block_reason(reason: &str) -> bool {
    matches!(reason, "MALFORMED_FUNCTION_CALL" | "OTHER")
}

/// A note to the user about the block (goes into the feed as reply text, so an empty turn
/// is explainable).
fn block_note(reason: &str) -> String {
    format!("\n⚠ Gemini did not produce a response (reason: {reason}).")
}

#[async_trait::async_trait]
impl EngineBackend for GeminiClient {
    async fn chat_stream(&self, req: ChatRequest, cancel: CancellationToken) -> Result<ChatStream> {
        let body = wire::build_request(&req, &self.model);
        let url = format!(
            "{}/models/{}:streamGenerateContent?alt=sse",
            self.base_url, self.model
        );

        let request = self
            .http
            .post(&url)
            .header("x-goog-api-key", &self.api_key)
            .json(&body);
        let Some(response) = http::send_cancellable(request, &cancel).await? else {
            return Ok(http::cancelled_stream());
        };
        let response = error::check_status(SUBJECT_GEMINI, response).await?;

        let mut events = response.bytes_stream().eventsource();

        let s = stream! {
            // The ordinal index of the tool call (Gemini has no call_id — synthesize a
            // stable id `"{name}-{index}"`; functionResponse matching goes by it).
            let mut tool_index = 0usize;
            let mut saw_tool_call = false;
            loop {
                tokio::select! {
                    biased;
                    _ = cancel.cancelled() => {
                        yield ChatChunk::Finished(FinishReason::Cancelled);
                        break;
                    }
                    next = events.next() => {
                        match next {
                            None => {
                                yield ChatChunk::Finished(FinishReason::Stop);
                                break;
                            }
                            Some(Err(err)) => {
                                let message = error::chain_text(&err);
                                tracing::warn!(error = %message, "SSE stream error (gemini)");
                                for chunk in ChatChunk::failure(message, true) { yield chunk; }
                                break;
                            }
                            Some(Ok(event)) => {
                                if event.data == "[DONE]" {
                                    yield ChatChunk::Finished(FinishReason::Stop);
                                    break;
                                }
                                let resp: GenResponse = match serde_json::from_str(&event.data) {
                                    Ok(r) => r,
                                    Err(err) => {
                                        tracing::warn!(error = %err, data = %event.data, "failed to parse gemini SSE chunk");
                                        continue;
                                    }
                                };
                                // An error reported inside the stream. Checked before
                                // anything else: every other field of GenResponse
                                // defaults, so this payload is otherwise a valid
                                // empty chunk and the turn ended as a silent Stop.
                                if let Some(e) = resp.error {
                                    let transient = error::stream_error_transient(&e.status, e.code);
                                    tracing::warn!(
                                        status = %e.status,
                                        code = ?e.code,
                                        transient,
                                        message = %e.message,
                                        "gemini reported an error inside the stream"
                                    );
                                    let message = error::stream_error_text(&e.status, &e.message);
                                    for chunk in ChatChunk::failure(message, transient) { yield chunk; }
                                    break;
                                }
                                // The prompt was blocked by the filter (candidates is empty) —
                                // ended as filtered, otherwise it would look like an empty STOP.
                                if let Some(reason) = resp
                                    .prompt_feedback
                                    .and_then(|f| f.block_reason)
                                    .filter(|r| !r.is_empty())
                                {
                                    tracing::warn!(reason = %reason, "gemini blocked the prompt");
                                    yield ChatChunk::Finished(FinishReason::Filtered);
                                    break;
                                }
                                let candidate = resp.candidates.into_iter().next();
                                if let Some(cand) = &candidate
                                    && let Some(content) = &cand.content
                                {
                                    for part in &content.parts {
                                        if let Some(fc) = &part.function_call {
                                            saw_tool_call = true;
                                            yield ChatChunk::ToolCall(ToolCallDelta {
                                                index: tool_index,
                                                id: Some(format!("{}-{}", fc.name, tool_index)),
                                                name: Some(fc.name.clone()),
                                                arguments: fc.args.to_string(),
                                                // The thought signature (Gemini 3) — on the functionCall part.
                                                thought_signature: part.thought_signature.clone(),
                                            });
                                            tool_index += 1;
                                        } else if let Some(text) = &part.text {
                                            if text.is_empty() {
                                                continue;
                                            }
                                            if part.thought == Some(true) {
                                                yield ChatChunk::Thoughts(text.clone());
                                            } else {
                                                yield ChatChunk::Text(text.clone());
                                            }
                                        }
                                    }
                                }
                                if let Some(u) = resp.usage_metadata {
                                    yield ChatChunk::Usage(TokenUsage {
                                        prompt_tokens: u.prompt_token_count,
                                        completion_tokens: u.candidates_token_count,
                                        reasoning_tokens: u.thoughts_token_count,
                                        prefill: None,
                                    });
                                }
                                if let Some(reason) = candidate.and_then(|c| c.finish_reason) {
                                    // A blocking reason that is not a filter (a malformed call,
                                    // OTHER) — surfaced as a note, otherwise an empty turn would
                                    // go unexplained. A filter reason ends as `Filtered` below.
                                    if is_filter_reason(&reason) {
                                        tracing::warn!(reason = %reason, "gemini stopped the reply with a filter reason");
                                    }
                                    if is_block_reason(&reason) && !saw_tool_call {
                                        tracing::warn!(reason = %reason, "gemini stopped with a block reason");
                                        yield ChatChunk::Text(block_note(&reason));
                                    }
                                    yield ChatChunk::Finished(map_finish(&reason, saw_tool_call));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        };

        Ok(Box::pin(s))
    }

    /// Gemini takes images on every current model, so the answer is static.
    ///
    /// Deliberately **not** a model-name allowlist: a hardcoded list of vision
    /// models goes stale the week after it is written and then lies confidently —
    /// the trap docs/research/grok-xai-provider.md recorded for reasoning detection.
    /// A genuinely text-only model returns a clear provider error on send, which is
    /// a far better failure than refusing an attach on a guess.
    async fn vision(&self) -> VisionSupport {
        VisionSupport::Supported
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::shared::api::sse_stub::{self, collect, serve};

    #[test]
    fn finish_mapping() {
        assert_eq!(map_finish("STOP", false), FinishReason::Stop);
        assert_eq!(map_finish("STOP", true), FinishReason::ToolCalls);
        assert_eq!(map_finish("MAX_TOKENS", false), FinishReason::Length);
        assert_eq!(map_finish("SAFETY", false), FinishReason::Filtered);
        assert_eq!(map_finish("RECITATION", false), FinishReason::Filtered);
        // The calls the model produced win over a filter reason after them.
        assert_eq!(map_finish("SAFETY", true), FinishReason::ToolCalls);
        assert_eq!(map_finish("OTHER", false), FinishReason::Stop);
    }

    #[test]
    fn strips_models_prefix_from_model() {
        let c = GeminiClient::new("https://x/v1beta", "k", "models/gemini-2.5-flash");
        assert_eq!(c.model, "gemini-2.5-flash");
    }

    #[test]
    fn block_reasons_recognized_and_noted() {
        assert!(is_block_reason("MALFORMED_FUNCTION_CALL"));
        assert!(is_block_reason("OTHER"));
        // A filter reason is not a block reason: it has a finish reason of its own.
        assert!(!is_block_reason("SAFETY"));
        assert!(!is_block_reason("STOP"));
        assert!(!is_block_reason("MAX_TOKENS"));
        // The note carries the reason.
        assert!(block_note("OTHER").contains("OTHER"));
    }

    #[test]
    fn filter_reasons_are_told_from_the_other_blocks() {
        for r in [
            "SAFETY",
            "RECITATION",
            "BLOCKLIST",
            "PROHIBITED_CONTENT",
            "SPII",
            "IMAGE_SAFETY",
        ] {
            assert!(is_filter_reason(r), "{r}");
            assert!(!is_block_reason(r), "{r}");
        }
        for r in ["STOP", "MAX_TOKENS", "MALFORMED_FUNCTION_CALL", "OTHER"] {
            assert!(!is_filter_reason(r), "{r}");
        }
    }

    /// A reply the filter stopped keeps what arrived, gains no text of ours, and ends
    /// as filtered — the note is the feed's, in the interface's language.
    #[tokio::test]
    async fn a_safety_stop_ends_the_turn_as_filtered_with_no_text_of_ours() {
        let base = serve(&[
            r#"{"candidates":[{"content":{"parts":[{"text":"Once upon"}],"role":"model"}}]}"#,
            r#"{"candidates":[{"content":{"parts":[],"role":"model"},"finishReason":"SAFETY"}]}"#,
        ]);
        let client = GeminiClient::new(base, "k", "gemini-x");
        let chunks = collect(
            client
                .chat_stream(sse_stub::hello(), Default::default())
                .await
                .unwrap(),
        )
        .await;
        let texts: Vec<_> = chunks
            .iter()
            .filter_map(|c| match c {
                ChatChunk::Text(t) => Some(t.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(texts, ["Once upon"], "{chunks:?}");
        assert_eq!(
            chunks.last(),
            Some(&ChatChunk::Finished(FinishReason::Filtered))
        );
    }

    /// A refused prompt — no candidates, a `blockReason` — ends the same way.
    #[tokio::test]
    async fn a_blocked_prompt_ends_the_turn_as_filtered() {
        let base = serve(&[r#"{"promptFeedback":{"blockReason":"PROHIBITED_CONTENT"}}"#]);
        let client = GeminiClient::new(base, "k", "gemini-x");
        let chunks = collect(
            client
                .chat_stream(sse_stub::hello(), Default::default())
                .await
                .unwrap(),
        )
        .await;
        assert_eq!(
            chunks,
            [ChatChunk::Finished(FinishReason::Filtered)],
            "no reply text, only the reason"
        );
    }

    /// A block that is not a filter keeps the note it had.
    #[tokio::test]
    async fn a_malformed_call_still_gets_its_note() {
        let base = serve(&[
            r#"{"candidates":[{"content":{"parts":[],"role":"model"},"finishReason":"MALFORMED_FUNCTION_CALL"}]}"#,
        ]);
        let client = GeminiClient::new(base, "k", "gemini-x");
        let chunks = collect(
            client
                .chat_stream(sse_stub::hello(), Default::default())
                .await
                .unwrap(),
        )
        .await;
        assert!(
            chunks.contains(&ChatChunk::Text(block_note("MALFORMED_FUNCTION_CALL"))),
            "{chunks:?}"
        );
        assert_eq!(
            chunks.last(),
            Some(&ChatChunk::Finished(FinishReason::Stop))
        );
    }
}

/// A manual smoke against the real Gemini API. Marked `#[ignore]` — not in CI.
/// Run: `MINDFORK_GEMINI_KEY=… cargo test gemini -- --ignored --nocapture`.
#[cfg(test)]
mod ignored_smoke {
    use super::*;
    use crate::entities::sampling::{ReasoningEffort, SamplingConfig};
    use crate::shared::api::ToolCallAccumulator;
    use crate::shared::api::contract::{ApiMessage, ToolSchema};

    fn client_from_env() -> Option<GeminiClient> {
        let key = std::env::var("MINDFORK_GEMINI_KEY").ok()?;
        let model =
            std::env::var("MINDFORK_GEMINI_MODEL").unwrap_or_else(|_| "gemini-2.5-flash".into());
        Some(GeminiClient::new(
            "https://generativelanguage.googleapis.com/v1beta",
            key,
            model,
        ))
    }

    #[tokio::test]
    #[ignore = "requires MINDFORK_GEMINI_KEY (live Gemini API)"]
    async fn simple_generation() {
        let Some(client) = client_from_env() else {
            eprintln!("skip: MINDFORK_GEMINI_KEY not set");
            return;
        };
        let req = ChatRequest {
            continue_final: false,
            system: Some("You are a helpful assistant.".into()),
            messages: vec![ApiMessage::user("Reply with exactly: pong")],
            sampling: SamplingConfig {
                max_tokens: Some(2048),
                ..Default::default()
            },
            tools: vec![],
        };
        let mut stream = client.chat_stream(req, Default::default()).await.unwrap();
        let mut text = String::new();
        let mut finish = None;
        while let Some(chunk) = stream.next().await {
            match chunk {
                ChatChunk::Text(t) => text.push_str(&t),
                ChatChunk::Finished(r) => {
                    finish = Some(r);
                    break;
                }
                ChatChunk::Error { message, .. } => {
                    eprintln!("engine error: {message}");
                }
                _ => {}
            }
        }
        assert!(!text.is_empty(), "expected non-empty response");
        assert!(matches!(
            finish,
            Some(FinishReason::Stop | FinishReason::Length)
        ));
    }

    /// The **fallback** an image in a tool result takes on Gemini, and the only place it
    /// is exercised end to end (fork F1-A of docs/research/mcp-tool-images.md).
    ///
    /// Gemini is the one provider that refuses a multimodal `functionResponse` — measured,
    /// a hard `400` "Multimodal function responses are not supported for this model" —
    /// so its builder emits the image as user parts *after* the response instead. This
    /// test is what proves that detour still reaches the model, and that the request is
    /// accepted at all: a regression putting the image back inside the `functionResponse`
    /// would fail here with that 400 rather than silently degrade.
    ///
    /// Control arm included, for the reason recorded in §2.1 of that document.
    #[tokio::test]
    #[ignore = "requires MINDFORK_GEMINI_KEY (live Gemini API)"]
    async fn tool_result_image_takes_the_user_part_fallback() {
        let Some(client) = client_from_env() else {
            eprintln!("skip: MINDFORK_GEMINI_KEY not set");
            return;
        };
        let turn = |with_image: bool| {
            let tool = ApiMessage::tool("take_screenshot-0", "Screenshot taken.");
            let tool = if with_image {
                tool.with_images(vec![crate::shared::api::ApiImage::new(
                    "image/png",
                    &crate::shared::api::green_circle_png_base64(),
                    None,
                )])
            } else {
                tool
            };
            ChatRequest {
                continue_final: false,
                system: None,
                // The shape a real turn has: the question is asked **up front**, and the
                // tool result is the last message — the model answers from it. A trailing
                // user message would be unrealistic *and* wrong here: Gemini puts a tool
                // result in a `user` content and adjacent same-role contents merge, so the
                // question would end up sharing one content with the `functionResponse` —
                // measured, Gemini then returns an empty candidate (`STOP`, zero
                // completion tokens) while still billing the image.
                messages: vec![
                    ApiMessage::user(crate::shared::api::TOOL_VISION_PROMPT),
                    ApiMessage::assistant_tool_calls(
                        "",
                        vec![crate::shared::api::ApiToolCall {
                            id: "take_screenshot-0".into(),
                            name: "take_screenshot".into(),
                            arguments: "{}".into(),
                            thought_signature: None,
                        }],
                    ),
                    tool,
                ],
                sampling: SamplingConfig {
                    max_tokens: Some(2048),
                    // Thinking muted, or there is no answer to assert on: 2.5-flash
                    // thinks by default and the budget is **shared** with the reply, so
                    // both arms come back empty and the failure reads as "the image did
                    // not arrive" (docs/lessons.md §3 — measured here first).
                    reasoning_budget: Some(0),
                    ..Default::default()
                },
                tools: vec![crate::shared::api::ToolSchema {
                    name: "take_screenshot".into(),
                    description: "Take a screenshot of the screen.".into(),
                    parameters: serde_json::json!({ "type": "object", "properties": {} }),
                }],
            }
        };
        let read = async |req| {
            let mut stream: ChatStream = client.chat_stream(req, Default::default()).await.unwrap();
            let mut text = String::new();
            while let Some(chunk) = stream.next().await {
                match chunk {
                    ChatChunk::Text(t) => text.push_str(&t),
                    ChatChunk::Error { message, .. } => eprintln!("engine error: {message}"),
                    ChatChunk::Finished(_) => break,
                    _ => {}
                }
            }
            text
        };

        let control = read(turn(false)).await;
        eprintln!("gemini control (no image): {control}");
        crate::shared::api::assert_sees_green_circle(&control, false, "control");

        let answer = read(turn(true)).await;
        eprintln!("gemini tool-result image: {answer}");
        crate::shared::api::assert_sees_green_circle(&answer, true, "with the image");
    }

    /// Image input (spec §9.10): an `inline_data` part reaches the model and is
    /// described. Verified live before the wire was written — see
    /// docs/research/multimodal-images.md §2.2.
    #[tokio::test]
    #[ignore = "requires MINDFORK_GEMINI_KEY (live Gemini API)"]
    async fn image_input_is_described() {
        let Some(client) = client_from_env() else {
            eprintln!("skip: MINDFORK_GEMINI_KEY not set");
            return;
        };
        let req = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![
                ApiMessage::user(crate::shared::api::VISION_PROMPT).with_images(vec![
                    crate::shared::api::ApiImage::new(
                        "image/png",
                        &crate::shared::api::blue_square_png_base64(),
                        None,
                    ),
                ]),
            ],
            // 2.5-flash thinks by default and the budget is shared with the reply, so a
            // small cap here would return an empty answer rather than a wrong one.
            sampling: SamplingConfig {
                max_tokens: Some(2048),
                ..Default::default()
            },
            tools: vec![],
        };
        let mut stream = client.chat_stream(req, Default::default()).await.unwrap();
        let mut text = String::new();
        while let Some(chunk) = stream.next().await {
            match chunk {
                ChatChunk::Text(t) => text.push_str(&t),
                ChatChunk::Error { message, .. } => eprintln!("engine error: {message}"),
                ChatChunk::Finished(_) => break,
                _ => {}
            }
        }
        eprintln!("gemini vision reply: {text}");
        crate::shared::api::assert_sees_blue_square(&text, "gemini");
    }

    /// Reasoning summary: with `thinking=true`, "thoughts" (Thoughts) and the reply arrive.
    /// `max_tokens` is generous — thought tokens eat into the reply budget.
    #[tokio::test]
    #[ignore = "requires MINDFORK_GEMINI_KEY (live Gemini API)"]
    async fn thinking_streams_thoughts() {
        let Some(client) = client_from_env() else {
            eprintln!("skip: MINDFORK_GEMINI_KEY not set");
            return;
        };
        let req = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![ApiMessage::user(
                "Think step by step: what is 17 * 23? Show brief reasoning.",
            )],
            sampling: SamplingConfig {
                max_tokens: Some(4096),
                thinking: Some(true),
                reasoning_effort: Some(ReasoningEffort::Medium),
                ..Default::default()
            },
            tools: vec![],
        };
        let mut stream = client.chat_stream(req, Default::default()).await.unwrap();
        let mut thoughts = String::new();
        let mut text = String::new();
        while let Some(chunk) = stream.next().await {
            match chunk {
                ChatChunk::Thoughts(t) => thoughts.push_str(&t),
                ChatChunk::Text(t) => text.push_str(&t),
                ChatChunk::Finished(_) => break,
                ChatChunk::Error { message, .. } => {
                    eprintln!("engine error: {message}");
                }
                _ => {}
            }
        }
        assert!(
            !text.is_empty(),
            "expected final answer, thoughts={thoughts:?}"
        );
    }

    /// One tool round: the model calls the tool (without resending the signature — Phase B).
    #[tokio::test]
    #[ignore = "requires MINDFORK_GEMINI_KEY (live Gemini API)"]
    async fn single_tool_call() {
        let Some(client) = client_from_env() else {
            eprintln!("skip: MINDFORK_GEMINI_KEY not set");
            return;
        };
        let tool = ToolSchema {
            name: "get_weather".into(),
            description: "Get the current weather for a city.".into(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"],
            }),
        };
        let req = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![ApiMessage::user("Call get_weather for Paris.")],
            sampling: SamplingConfig {
                max_tokens: Some(2048),
                ..Default::default()
            },
            tools: vec![tool],
        };
        let mut stream = client.chat_stream(req, Default::default()).await.unwrap();
        let mut acc = ToolCallAccumulator::default();
        let mut reason = FinishReason::Stop;
        while let Some(chunk) = stream.next().await {
            match chunk {
                ChatChunk::ToolCall(d) => acc.push(d),
                ChatChunk::Finished(r) => {
                    reason = r;
                    break;
                }
                ChatChunk::Error { message, .. } => {
                    eprintln!("engine error: {message}");
                }
                _ => {}
            }
        }
        assert_eq!(
            reason,
            FinishReason::ToolCalls,
            "model should call the tool"
        );
        let calls = acc.finish();
        assert!(!calls.is_empty(), "expected a tool call");
        assert_eq!(calls[0].name, "get_weather");
    }

    /// Phase B: a tool-use round-trip resending the thought signature. On **Gemini 3**
    /// (`MINDFORK_GEMINI_MODEL=gemini-3-*`) the first round gives a call + `thoughtSignature`;
    /// the second resends it on `functionCall` + the result — Gemini must not return
    /// `400` ("missing thought_signature"). On 2.5 the signature is optional (the round also
    /// goes through). Checks: the signature arrived and resending doesn't break the round.
    #[tokio::test]
    #[ignore = "requires MINDFORK_GEMINI_KEY (live Gemini API), Gemini 3 for signatures"]
    async fn tool_use_round_trips_signature() {
        let Some(client) = client_from_env() else {
            eprintln!("skip: MINDFORK_GEMINI_KEY not set");
            return;
        };
        let tool = ToolSchema {
            name: "get_weather".into(),
            description: "Get the current weather for a city.".into(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"],
            }),
        };
        let sampling = SamplingConfig {
            max_tokens: Some(4096),
            thinking: Some(true),
            reasoning_effort: Some(ReasoningEffort::High),
            ..Default::default()
        };
        let prompt = "Reason briefly which of Paris or Berlin is the capital of France, \
             then call get_weather for that city.";
        let round1 = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![ApiMessage::user(prompt)],
            sampling: sampling.clone(),
            tools: vec![tool.clone()],
        };
        let mut stream = client
            .chat_stream(round1, Default::default())
            .await
            .unwrap();
        let mut acc = ToolCallAccumulator::default();
        let mut reason = FinishReason::Stop;
        while let Some(chunk) = stream.next().await {
            match chunk {
                ChatChunk::ToolCall(d) => acc.push(d),
                ChatChunk::Finished(r) => {
                    reason = r;
                    break;
                }
                ChatChunk::Error { message, .. } => {
                    eprintln!("engine error: {message}");
                }
                _ => {}
            }
        }
        assert_eq!(
            reason,
            FinishReason::ToolCalls,
            "model should call the tool"
        );
        let calls = acc.finish();
        assert!(!calls.is_empty(), "expected a tool call");
        let call = calls[0].clone();
        eprintln!(
            "thought_signature present: {}",
            call.thought_signature.is_some()
        );

        // Second round: assistant(functionCall with the signature) + the result.
        let round2 = ChatRequest {
            continue_final: false,
            system: None,
            messages: vec![
                ApiMessage::user(prompt),
                ApiMessage::assistant_tool_calls("", vec![call.clone()]),
                ApiMessage::tool(&call.id, "18°C, sunny"),
            ],
            sampling,
            tools: vec![tool],
        };
        let mut stream = client
            .chat_stream(round2, Default::default())
            .await
            .unwrap();
        let mut text = String::new();
        let mut finish = None;
        while let Some(chunk) = stream.next().await {
            match chunk {
                ChatChunk::Text(t) => text.push_str(&t),
                ChatChunk::Finished(r) => {
                    finish = Some(r);
                    break;
                }
                ChatChunk::Error { message, .. } => {
                    eprintln!("engine error: {message}");
                }
                _ => {}
            }
        }
        assert!(
            matches!(finish, Some(FinishReason::Stop | FinishReason::Length)),
            "second round must succeed (no 400), got {finish:?}"
        );
        assert!(
            !text.is_empty(),
            "expected a final answer after tool result"
        );
    }
}