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
/*
* This file is part of monothink.
*
* Wavething is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* Wavething is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Wavething.
* If not, see <https://www.gnu.org/licenses/>.
*/
use std::{fs, io::Write};
use directories::ProjectDirs;
use rig::completion::Usage;
use tokio::sync::mpsc::{Receiver, Sender};
use crate::{
core::conversation::{Conversation, NotificationType},
llm::LlmMessage,
ui::UiMessage,
};
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct TokenUsage {
pub input: Option<u64>,
pub output: Option<u64>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum SessionMessage {
SubmitPrompt(String),
AgentResponse(String),
AgentReasoning(String),
AgentCompletion(Usage), // Usage is a rig type we we should abstract from. But at this point we need the same information anyhow.
ToolCall {
name: String,
args: serde_json::Value,
},
ToolResult {
output: String,
success: bool,
},
//CancelGeneration,
Error(String),
Warning(String),
QuitRequest,
}
#[derive(Debug)]
pub struct Session {
ui_tx: Sender<UiMessage>,
llm_tx: Sender<LlmMessage>,
rx: Receiver<SessionMessage>,
conversation: Conversation,
token_usage: TokenUsage,
}
impl Session {
pub fn new(
ui_tx: Sender<UiMessage>,
llm_tx: Sender<LlmMessage>,
rx: Receiver<SessionMessage>,
) -> Self {
Self {
ui_tx,
llm_tx,
rx,
conversation: Conversation::new(),
token_usage: TokenUsage::default(),
}
}
pub async fn run(&mut self) {
loop {
let event = self.rx.recv().await;
if let Some(msg) = event {
match msg {
SessionMessage::SubmitPrompt(prompt) => {
let item = self.conversation.add_user_prompt(&prompt);
self.llm_tx
.send(LlmMessage::SubmitPrompt {
prompt,
history: Vec::new(), // @todo send recent history
})
.await
.unwrap();
self.ui_tx
.send(UiMessage::NewConversationItem(item.to_owned()))
.await
.unwrap();
}
SessionMessage::AgentResponse(chunk) => {
let (item, new) = self.conversation.add_assistant_response_chunk(&chunk);
if new {
self.ui_tx
.send(UiMessage::NewConversationItem(item.to_owned()))
.await
.unwrap();
} else {
self.ui_tx
.send(UiMessage::UpdatedConversationItem(item.to_owned()))
.await
.unwrap();
}
}
SessionMessage::AgentReasoning(chunk) => {
let (item, new) = self.conversation.add_assistant_reasoning_chunk(&chunk);
if new {
self.ui_tx
.send(UiMessage::NewConversationItem(item.to_owned()))
.await
.unwrap();
} else {
self.ui_tx
.send(UiMessage::UpdatedConversationItem(item.to_owned()))
.await
.unwrap();
}
}
SessionMessage::AgentCompletion(usage) => {
self.update_token_usage(usage);
self.ui_tx
.send(UiMessage::GenerationFinished(TokenUsage {
input: self.token_usage.input,
output: self.token_usage.output,
}))
.await
.unwrap();
// publish report as system message for analyzing provider behavior
// bypass conversation as this is only for development
let msg = format!(
"Usage: input tokens = {}, output tokens = {}, \
cached input tokens = {}, cached creation input tokens = {}, \
reasoning tokens = {}, tool use prompt tokens = {}, total tokens = {}",
usage.input_tokens,
usage.output_tokens,
usage.cached_input_tokens,
usage.cache_creation_input_tokens,
usage.reasoning_tokens,
usage.tool_use_prompt_tokens,
usage.total_tokens
);
let item = self
.conversation
.add_notification(NotificationType::Info, msg);
self.ui_tx
.send(UiMessage::NewConversationItem(item.to_owned()))
.await
.unwrap();
// We could use this event to mark our messages as complete.
// But as of now a message is complete when a new message arrives.
}
SessionMessage::QuitRequest => {
// @todo send quit to Ui. Ui should not quit itself but send a user request
// to session. Session decided if app should quit or not.
self.llm_tx.send(LlmMessage::Quit).await.unwrap();
// @todo do not quit if changes are unsafed and command is not force exit
if !self.conversation.messages().is_empty() {
// save session
if let Some(proj_dirs) =
ProjectDirs::from("org", "codemonk", "monothink")
{
let mut state_dir = proj_dirs
.state_dir()
.expect("Running on other OS than Linux is not supported.")
.to_path_buf();
state_dir.push("sessions");
state_dir.push(format!("{}.json", self.conversation.id()));
let session_path = state_dir.as_path();
// @todo stream to a writer
let output = serde_json::to_string(&self.conversation)
.expect("Should be able to serealize a session.");
let mut session_file = fs::File::create(session_path)
.expect("Cannot open session file for writing");
let _ = session_file
.write(output.as_bytes())
.expect("Cannot write session to file");
} else {
panic!("Could not read test data from test.json.");
};
}
break;
}
SessionMessage::Error(msg) => {
let item = self
.conversation
.add_notification(NotificationType::Error, msg);
self.ui_tx
.send(UiMessage::NewConversationItem(item.to_owned()))
.await
.unwrap();
}
SessionMessage::Warning(msg) => {
let item = self
.conversation
.add_notification(NotificationType::Warn, msg);
self.ui_tx
.send(UiMessage::NewConversationItem(item.to_owned()))
.await
.unwrap();
}
SessionMessage::ToolCall { name, args } => {
let item = self.conversation.add_tool_invocation(name, args);
self.ui_tx
.send(UiMessage::NewConversationItem(item.to_owned()))
.await
.unwrap();
}
SessionMessage::ToolResult { output, success } => {
let item = self.conversation.add_tool_result(output, success);
self.ui_tx
.send(UiMessage::NewConversationItem(item.to_owned()))
.await
.unwrap();
}
}
}
}
}
fn update_token_usage(&mut self, usage: Usage) {
// assume that OpenAI typical token usage reports,
// i.e. only input and output are reported
if usage.input_tokens > 0 {
self.token_usage.input = Some(self.token_usage.input.unwrap_or(0) + usage.input_tokens);
}
if usage.output_tokens > 0 {
self.token_usage.output =
Some(self.token_usage.output.unwrap_or(0) + usage.output_tokens);
}
}
}