use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use egui::{Key, Modifiers, RichText};
use serde_json::{json, Value};
use bigtext::ai::agent::{Config, Next, Session, Step};
use bigtext::ai::chat::{Event, Message, Reply, Role, Usage};
use bigtext::ai::keys::KeyStore;
use bigtext::ai::privacy::{self, Redact};
use bigtext::ai::profile::Profile;
use bigtext::ai::tools::{self, Change, Kind, Output, Show, Times};
use bigtext::ai::{preset, AiError, Protocol, Provider};
use bigtext::jobs::{self, CancelToken};
use super::ai_settings::{resolve_key, AiConfig, SettingsUi};
use super::i18n::{tr, trf};
use super::BigTextApp;
pub enum Entry {
User(String),
Card(usize),
Answer(String),
Error(String),
Note(String),
}
#[derive(Clone, Debug, PartialEq)]
pub enum State {
Waiting,
Running,
Done,
Failed(String),
Skipped,
Review,
Applied,
Declined,
}
impl State {
fn finished(&self) -> bool {
!matches!(self, State::Waiting | State::Running | State::Review)
}
}
pub struct Card {
pub step: Step,
pub edit: String,
pub state: State,
pub output: Option<Output>,
pub sample: Option<(usize, usize)>,
version: u64,
}
type Started = (Session, Provider, Vec<(u64, String)>);
enum Done {
Started(Result<Started, String>),
Replied(Session, Provider, Result<Reply, AiError>),
Ran(usize, Result<Output, String>),
}
struct Job {
cancel: CancelToken,
slot: Arc<Mutex<Option<Done>>>,
stream: Arc<Mutex<String>>,
thinking: Arc<Mutex<bool>>,
started: Instant,
card: Option<usize>,
}
pub struct Confirm {
session: Session,
provider: Provider,
pub text: String,
pub dont_ask: bool,
}
pub struct AiUi {
pub open: bool,
pub cfg: AiConfig,
pub settings: SettingsUi,
pub store: KeyStore,
pub provider: Option<Provider>,
pub input: String,
pub focus: bool,
hist: Option<usize>,
pub entries: Vec<Entry>,
pub cards: Vec<Card>,
pub doc: Option<u64>,
session: Option<Session>,
turn: Vec<usize>,
queue: VecDeque<usize>,
job: Option<Job>,
pub confirm: Option<Confirm>,
stopped: bool,
pub dont_ask: bool,
pub usage: Usage,
samples: Vec<(u64, String)>,
}
impl Default for AiUi {
fn default() -> Self {
AiUi {
open: false,
cfg: AiConfig::default(),
settings: SettingsUi::default(),
store: KeyStore::for_this_copy(),
provider: None,
input: String::new(),
focus: false,
hist: None,
entries: Vec::new(),
cards: Vec::new(),
doc: None,
session: None,
turn: Vec::new(),
queue: VecDeque::new(),
job: None,
confirm: None,
stopped: false,
dont_ask: true,
usage: Usage::default(),
samples: Vec::new(),
}
}
}
impl AiUi {
pub fn on_config_changed(&mut self) {
self.provider = None;
}
pub fn busy(&self) -> bool {
self.job.is_some() || !self.queue.is_empty()
}
pub fn clear(&mut self) {
if let Some(j) = self.job.take() {
j.cancel.cancel();
}
self.entries.clear();
self.cards.clear();
self.session = None;
self.turn.clear();
self.queue.clear();
self.confirm = None;
self.doc = None;
self.usage = Usage::default();
self.samples.clear();
self.stopped = false;
}
fn is_local(&self) -> bool {
self.cfg.provider().is_some_and(|p| p.is_local())
}
fn privacy(&self) -> privacy::Privacy {
let mut p = self.cfg.privacy.clone();
if self.is_local() {
p.redact = self.cfg.redact_local;
}
p
}
fn auto_run(&self) -> bool {
if self.is_local() {
self.cfg.auto_local
} else {
self.cfg.auto_cloud
}
}
}
fn tool_label(name: &str) -> &'static str {
match name {
"file_profile" => tr("File profile"),
"find_all" => tr("Find all"),
"count" => tr("Count lines"),
"filter_lines" => tr("Filter lines"),
"field_query" => tr("Field query"),
"levels" => tr("Log levels"),
"time_range" => tr("Time range"),
"histogram" => tr("Time histogram"),
"message_patterns" => tr("Message patterns"),
"top_values" => tr("Top values"),
"read_lines" => tr("Read lines"),
"context" => tr("Lines around"),
"time_gaps" => tr("Time gaps"),
"selection" => tr("Selection"),
"go_to_line" => tr("Go to line"),
"highlight" => tr("Highlight"),
"bookmark" => tr("Bookmark lines"),
"save_search" => tr("Save search"),
"replace_all" => tr("Replace all"),
"delete_lines" => tr("Delete lines"),
"replace_lines" => tr("Replace lines"),
"extract_values" => tr("Values of a pattern"),
"bookmarks" => tr("Bookmarked lines"),
"table_rows" => tr("Table rows"),
"column_stats" => tr("Column statistics"),
"group_by" => tr("Rows per value"),
_ => tr("Unknown step"),
}
}
fn result_of(c: &Card) -> Result<Value, String> {
match &c.state {
State::Done => Ok(c
.output
.as_ref()
.map(|o| o.for_model.clone())
.unwrap_or(json!({}))),
State::Failed(e) => Err(e.clone()),
State::Skipped => Ok(json!({"not_run": "the user skipped this step"})),
State::Applied => {
Ok(json!({"applied": true, "changed": c.output.as_ref().and_then(|o| o.n)}))
}
State::Declined => Ok(json!({"applied": false, "note": "the user declined this change"})),
_ => Err("not run".into()),
}
}
fn cost(model: &str, u: &Usage) -> Option<f64> {
let (input, output, cached) = match model.trim() {
"claude-opus-5-5" => (4.0, 20.0, 0.20),
"claude-sonnet-5-5" => (2.0, 10.0, 0.10),
"claude-haiku-5-5" => (0.10, 0.50, 0.01),
_ => return None,
};
Some(
(u.input as f64 * input
+ u.cache_write as f64 * input * 1.25
+ u.cache_read as f64 * cached
+ u.output as f64 * output)
/ 1e6,
)
}
fn short_count(n: u64) -> String {
if n >= 10_000 {
format!("{:.1}k", n as f64 / 1000.0)
} else {
n.to_string()
}
}
fn transcript(system: &str, messages: &[Message]) -> String {
let mut out = format!("[system]\n{system}\n");
for m in messages {
out.push_str(match m.role {
Role::User => "[user]\n",
Role::Assistant => "[assistant]\n",
});
for b in &m.blocks {
match b {
bigtext::ai::chat::Block::Text(t) => out.push_str(t),
bigtext::ai::chat::Block::ToolUse { name, input, .. } => {
out.push_str(&format!("(calls {name} {input})"))
}
bigtext::ai::chat::Block::ToolResult { content, .. } => {
out.push_str(&format!("(result {content})"))
}
bigtext::ai::chat::Block::Opaque(_) => {}
}
out.push('\n');
}
}
out
}
fn line_links(text: &str) -> Vec<(usize, usize, u64)> {
let b = text.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while i < b.len() {
let word_start = i == 0 || !(b[i - 1] as char).is_alphanumeric();
if b[i] == b'L' && word_start && i + 1 < b.len() && b[i + 1].is_ascii_digit() {
let mut j = i + 1;
while j < b.len() && b[j].is_ascii_digit() {
j += 1;
}
let end_ok = j == b.len() || !(b[j] as char).is_alphanumeric();
if end_ok {
if let Ok(n) = text[i + 1..j].parse::<u64>() {
out.push((i, j, n));
}
}
i = j;
} else {
i += 1;
}
}
out
}
impl BigTextApp {
pub(crate) fn open_ask(&mut self) {
if self.ai.open && !self.ai.focus {
self.ai.focus = true;
return;
}
self.ai.open = true;
self.ai.focus = true;
if !self.ai.cfg.enabled() {
self.open_ai_settings();
}
}
pub(crate) fn ai_explain(&mut self) {
if !self
.docs
.get(self.active)
.is_some_and(|d| d.has_selection())
{
self.notify(tr("Select the lines to explain first.").into(), None);
return;
}
self.ai.open = true;
self.ai_ask(tr("Explain the selected text: what it says, the likely cause, and what to check next.").into());
}
pub(crate) fn ai_report(&mut self) {
if self
.docs
.get(self.active)
.is_none_or(|d| d.bookmarks.is_empty())
{
self.notify(
tr("Bookmark the lines that matter first (Ctrl+F2).").into(),
None,
);
return;
}
self.ai.open = true;
self.ai_ask(tr("Write a short incident report in Markdown from the bookmarked lines: what happened and when, the evidence with line numbers, the likely cause, and what to check next.").into());
}
pub(crate) fn ai_ask(&mut self, question: String) {
let question = question.trim().to_string();
if question.is_empty() || self.ai.busy() || self.ai.confirm.is_some() {
return;
}
if !self.ai.cfg.enabled() {
self.open_ai_settings();
self.ai.entries.push(Entry::Note(
tr("Choose a provider in the AI settings first.").into(),
));
return;
}
let Some(d) = self.docs.get(self.active).filter(|d| d.is_ready()) else {
self.ai
.entries
.push(Entry::Note(tr("Open a file first.").into()));
return;
};
if self.ai.doc.is_some() && self.ai.doc != Some(d.id) {
self.ai.clear();
}
self.ai.doc = Some(d.id);
self.ai.stopped = false;
self.ai.cfg.remember(&question);
self.ai.hist = None;
self.persist_state();
self.ai.entries.push(Entry::User(question.clone()));
let Some(provider) = self.ai.provider.clone().or_else(|| self.ai.cfg.provider()) else {
return;
};
if let Some(mut s) = self.ai.session.take() {
s.ask(&question, None);
self.ai_request(s, provider);
return;
}
let conf = self.ai.cfg.conf(&provider.id);
let anthropic = provider.protocol == Protocol::Anthropic;
let cfg = Config {
tools: conf.map(|c| c.tools).unwrap_or(true),
max_steps: self.ai.cfg.steps as usize,
explain: self.ai.cfg.explain,
writes: self.ai.cfg.writes && d.editable(),
effort: anthropic.then_some(self.ai.cfg.effort),
max_tokens: 8192,
language: bigtext::ai::prompt::language_name(super::i18n::lang().code()).into(),
limit: self.ai.cfg.privacy.limit,
};
let (snap, name) = (d.buf.snapshot(), d.title.clone());
let privacy = self.ai.privacy();
let store = self.ai.store.clone();
self.ai_spawn(None, move |cancel, _, _| {
let mut p = provider;
if p.key.is_none() {
if let Some(pr) = preset(&p.id) {
p.key = resolve_key(&store, pr).0;
}
}
if let Err(e) = p.check() {
return Done::Started(Err(e.user_text()));
}
let profile = Profile::build(&snap, &name, cancel);
let mut red = Redact::new(&privacy);
let json = profile.to_json(&mut |s| red.text(s));
let mut s = Session::new(cfg);
s.ask(&question, Some(&json));
Done::Started(Ok((s, p, profile.samples)))
});
}
fn ai_spawn(
&mut self,
card: Option<usize>,
f: impl FnOnce(&CancelToken, &Arc<Mutex<String>>, &Arc<Mutex<bool>>) -> Done + Send + 'static,
) {
let job = Job {
cancel: CancelToken::new(),
slot: Arc::new(Mutex::new(None)),
stream: Arc::new(Mutex::new(String::new())),
thinking: Arc::new(Mutex::new(false)),
started: Instant::now(),
card,
};
let (cancel, slot, stream, thinking, waker) = (
job.cancel.clone(),
job.slot.clone(),
job.stream.clone(),
job.thinking.clone(),
self.waker.clone(),
);
self.ai.job = Some(job);
jobs::spawn("ai", move || {
let d = f(&cancel, &stream, &thinking);
*slot.lock().unwrap() = Some(d);
waker();
});
}
fn ai_request(&mut self, session: Session, provider: Provider) {
let store = self.ai.store.clone();
let journal = self.ai.cfg.privacy.journal;
self.ai_spawn(None, move |cancel, stream, thinking| {
let mut p = provider;
if p.key.is_none() {
if let Some(pr) = preset(&p.id) {
p.key = resolve_key(&store, pr).0;
}
}
if journal {
privacy::log_sent(
&p.id,
&p.model,
&transcript(&session.system, &session.messages),
);
}
let r = p.send(&session.request(), cancel, &mut |e| match e {
Event::Text(t) => {
stream.lock().unwrap().push_str(t);
*thinking.lock().unwrap() = false;
}
Event::Thinking => *thinking.lock().unwrap() = true,
Event::Tool(_) => {}
});
Done::Replied(session, p, r)
});
}
pub(super) fn ai_tick(&mut self) {
let done = self
.ai
.job
.as_ref()
.and_then(|j| j.slot.lock().unwrap().take());
if let Some(d) = done {
self.ai.job = None;
match d {
Done::Started(Ok((s, p, samples))) => {
self.ai.samples = samples;
let cloud = !p.is_local();
if cloud && !self.ai.cfg.asked.contains(&p.id) {
let text = s.messages.first().map(|m| m.text()).unwrap_or_default();
self.ai.confirm = Some(Confirm {
session: s,
provider: p,
text,
dont_ask: true,
});
} else {
self.ai_request(s, p);
}
}
Done::Started(Err(e)) => {
self.ai.entries.push(Entry::Error(e));
self.ai.doc = None;
}
Done::Replied(s, p, r) => self.ai_on_reply(s, p, r),
Done::Ran(i, r) => self.ai_on_ran(i, r),
}
}
if self.ai.job.is_none() {
self.ai_run_next();
}
self.ai_end_turn();
}
fn ai_on_reply(&mut self, mut s: Session, p: Provider, r: Result<Reply, AiError>) {
self.ai.provider = Some(p.clone());
let reply = match r {
Ok(r) => r,
Err(AiError::Cancelled) => {
self.ai.entries.push(Entry::Note(tr("Stopped.").into()));
self.ai.session = Some(s);
return;
}
Err(e) => {
self.ai.entries.push(Entry::Error(e.user_text()));
self.ai.session = Some(s);
return;
}
};
self.ai.usage.add(&reply.usage);
match s.on_reply(&reply) {
Next::Answer(a) => {
if !a.trim().is_empty() {
self.ai.entries.push(Entry::Answer(a));
}
self.ai.session = Some(s);
}
Next::Again => self.ai_request(s, p),
Next::Calls(steps) => {
let auto = self.ai.auto_run();
let version = self.ai_doc().map(|d| d.version).unwrap_or(0);
for step in steps {
let i = self.ai.cards.len();
let state = match &step.call {
Err(e) => State::Failed(e.clone()),
Ok(c) => match c.kind() {
Kind::Read if !auto => State::Waiting,
_ => {
self.ai.queue.push_back(i);
State::Waiting
}
},
};
let sample = step
.call
.as_ref()
.ok()
.and_then(|c| c.pattern())
.and_then(|p| {
let m = bigtext::search::Matcher::new(
&p.query(),
bigtext::encoding::Codec::utf8(),
)
.ok()?;
let hits = self
.ai
.samples
.iter()
.filter(|(_, t)| {
let mut found = false;
m.find_in(
t.as_bytes(),
0,
0,
t.len(),
t.len(),
&mut None,
&mut |_, _| {
found = true;
false
},
);
found
})
.count();
(!self.ai.samples.is_empty()).then_some((hits, self.ai.samples.len()))
});
let edit = step
.call
.as_ref()
.ok()
.and_then(|c| c.editable_text())
.unwrap_or_default();
self.ai.cards.push(Card {
step,
edit,
state,
output: None,
sample,
version,
});
self.ai.entries.push(Entry::Card(i));
self.ai.turn.push(i);
}
self.ai.session = Some(s);
}
}
}
fn ai_doc(&self) -> Option<&super::document::Document> {
let id = self.ai.doc?;
self.docs.iter().find(|d| d.id == id)
}
fn ai_run_next(&mut self) {
while let Some(i) = self.ai.queue.pop_front() {
let Some(card) = self.ai.cards.get(i) else {
continue;
};
if card.state != State::Waiting {
continue;
}
let call = match &card.step.call {
Ok(c) => {
let changed = c.editable_text().is_some_and(|t| t != card.edit);
if changed {
c.with_pattern(&card.edit)
.ok_or_else(|| "cannot change this step".to_string())
.and_then(|c| tools::parse(c.name(), &c.input()))
} else {
Ok(c.clone())
}
}
Err(e) => Err(e.clone()),
};
let call = match call {
Ok(c) => c,
Err(e) => {
self.ai.cards[i].state = State::Failed(e);
continue;
}
};
if call.with_pattern("").is_some()
&& self.ai.cards[i].edit
!= card
.step
.call
.as_ref()
.ok()
.and_then(|c| c.editable_text())
.unwrap_or_default()
{
self.ai.cards[i].step.call = Ok(call.clone());
self.ai.cards[i].step.input = call.input();
}
let Some(d) = self.ai_doc() else {
self.ai.cards[i].state =
State::Failed(tr("The file of this conversation is closed.").into());
continue;
};
let (snap, name, version) = (d.buf.snapshot(), d.title.clone(), d.version);
let selection = d.has_selection().then(|| d.selection());
let bookmarks = d.bookmarks.clone();
let privacy = self.ai.privacy();
self.ai.cards[i].state = State::Running;
self.ai.cards[i].version = version;
self.ai_spawn(Some(i), move |cancel, _, _| {
let mut red = Redact::new(&privacy);
let mut f = |s: &str| red.text(s);
let r = tools::run(
&mut tools::Run {
buf: &snap,
cancel,
name: &name,
selection,
bookmarks: &bookmarks,
redact: &mut f,
},
&call,
);
Done::Ran(i, r)
});
return;
}
}
fn ai_on_ran(&mut self, i: usize, r: Result<Output, String>) {
let Some(card) = self.ai.cards.get_mut(i) else {
return;
};
match r {
Ok(o) => {
let kind = card
.step
.call
.as_ref()
.map(|c| c.kind())
.unwrap_or(Kind::Read);
card.state = if kind == Kind::Write {
State::Review
} else {
State::Done
};
let show = o.show.clone();
card.output = Some(o);
if let Some(s) = show {
if self
.ai_doc()
.is_some_and(|d| self.docs.get(self.active).is_some_and(|a| a.id == d.id))
{
self.ai_show(&s);
}
}
}
Err(e) => card.state = State::Failed(e),
}
}
fn ai_end_turn(&mut self) {
if self.ai.turn.is_empty() || self.ai.job.is_some() {
return;
}
if !self
.ai
.turn
.iter()
.all(|&i| self.ai.cards[i].state.finished())
{
return;
}
let Some(mut s) = self.ai.session.take() else {
return;
};
let results: Vec<(Step, Result<Value, String>)> = self
.ai
.turn
.iter()
.map(|&i| (self.ai.cards[i].step.clone(), result_of(&self.ai.cards[i])))
.collect();
self.ai.turn.clear();
let more = s.give_results(results);
let p = self.ai.provider.clone().or_else(|| self.ai.cfg.provider());
match p {
Some(p) if more && !self.ai.stopped => self.ai_request(s, p),
_ => self.ai.session = Some(s),
}
}
pub(crate) fn ai_stop(&mut self) {
self.ai.stopped = true;
if let Some(j) = self.ai.job.take() {
j.cancel.cancel();
if let Some(i) = j.card {
self.ai.cards[i].state = State::Failed(tr("Stopped.").into());
} else if self.ai.turn.is_empty() {
self.ai.entries.push(Entry::Note(tr("Stopped.").into()));
}
}
self.ai.queue.clear();
for &i in &self.ai.turn {
let c = &mut self.ai.cards[i];
if matches!(c.state, State::Waiting | State::Review) {
c.state = State::Skipped;
}
}
if self.ai.session.is_none() && self.ai.turn.is_empty() {
self.ai.doc = None;
}
self.ai_end_turn();
}
fn ai_range(&mut self, t: &Times) {
match t.pair() {
Some((f, to)) => self.apply_range(f, to),
None if self.range.active.is_some() => self.apply_range(String::new(), String::new()),
None => {}
}
}
fn ai_show(&mut self, show: &Show) {
match show.clone() {
Show::FindAll { query, times } => {
self.ai_range(×);
self.search.query = query;
self.search.open = true;
self.search.in_selection = false;
self.find_all();
}
Show::Filter {
query,
invert,
context,
times,
} => {
self.ai_range(×);
self.search.query = query;
self.search.invert = invert;
self.settings.filter_context = context;
self.start_filter();
}
Show::FieldFilter { query, times } => {
self.ai_range(×);
self.search.invert = false;
self.start_field_filter(&query);
}
Show::Levels { levels, times } => {
self.ai_range(×);
self.filter_levels(levels);
}
Show::TimeRange(t) => self.ai_range(&t),
Show::Histogram(q) => {
self.timeline.count = match q {
Some(q) => {
self.search.query = q;
super::timeline::Count::Search
}
None => super::timeline::Count::Nothing,
};
self.timeline.open = true;
self.start_timeline();
}
Show::Patterns(_) => self.open_patterns(),
Show::TopValues(_) => {}
Show::Gaps(ms) => {
self.gaps.min_secs = ms as f64 / 1000.0;
self.open_gaps();
}
Show::Line(n) => self.ai_goto(n),
Show::Highlight(q) => self.add_mark(q),
Show::Bookmarks(lines) => {
if let Some(d) = self.docs.get_mut(self.active) {
for n in lines {
if let Some((off, _)) = d.buf.line_start(n.saturating_sub(1)) {
let ls = bigtext::filter::line_start_at(&d.buf, off).unwrap_or(off);
if let Err(i) = d.bookmarks.binary_search(&ls) {
d.bookmarks.insert(i, ls);
}
}
}
}
}
Show::SaveSearch {
name,
query,
invert,
} => {
self.settings.saved.retain(|s| s.name != name);
self.settings
.saved
.push(super::saved_searches::SavedSearch {
name,
query,
invert,
column: None,
});
self.persist_state();
}
}
}
pub(crate) fn ai_bookmark(&mut self, lines: Vec<u64>) {
let id = self.ai.doc;
if let Some(di) = self.docs.iter().position(|d| Some(d.id) == id) {
self.active = di;
let n = lines.len();
self.ai_show(&Show::Bookmarks(lines));
self.notify(
trf(
"{n} lines bookmarked; F2 jumps between them.",
&[("n", &n.to_string())],
),
None,
);
}
}
fn ai_goto(&mut self, n: u64) {
let Some(id) = self.ai.doc else { return };
if let Some(i) = self.docs.iter().position(|d| d.id == id) {
self.active = i;
self.docs[i].goto_line(n);
}
}
pub(crate) fn ai_apply(&mut self, i: usize) {
let Some(card) = self.ai.cards.get(i) else {
return;
};
let Some(change) = card.output.as_ref().and_then(|o| o.change.clone()) else {
return;
};
let version = card.version;
let Some(id) = self.ai.doc else { return };
let Some(di) = self.docs.iter().position(|d| d.id == id) else {
self.ai.cards[i].state =
State::Failed(tr("The file of this conversation is closed.").into());
return;
};
if self.docs[di].version != version {
self.ai.cards[i].state = State::Waiting;
self.ai.queue.push_back(i);
self.ai.entries.push(Entry::Note(
tr("The file changed since the preview; it is made again.").into(),
));
return;
}
self.active = di;
match change {
Change::ReplaceAll { query, with, .. } => {
self.search.query = query;
self.search.replace_with = with;
self.search.in_selection = false;
self.replace_all();
}
Change::ReplaceRange { range, text } => {
self.docs[di].edit(range, text.as_bytes(), super::document::EditKind::Other);
}
}
self.ai.cards[i].state = State::Applied;
}
pub(super) fn ai_confirm_window(&mut self, ctx: &egui::Context) {
let Some(c) = &mut self.ai.confirm else {
return;
};
let mut send = None;
let name = preset(&c.provider.id).map(|p| p.name).unwrap_or("?");
egui::Window::new(tr("What will be sent"))
.collapsible(false)
.resizable(true)
.default_width(560.0)
.anchor(egui::Align2::CENTER_CENTER, egui::vec2(0.0, 0.0))
.show(ctx, |ui| {
ui.label(trf(
"This is the first request to {provider}. BigText sends it this text (secrets hidden), BigText's instructions and the list of its tools, never the file. Later requests add the steps' short results.",
&[("provider", name)],
));
ui.label(
RichText::new(trf(
"{bytes} bytes, about {tokens} tokens of file text and question.",
&[
("bytes", &c.text.len().to_string()),
("tokens", &privacy::tokens(c.text.len()).to_string()),
],
))
.weak(),
);
egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {
let mut t = c.text.as_str();
ui.add(egui::TextEdit::multiline(&mut t).font(egui::TextStyle::Monospace).desired_width(f32::INFINITY));
});
ui.checkbox(&mut c.dont_ask, tr("Do not ask again for this provider"));
ui.horizontal(|ui| {
if ui.button(tr("Send")).clicked() {
send = Some(true);
}
if ui.button(tr("Cancel")).clicked() {
send = Some(false);
}
});
});
match send {
Some(true) => {
let c = self.ai.confirm.take().unwrap();
if c.dont_ask {
self.ai.cfg.asked.push(c.provider.id.clone());
self.persist_state();
}
self.ai_request(c.session, c.provider);
}
Some(false) => {
self.ai.confirm = None;
self.ai.doc = None;
self.ai
.entries
.push(Entry::Note(tr("Nothing was sent.").into()));
}
None => {}
}
}
pub(super) fn ai_panel(&mut self, ui: &mut egui::Ui) {
let mut close = false;
let mut new = false;
let mut settings = false;
ui.horizontal(|ui| {
ui.strong(tr("Ask BigText"));
match self.ai.cfg.provider() {
Some(p) => {
let badge = if p.is_local() {
tr("local")
} else {
tr("cloud")
};
ui.label(
RichText::new(format!("{} · {badge}", p.model.trim()))
.weak()
.small(),
)
.on_hover_text(preset(&p.id).map(|x| x.name).unwrap_or_default());
}
None => {
ui.label(RichText::new(tr("not set up")).weak().small());
}
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.small_button("×").on_hover_text(tr("Close")).clicked() {
close = true;
}
if ui
.small_button("⚙")
.on_hover_text(tr("AI settings"))
.clicked()
{
settings = true;
}
if ui
.small_button("⟲")
.on_hover_text(tr("New conversation"))
.clicked()
{
new = true;
}
});
});
ui.separator();
let busy = self.ai.busy();
let mut submit = false;
let mut stop = false;
ui.with_layout(egui::Layout::bottom_up(egui::Align::LEFT), |ui| {
let u = self.ai.usage;
if u.total_input() + u.output > 0 {
let mut s = trf(
"{in} tokens in, {out} out",
&[("in", &short_count(u.total_input())), ("out", &short_count(u.output))],
);
let model = self.ai.cfg.provider().map(|p| p.model).unwrap_or_default();
if let Some(c) = cost(&model, &u) {
s.push_str(&format!(" · ~${c:.3}"));
}
ui.label(RichText::new(s).weak().small());
}
ui.horizontal(|ui| {
if busy {
if ui.button(tr("Stop")).clicked() {
stop = true;
}
ui.spinner();
} else if ui.add_enabled(!self.ai.input.trim().is_empty(), egui::Button::new(tr("Ask"))).clicked() {
submit = true;
}
});
let id = egui::Id::new("ai-input");
let focused = ui.memory(|m| m.has_focus(id));
if focused && !busy {
let (enter, up, down) = ui.input_mut(|i| {
(
i.consume_key(Modifiers::NONE, Key::Enter),
self.ai.input.is_empty() || self.ai.hist.is_some(),
self.ai.hist.is_some(),
)
});
if enter {
submit = true;
}
if up && ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::ArrowUp)) {
let n = self.ai.hist.map(|h| h + 1).unwrap_or(0);
if let Some(h) = self.ai.cfg.history.get(n) {
self.ai.input = h.clone();
self.ai.hist = Some(n);
}
}
if down && ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::ArrowDown)) {
match self.ai.hist {
Some(0) | None => {
self.ai.hist = None;
self.ai.input.clear();
}
Some(h) => {
self.ai.hist = Some(h - 1);
self.ai.input = self.ai.cfg.history[h - 1].clone();
}
}
}
}
let r = ui.add(
egui::TextEdit::multiline(&mut self.ai.input)
.id(id)
.desired_rows(2)
.desired_width(f32::INFINITY)
.hint_text(tr("Ask about this file: “find all errors”, “requests slower than 2 s”… (Enter sends)")),
);
if self.ai.focus {
r.request_focus();
self.ai.focus = false;
}
ui.separator();
ui.with_layout(egui::Layout::top_down(egui::Align::LEFT), |ui| {
egui::ScrollArea::vertical()
.auto_shrink([false, false])
.stick_to_bottom(true)
.show(ui, |ui| self.ai_entries(ui));
});
});
if submit {
let q = std::mem::take(&mut self.ai.input);
self.ai_ask(q);
}
if stop {
self.ai_stop();
}
if new {
self.ai.clear();
}
if settings {
self.open_ai_settings();
}
if close {
self.ai.open = false;
}
}
fn ai_entries(&mut self, ui: &mut egui::Ui) {
if self.ai.entries.is_empty() {
ui.label(RichText::new(tr("Ask in your own words. BigText turns the request into its own searches and filters, runs them on this computer and shows the results where they always appear. The model sees only the file's first lines and short results.")).weak());
ui.add_space(6.0);
for ex in [
tr("Find all errors"),
tr("Which messages repeat most?"),
tr("When did the errors start?"),
tr("Explain the selected lines"),
] {
if ui.link(ex).clicked() {
self.ai.input = ex.to_string();
self.ai.focus = true;
}
}
}
if let Some(id) = self.ai.doc {
if self.docs.get(self.active).is_some_and(|d| d.id != id) {
let title = self.ai_doc().map(|d| d.title.clone()).unwrap_or_default();
ui.label(RichText::new(trf("This conversation is about {file}. A new question starts one about this file.", &[("file", &title)])).weak().small());
}
}
let mut act: Option<(usize, &'static str)> = None;
let mut goto = None;
let mut bookmark: Option<Vec<u64>> = None;
let mut new_tab: Option<String> = None;
let mut dont_ask = self.ai.dont_ask;
let mut fill = None;
for e in &self.ai.entries {
match e {
Entry::User(q) => {
ui.add_space(6.0);
egui::Frame::new()
.fill(super::theme::faint_fill(ui.visuals()))
.corner_radius(4.0)
.inner_margin(6.0)
.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.label(RichText::new(q).strong());
});
}
Entry::Card(i) => {
if let Some(c) = self.ai.cards.get(*i) {
let offer = !self.ai.is_local()
&& !self.ai.cfg.auto_cloud
&& c.state == State::Waiting
&& c.step.call.as_ref().is_ok_and(|x| x.kind() == Kind::Read);
let ask = if offer { Some(&mut dont_ask) } else { None };
card_ui(ui, *i, c, &mut act, &mut fill, ask);
}
}
Entry::Answer(a) => {
ui.add_space(4.0);
answer_ui(ui, a, &mut goto);
let lines: Vec<u64> = line_links(a).into_iter().map(|l| l.2).collect();
ui.horizontal(|ui| {
if !lines.is_empty()
&& ui
.small_button(tr("Bookmark these lines"))
.on_hover_text(tr("The lines this answer names, as bookmarks (F2 jumps between them)"))
.clicked()
{
bookmark = Some(lines);
}
if ui.small_button(tr("Copy")).clicked() {
ui.ctx().copy_text(a.clone());
}
if ui
.small_button(tr("Open in a new tab"))
.on_hover_text(tr("The answer as a new document, to edit and save (a report, for example)"))
.clicked()
{
new_tab = Some(a.clone());
}
});
}
Entry::Error(e) => {
ui.colored_label(ui.visuals().error_fg_color, e);
}
Entry::Note(n) => {
ui.label(RichText::new(n).weak().italics());
}
}
}
if let Some(j) = &self.ai.job {
if j.card.is_none() {
let text = j.stream.lock().unwrap().clone();
let thinking = *j.thinking.lock().unwrap();
ui.horizontal(|ui| {
ui.spinner();
let secs = j.started.elapsed().as_secs();
let what = if thinking && text.is_empty() {
tr("Thinking…")
} else {
tr("Waiting for the model…")
};
ui.label(RichText::new(format!("{what} {secs} s")).weak());
});
if !text.is_empty() {
answer_ui(ui, &text, &mut goto);
}
ui.ctx()
.request_repaint_after(std::time::Duration::from_millis(250));
}
}
self.ai.dont_ask = dont_ask;
if let Some((i, what)) = act {
match what {
"run" => {
if let Some(c) = self.ai.cards.get(i) {
if c.state == State::Waiting {
self.ai.queue.push_back(i);
}
}
if !self.ai.is_local() && !self.ai.cfg.auto_cloud && dont_ask {
self.ai.cfg.auto_cloud = true;
self.persist_state();
let rest: Vec<usize> = self
.ai
.turn
.iter()
.copied()
.filter(|&k| {
k != i
&& self.ai.cards[k].state == State::Waiting
&& self.ai.cards[k]
.step
.call
.as_ref()
.is_ok_and(|x| x.kind() == Kind::Read)
})
.collect();
self.ai.queue.extend(rest);
}
}
"skip" => self.ai.cards[i].state = State::Skipped,
"apply" => self.ai_apply(i),
"decline" => self.ai.cards[i].state = State::Declined,
"save" => {
let question = self.ai.entries[..self
.ai
.entries
.iter()
.position(|e| matches!(e, Entry::Card(k) if *k == i))
.unwrap_or(0)]
.iter()
.rev()
.find_map(|e| match e {
Entry::User(q) => Some(q.clone()),
_ => None,
})
.unwrap_or_default();
let call = self.ai.cards[i].step.call.clone();
if let Some(p) = call.as_ref().ok().and_then(|c| c.pattern()) {
let mut name: String = question.chars().take(40).collect();
if name.trim().is_empty() {
name = p.text.chars().take(40).collect();
}
let invert = matches!(
call,
Ok(tools::Call::Count { invert: true, .. }
| tools::Call::FilterLines { invert: true, .. })
);
self.ai_show(&Show::SaveSearch {
name: name.replace('|', "/"),
query: p.query(),
invert,
});
self.notify(
trf(
"Saved as “{name}” (★ in the search bar).",
&[("name", &name)],
),
None,
);
}
}
"show" => {
if let Some(s) = self.ai.cards[i]
.output
.as_ref()
.and_then(|o| o.show.clone())
{
let id = self.ai.doc;
if let Some(di) = self.docs.iter().position(|d| Some(d.id) == id) {
self.active = di;
}
self.ai_show(&s);
}
}
_ => {}
}
}
if let Some((i, text)) = fill {
if let Some(c) = self.ai.cards.get_mut(i) {
c.edit = text;
}
}
if let Some(n) = goto {
self.ai_goto(n);
}
if let Some(lines) = bookmark {
self.ai_bookmark(lines);
}
if let Some(text) = new_tab {
self.new_doc();
if let Some(d) = self.docs.get_mut(self.active) {
d.edit(0..0, text.as_bytes(), super::document::EditKind::Other);
d.lang = Some(crate::view::highlight::Lang::Markdown);
}
}
}
}
fn card_ui(
ui: &mut egui::Ui,
i: usize,
c: &Card,
act: &mut Option<(usize, &'static str)>,
fill: &mut Option<(usize, String)>,
dont_ask: Option<&mut bool>,
) {
ui.add_space(3.0);
egui::Frame::group(ui.style())
.inner_margin(6.0)
.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
let (icon, color) = match &c.state {
State::Done | State::Applied => ("✔", super::theme::ok_text(ui)),
State::Failed(_) => ("⚠", ui.visuals().error_fg_color),
State::Running => ("…", ui.visuals().text_color()),
State::Review => ("✎", super::theme::warn_text(ui)),
_ => ("•", ui.visuals().weak_text_color()),
};
ui.label(RichText::new(icon).color(color));
ui.strong(tool_label(&c.step.name));
if c.state == State::Running {
ui.spinner();
}
if let Some(o) = &c.output {
let n = o.n.map(super::filter_panel::fmt_count).unwrap_or_default();
ui.label(RichText::new(trf(tr_summary(o.summary), &[("n", &n)])).weak());
}
});
if !c.step.note.trim().is_empty() && c.step.note.len() < 400 {
ui.label(RichText::new(c.step.note.trim()).weak().italics().small());
}
let editable = c.state == State::Waiting
&& c.step
.call
.as_ref()
.is_ok_and(|x| x.editable_text().is_some());
if editable {
let mut t = c.edit.clone();
if ui
.add(
egui::TextEdit::singleline(&mut t)
.font(egui::TextStyle::Monospace)
.desired_width(f32::INFINITY),
)
.changed()
{
*fill = Some((i, t));
}
} else if let Ok(call) = &c.step.call {
let args = call.input();
let text = match call.editable_text() {
Some(t) => t,
None => args.to_string(),
};
if text != "{}" {
ui.label(RichText::new(text).monospace().small());
}
let mut flags = Vec::new();
if args["regex"] == true {
flags.push(tr("regular expression"));
}
if args["ignore_case"] == true {
flags.push(tr("ignore case"));
}
if args["whole_word"] == true {
flags.push(tr("whole words"));
}
if args["invert"] == true {
flags.push(tr("lines without a match"));
}
let mut f: Vec<String> = flags.iter().map(|s| s.to_string()).collect();
let (a, b) = (args["from"].as_str(), args["to"].as_str());
if a.is_some() || b.is_some() {
f.push(format!("{} – {}", a.unwrap_or("…"), b.unwrap_or("…")));
}
if !f.is_empty() {
ui.label(RichText::new(f.join(" · ")).weak().small());
}
}
if let Some((hits, of)) = c.sample {
if matches!(c.state, State::Waiting | State::Running) {
ui.label(
RichText::new(trf(
"Matches {hits} of the file's first {of} lines.",
&[("hits", &hits.to_string()), ("of", &of.to_string())],
))
.weak()
.small(),
);
}
}
if let State::Failed(e) = &c.state {
ui.colored_label(ui.visuals().error_fg_color, RichText::new(e).small());
}
if let Some(o) = &c.output {
if !o.preview.is_empty()
&& matches!(c.state, State::Review | State::Applied | State::Declined)
{
for (line, before, after) in o.preview.iter().take(5) {
ui.label(RichText::new(format!("L{line}")).weak().small());
ui.label(
RichText::new(before)
.monospace()
.small()
.strikethrough()
.color(ui.visuals().error_fg_color),
);
ui.label(
RichText::new(after)
.monospace()
.small()
.color(super::theme::ok_text(ui)),
);
}
}
}
ui.horizontal(|ui| match &c.state {
State::Waiting => {
if ui.button(tr("Run")).clicked() {
*act = Some((i, "run"));
}
if ui.button(tr("Skip")).clicked() {
*act = Some((i, "skip"));
}
if let Some(d) = dont_ask {
ui.checkbox(d, tr("From now on, run steps that only read without asking"))
.on_hover_text(tr("They only read the file and send its short results; steps that change it always wait for Apply (AI settings)"));
}
}
State::Review => {
if ui
.button(tr("Apply"))
.on_hover_text(tr("Make this change (Edit → Undo takes it back)"))
.clicked()
{
*act = Some((i, "apply"));
}
if ui.button(tr("Cancel")).clicked() {
*act = Some((i, "decline"));
}
}
State::Applied => {
ui.label(RichText::new(tr("Applied.")).weak().small());
}
State::Declined => {
ui.label(RichText::new(tr("Not applied.")).weak().small());
}
State::Skipped => {
ui.label(RichText::new(tr("Skipped.")).weak().small());
}
State::Done => {
if c.output.as_ref().is_some_and(|o| o.show.is_some())
&& ui.small_button(tr("Show again")).clicked()
{
*act = Some((i, "show"));
}
let searches = c
.step
.call
.as_ref()
.is_ok_and(|x| x.pattern().is_some() && x.kind() == Kind::Read);
if searches
&& ui
.small_button("★")
.on_hover_text(tr("Save this search (★ in the search bar)"))
.clicked()
{
*act = Some((i, "save"));
}
}
_ => {}
});
});
}
fn tr_summary(s: &'static str) -> &'static str {
match s {
"{n} matches" => tr("{n} matches"),
"{n} lines" => tr("{n} lines"),
"{n} lines in the range" => tr("{n} lines in the range"),
"{n} bars" => tr("{n} bars"),
"{n} message patterns" => tr("{n} message patterns"),
"{n} values" => tr("{n} values"),
"{n} rows" => tr("{n} rows"),
"{n} groups" => tr("{n} groups"),
"{n} time gaps" => tr("{n} time gaps"),
"{n} bookmarks" => tr("{n} bookmarks"),
"{n} lines to change" => tr("{n} lines to change"),
"{n} lines to delete" => tr("{n} lines to delete"),
"{n} matches to replace" => tr("{n} matches to replace"),
"Line {n}" => tr("Line {n}"),
"File profile" => tr("File profile"),
"Highlighted" => tr("Highlighted"),
"Saved" => tr("Saved"),
other => other,
}
}
fn answer_ui(ui: &mut egui::Ui, text: &str, goto: &mut Option<u64>) {
for para in text.split('\n') {
if para.trim().is_empty() {
ui.add_space(2.0);
continue;
}
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
let links = line_links(para);
let mut at = 0;
let mut pieces: Vec<(&str, Option<u64>)> = Vec::new();
for (s, e, n) in links {
if s > at {
pieces.push((¶[at..s], None));
}
pieces.push((¶[s..e], Some(n)));
at = e;
}
if at < para.len() {
pieces.push((¶[at..], None));
}
for (t, link) in pieces {
match link {
Some(n) => {
if ui.link(t).on_hover_text(tr("Go to this line")).clicked() {
*goto = Some(n);
}
}
None => styled(ui, t),
}
}
});
}
}
fn styled(ui: &mut egui::Ui, t: &str) {
let mut bold = false;
for (k, part) in t.split("**").enumerate() {
if k > 0 {
bold = !bold;
}
for (j, piece) in part.split('`').enumerate() {
if piece.is_empty() {
continue;
}
let mut r = RichText::new(piece);
if j % 2 == 1 {
r = r.monospace();
}
if bold {
r = r.strong();
}
ui.label(r);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_links_in_answers() {
assert_eq!(
line_links("See L12 and L1204, not FL3 or L5x."),
vec![(4, 7, 12), (12, 17, 1204)]
);
assert_eq!(line_links("L1"), vec![(0, 2, 1)]);
assert!(line_links("Level 5").is_empty());
}
#[test]
fn costs() {
let u = Usage {
input: 1_000_000,
output: 100_000,
cache_read: 0,
cache_write: 0,
};
assert!((cost("claude-opus-5-5", &u).unwrap() - 6.0).abs() < 1e-9);
assert_eq!(cost("gpt-x", &u), None);
assert_eq!(short_count(12_345), "12.3k");
}
}