leejunyoung5819 handmade-dataset-creator
공개고품질 LLM 데이터셋 수제작을 위한 생산성 도구
| 1 | use eframe::egui::{ |
| 2 | self, Align, Area, Button, Color32, ComboBox, Frame, Id, Key, Layout, Modal, Modifiers, Order, Pos2, RichText, |
| 3 | ScrollArea, Sense, TextEdit, TextStyle, TextWrapMode, ViewportCommand, WidgetText, vec2, |
| 4 | }; |
| 5 | use handmade_dataset_creator::document::Document; |
| 6 | use crate::markup_ui; |
| 7 | use crate::tools_ui::{self, LibraryEditor, LibraryOutcome}; |
| 8 | use handmade_dataset_creator::model::{Conversation, Message, Role}; |
| 9 | use handmade_dataset_creator::recent::RecentFiles; |
| 10 | use handmade_dataset_creator::tools::{self, ToolDef, ToolLibrary}; |
| 11 | use std::collections::BTreeSet; |
| 12 | use std::path::{Path, PathBuf}; |
| 13 | |
| 14 | // --------------------------------------------------------------------------- |
| 15 | // 행동 (퀵 메뉴에서 검색/실행 가능한 명령) |
| 16 | // --------------------------------------------------------------------------- |
| 17 | |
| 18 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 19 | enum Action { |
| 20 | NewConversation, |
| 21 | DeleteConversation, |
| 22 | Undo, |
| 23 | Redo, |
| 24 | Save, |
| 25 | Load, |
| 26 | SaveAs, |
| 27 | NewFile, |
| 28 | AddMessage, |
| 29 | EditMessage, |
| 30 | DuplicateMessages, |
| 31 | MoveMessagesUp, |
| 32 | MoveMessagesDown, |
| 33 | DeleteMessages, |
| 34 | ToolLibrary, |
| 35 | CollectTools, |
| 36 | } |
| 37 | |
| 38 | impl Action { |
| 39 | /// 퀵 메뉴(` 키)에 나오는 순서. |
| 40 | const QUICK: [Action; 16] = [ |
| 41 | Action::NewConversation, |
| 42 | Action::DeleteConversation, |
| 43 | Action::Undo, |
| 44 | Action::Redo, |
| 45 | Action::Save, |
| 46 | Action::Load, |
| 47 | Action::SaveAs, |
| 48 | Action::NewFile, |
| 49 | Action::AddMessage, |
| 50 | Action::EditMessage, |
| 51 | Action::DuplicateMessages, |
| 52 | Action::MoveMessagesUp, |
| 53 | Action::MoveMessagesDown, |
| 54 | Action::DeleteMessages, |
| 55 | Action::ToolLibrary, |
| 56 | Action::CollectTools, |
| 57 | ]; |
| 58 | |
| 59 | fn label(self) -> &'static str { |
| 60 | match self { |
| 61 | Action::NewConversation => "대화 생성 (Create Conversation)", |
| 62 | Action::DeleteConversation => "대화 삭제 (Delete Conversation)", |
| 63 | Action::Undo => "되돌리기 (Undo)", |
| 64 | Action::Redo => "다시하기 (Redo)", |
| 65 | Action::Save => "저장 (Save)", |
| 66 | Action::Load => "불러오기 (Load)", |
| 67 | Action::SaveAs => "다른 이름으로 저장 (Save As)", |
| 68 | Action::NewFile => "새 파일 (New File)", |
| 69 | Action::AddMessage => "메시지 추가 (Add Message)", |
| 70 | Action::EditMessage => "메시지 수정 (Edit Message)", |
| 71 | Action::DuplicateMessages => "메시지 복제 (Duplicate Messages)", |
| 72 | Action::MoveMessagesUp => "메시지 위로 (Move Messages Up)", |
| 73 | Action::MoveMessagesDown => "메시지 아래로 (Move Messages Down)", |
| 74 | Action::DeleteMessages => "메시지 삭제 (Delete Messages)", |
| 75 | Action::ToolLibrary => "도구 라이브러리 (Tool Library)", |
| 76 | Action::CollectTools => "데이터셋에서 도구 가져오기 (Collect Tools)", |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | fn shortcut(self) -> &'static str { |
| 81 | match self { |
| 82 | Action::Undo => "Ctrl+Z", |
| 83 | Action::Redo => "Ctrl+Shift+Z", |
| 84 | Action::Save => "Ctrl+S", |
| 85 | Action::SaveAs => "Ctrl+Shift+S", |
| 86 | Action::Load => "Ctrl+O", |
| 87 | Action::AddMessage => "Ctrl+A", |
| 88 | Action::EditMessage => "더블클릭 / Enter", |
| 89 | Action::DuplicateMessages => "Ctrl+D", |
| 90 | Action::MoveMessagesUp => "Ctrl+↑", |
| 91 | Action::MoveMessagesDown => "Ctrl+↓", |
| 92 | Action::DeleteMessages | Action::DeleteConversation => "Del", |
| 93 | Action::NewConversation | Action::NewFile | Action::ToolLibrary | Action::CollectTools => "", |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | fn matches(self, query: &str) -> bool { |
| 98 | let q: String = query.chars().filter(|c| !c.is_whitespace()).flat_map(char::to_lowercase).collect(); |
| 99 | if q.is_empty() { |
| 100 | return true; |
| 101 | } |
| 102 | let label: String = self.label().chars().filter(|c| !c.is_whitespace()).flat_map(char::to_lowercase).collect(); |
| 103 | label.contains(&q) |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | // --------------------------------------------------------------------------- |
| 108 | // 상태 |
| 109 | // --------------------------------------------------------------------------- |
| 110 | |
| 111 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 112 | enum Focus { |
| 113 | Sidebar, |
| 114 | Messages, |
| 115 | } |
| 116 | |
| 117 | /// "저장되지 않은 변경사항" 확인 뒤에 이어서 할 일. |
| 118 | #[derive(Clone, PartialEq, Eq)] |
| 119 | enum Pending { |
| 120 | Load, |
| 121 | /// 최근 파일 목록에서 고른 파일 열기. |
| 122 | Open(PathBuf), |
| 123 | NewFile, |
| 124 | Quit, |
| 125 | } |
| 126 | |
| 127 | #[derive(Clone, Copy)] |
| 128 | enum EditTarget { |
| 129 | Insert(usize), |
| 130 | Edit(usize), |
| 131 | } |
| 132 | |
| 133 | struct MessageEditor { |
| 134 | conv: usize, |
| 135 | target: EditTarget, |
| 136 | msg: Message, |
| 137 | focus_content: bool, |
| 138 | /// 이 메시지 앞에 있는 tools 메시지들의 도구. 없으면 None(→ 라이브러리 기준). |
| 139 | conv_tools: Option<Vec<ToolDef>>, |
| 140 | /// 직전 assistant의 도구 호출 (id, 이름). |
| 141 | call_choices: Vec<(String, String)>, |
| 142 | /// tools 메시지: JSON 직접 편집 탭인지. |
| 143 | tools_json_tab: bool, |
| 144 | /// 직전 assistant 호출 중 아직 tool 결과가 없는 id (역할을 tool로 바꿀 때 자동 입력). |
| 145 | unanswered: Option<String>, |
| 146 | } |
| 147 | |
| 148 | /// 메시지 편집 창에 필요한 주변 정보: 앞쪽 tools 메시지의 도구들, 직전 assistant 호출들, 아직 응답 안 된 호출 id. |
| 149 | struct EditorContext { |
| 150 | conv_tools: Option<Vec<ToolDef>>, |
| 151 | call_choices: Vec<(String, String)>, |
| 152 | unanswered: Option<String>, |
| 153 | } |
| 154 | |
| 155 | fn editor_context(conv: &Conversation, pos: usize) -> EditorContext { |
| 156 | let before = &conv.messages[..pos.min(conv.messages.len())]; |
| 157 | let mut conv_tools: Option<Vec<ToolDef>> = None; |
| 158 | for m in before.iter().filter(|m| m.role == Role::Tools) { |
| 159 | if let Ok(list) = tools::parse_tool_list(&m.content) { |
| 160 | let all = conv_tools.get_or_insert_with(Vec::new); |
| 161 | for t in list { |
| 162 | if !all.iter().any(|x| x.name == t.name) { |
| 163 | all.push(t); |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | } |
| 168 | let mut choices = Vec::new(); |
| 169 | let mut unanswered = None; |
| 170 | if let Some(ai) = before.iter().rposition(|m| m.role == Role::Assistant && !m.tool_calls.is_empty()) { |
| 171 | choices = before[ai].tool_calls.iter().map(|t| (t.id.clone(), t.name.clone())).collect(); |
| 172 | let answered: Vec<&str> = before[ai + 1..] |
| 173 | .iter() |
| 174 | .filter(|m| m.role == Role::Tool) |
| 175 | .map(|m| m.tool_call_id.as_str()) |
| 176 | .collect(); |
| 177 | unanswered = choices |
| 178 | .iter() |
| 179 | .find(|(id, _)| !answered.contains(&id.as_str())) |
| 180 | .or(choices.last()) |
| 181 | .map(|(id, _)| id.clone()); |
| 182 | } |
| 183 | EditorContext { conv_tools, call_choices: choices, unanswered } |
| 184 | } |
| 185 | |
| 186 | struct QuickMenu { |
| 187 | pos: Pos2, |
| 188 | query: String, |
| 189 | selected: usize, |
| 190 | focus_input: bool, |
| 191 | } |
| 192 | |
| 193 | pub struct App { |
| 194 | doc: Document, |
| 195 | current: Option<usize>, |
| 196 | conv_sel: BTreeSet<usize>, |
| 197 | conv_anchor: Option<usize>, |
| 198 | msg_sel: BTreeSet<usize>, |
| 199 | msg_anchor: Option<usize>, |
| 200 | focus: Focus, |
| 201 | editor: Option<MessageEditor>, |
| 202 | quick: Option<QuickMenu>, |
| 203 | pending: Option<Pending>, |
| 204 | error: Option<String>, |
| 205 | status: String, |
| 206 | scroll_to_current: bool, |
| 207 | allow_close: bool, |
| 208 | last_title: String, |
| 209 | library: ToolLibrary, |
| 210 | library_editor: Option<LibraryEditor>, |
| 211 | recent: RecentFiles, |
| 212 | } |
| 213 | |
| 214 | impl App { |
| 215 | pub fn new(cc: &eframe::CreationContext<'_>, initial: Option<PathBuf>) -> Self { |
| 216 | // 창/모달/메뉴/팝업의 fade, 접기 애니메이션 등을 모두 없애고 즉시 표시한다. |
| 217 | // (egui의 UI 애니메이션은 전부 Style::animation_time을 따른다.) |
| 218 | cc.egui_ctx.all_styles_mut(apply_style); |
| 219 | let mut app = App { |
| 220 | doc: Document::new(), |
| 221 | current: None, |
| 222 | conv_sel: BTreeSet::new(), |
| 223 | conv_anchor: None, |
| 224 | msg_sel: BTreeSet::new(), |
| 225 | msg_anchor: None, |
| 226 | focus: Focus::Sidebar, |
| 227 | editor: None, |
| 228 | quick: None, |
| 229 | pending: None, |
| 230 | error: None, |
| 231 | status: "` 키로 퀵 메뉴를 열 수 있습니다.".into(), |
| 232 | scroll_to_current: false, |
| 233 | allow_close: false, |
| 234 | last_title: String::new(), |
| 235 | library: ToolLibrary::default(), |
| 236 | library_editor: None, |
| 237 | // 테스트에서는 사용자 설정 파일을 건드리지 않는다. |
| 238 | recent: RecentFiles::load(if cfg!(test) { None } else { RecentFiles::default_store() }), |
| 239 | }; |
| 240 | if let Some(path) = initial { |
| 241 | if path.exists() { |
| 242 | app.open_path(&path); |
| 243 | } else { |
| 244 | // 없는 파일을 인자로 주면 그 경로를 저장 위치로 쓰는 새 문서로 시작한다. |
| 245 | app.doc.path = Some(path); |
| 246 | } |
| 247 | } |
| 248 | app |
| 249 | } |
| 250 | |
| 251 | fn overlay_open(&self) -> bool { |
| 252 | self.editor.is_some() |
| 253 | || self.quick.is_some() |
| 254 | || self.pending.is_some() |
| 255 | || self.error.is_some() |
| 256 | || self.library_editor.is_some() |
| 257 | } |
| 258 | |
| 259 | /// 데이터셋 또는 도구 라이브러리에 저장 안 된 변경이 있는지. |
| 260 | fn is_dirty(&self) -> bool { |
| 261 | self.doc.is_dirty() || self.library.dirty |
| 262 | } |
| 263 | |
| 264 | fn file_name(&self) -> String { |
| 265 | self.doc |
| 266 | .path |
| 267 | .as_ref() |
| 268 | .and_then(|p| p.file_name()) |
| 269 | .map(|n| n.to_string_lossy().into_owned()) |
| 270 | .unwrap_or_else(|| "제목 없음".into()) |
| 271 | } |
| 272 | |
| 273 | // ---- 선택/현재 대화 ----------------------------------------------------- |
| 274 | |
| 275 | fn set_current(&mut self, idx: Option<usize>) { |
| 276 | if self.current != idx { |
| 277 | // 큰 데이터셋에서 메모리가 쌓이지 않도록, 떠나는 대화의 파싱 결과는 버린다. |
| 278 | if let Some(old) = self.current |
| 279 | && let Some(e) = self.doc.entries.get_mut(old) |
| 280 | { |
| 281 | e.drop_parsed_cache(); |
| 282 | } |
| 283 | self.current = idx; |
| 284 | self.msg_sel.clear(); |
| 285 | self.msg_anchor = None; |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | fn select_only_conv(&mut self, idx: usize) { |
| 290 | self.conv_sel.clear(); |
| 291 | self.conv_sel.insert(idx); |
| 292 | self.conv_anchor = Some(idx); |
| 293 | self.set_current(Some(idx)); |
| 294 | self.scroll_to_current = true; |
| 295 | } |
| 296 | |
| 297 | fn clamp_state(&mut self) { |
| 298 | let n = self.doc.len(); |
| 299 | self.conv_sel.retain(|&i| i < n); |
| 300 | if self.conv_anchor.is_some_and(|a| a >= n) { |
| 301 | self.conv_anchor = None; |
| 302 | } |
| 303 | if let Some(c) = self.current |
| 304 | && c >= n |
| 305 | { |
| 306 | self.current = if n == 0 { None } else { Some(n - 1) }; |
| 307 | self.msg_sel.clear(); |
| 308 | } |
| 309 | let m = self.current_msg_count(); |
| 310 | self.msg_sel.retain(|&i| i < m); |
| 311 | if self.msg_anchor.is_some_and(|a| a >= m) { |
| 312 | self.msg_anchor = None; |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | fn current_msg_count(&mut self) -> usize { |
| 317 | self.current |
| 318 | .and_then(|c| self.doc.entries.get_mut(c)) |
| 319 | .and_then(|e| e.conversation().ok()) |
| 320 | .map(|c| c.messages.len()) |
| 321 | .unwrap_or(0) |
| 322 | } |
| 323 | |
| 324 | fn click_conv(&mut self, i: usize, mods: Modifiers) { |
| 325 | self.focus = Focus::Sidebar; |
| 326 | if mods.shift { |
| 327 | let a = self.conv_anchor.unwrap_or(i); |
| 328 | for j in a.min(i)..=a.max(i) { |
| 329 | self.conv_sel.insert(j); |
| 330 | } |
| 331 | } else if mods.command { |
| 332 | if !self.conv_sel.remove(&i) { |
| 333 | self.conv_sel.insert(i); |
| 334 | } |
| 335 | self.conv_anchor = Some(i); |
| 336 | } else { |
| 337 | self.conv_sel.clear(); |
| 338 | self.conv_sel.insert(i); |
| 339 | self.conv_anchor = Some(i); |
| 340 | } |
| 341 | self.set_current(Some(i)); |
| 342 | } |
| 343 | |
| 344 | fn click_msg(&mut self, i: usize, mods: Modifiers) { |
| 345 | self.focus = Focus::Messages; |
| 346 | if mods.shift { |
| 347 | // Shift+클릭: 범위를 한 번에 선택. 이미 선택된 메시지를 누르면 그 범위의 선택을 해제. |
| 348 | let a = self.msg_anchor.unwrap_or(i); |
| 349 | let deselect = self.msg_sel.contains(&i); |
| 350 | for j in a.min(i)..=a.max(i) { |
| 351 | if deselect { |
| 352 | self.msg_sel.remove(&j); |
| 353 | } else { |
| 354 | self.msg_sel.insert(j); |
| 355 | } |
| 356 | } |
| 357 | } else if mods.command { |
| 358 | if !self.msg_sel.remove(&i) { |
| 359 | self.msg_sel.insert(i); |
| 360 | } |
| 361 | self.msg_anchor = Some(i); |
| 362 | } else { |
| 363 | self.msg_sel.clear(); |
| 364 | self.msg_sel.insert(i); |
| 365 | self.msg_anchor = Some(i); |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | // ---- 행동 실행 --------------------------------------------------------- |
| 370 | |
| 371 | fn run(&mut self, ctx: &egui::Context, action: Action) { |
| 372 | match action { |
| 373 | Action::NewConversation => { |
| 374 | let at = self |
| 375 | .conv_sel |
| 376 | .last() |
| 377 | .copied() |
| 378 | .or(self.current) |
| 379 | .map(|i| i + 1) |
| 380 | .unwrap_or(self.doc.len()); |
| 381 | let at = at.min(self.doc.len()); |
| 382 | self.doc.insert_conversation(at, Conversation::default()); |
| 383 | self.select_only_conv(at); |
| 384 | self.focus = Focus::Messages; |
| 385 | self.status = format!("대화 턴 #{} 생성", at + 1); |
| 386 | } |
| 387 | Action::DeleteConversation => { |
| 388 | let mut idx: Vec<usize> = self.conv_sel.iter().copied().collect(); |
| 389 | if idx.is_empty() { |
| 390 | idx.extend(self.current); |
| 391 | } |
| 392 | if idx.is_empty() { |
| 393 | return; |
| 394 | } |
| 395 | let first = idx[0]; |
| 396 | self.doc.remove_conversations(&idx); |
| 397 | self.current = None; |
| 398 | self.conv_sel.clear(); |
| 399 | if !self.doc.is_empty() { |
| 400 | self.select_only_conv(first.min(self.doc.len() - 1)); |
| 401 | } |
| 402 | self.status = format!("대화 턴 {}개 삭제", idx.len()); |
| 403 | } |
| 404 | Action::Undo => match self.doc.undo() { |
| 405 | Some(affected) => { |
| 406 | self.after_history(affected); |
| 407 | self.status = "되돌리기".into(); |
| 408 | } |
| 409 | None => self.status = "되돌릴 작업이 없습니다".into(), |
| 410 | }, |
| 411 | Action::Redo => match self.doc.redo() { |
| 412 | Some(affected) => { |
| 413 | self.after_history(affected); |
| 414 | self.status = "다시하기".into(); |
| 415 | } |
| 416 | None => self.status = "다시할 작업이 없습니다".into(), |
| 417 | }, |
| 418 | Action::Save => { |
| 419 | self.save(); |
| 420 | } |
| 421 | Action::SaveAs => { |
| 422 | self.save_as(); |
| 423 | } |
| 424 | Action::Load => self.guard_unsaved(ctx, Pending::Load), |
| 425 | Action::NewFile => self.guard_unsaved(ctx, Pending::NewFile), |
| 426 | Action::AddMessage => self.open_add_editor(), |
| 427 | Action::EditMessage => { |
| 428 | if self.msg_sel.len() == 1 { |
| 429 | let i = *self.msg_sel.first().unwrap(); |
| 430 | self.open_edit_editor(i); |
| 431 | } else { |
| 432 | self.status = "수정할 메시지 하나를 선택하세요".into(); |
| 433 | } |
| 434 | } |
| 435 | Action::DuplicateMessages => { |
| 436 | let sel: Vec<usize> = self.msg_sel.iter().copied().collect(); |
| 437 | self.modify_messages(|c| (!sel.is_empty()).then(|| c.duplicate(&sel))); |
| 438 | } |
| 439 | Action::MoveMessagesUp => { |
| 440 | let sel: Vec<usize> = self.msg_sel.iter().copied().collect(); |
| 441 | self.modify_messages(|c| (!sel.is_empty()).then(|| c.move_up(&sel))); |
| 442 | } |
| 443 | Action::MoveMessagesDown => { |
| 444 | let sel: Vec<usize> = self.msg_sel.iter().copied().collect(); |
| 445 | self.modify_messages(|c| (!sel.is_empty()).then(|| c.move_down(&sel))); |
| 446 | } |
| 447 | Action::DeleteMessages => { |
| 448 | let sel: Vec<usize> = self.msg_sel.iter().copied().collect(); |
| 449 | let n = sel.len(); |
| 450 | self.modify_messages(|c| { |
| 451 | if sel.is_empty() { |
| 452 | return None; |
| 453 | } |
| 454 | let first = sel[0]; |
| 455 | c.delete(&sel); |
| 456 | // 지운 자리 근처를 다시 선택해서 연속 삭제가 편하도록. |
| 457 | Some(if c.messages.is_empty() { vec![] } else { vec![first.min(c.messages.len() - 1)] }) |
| 458 | }); |
| 459 | if n > 0 { |
| 460 | self.status = format!("메시지 {n}개 삭제"); |
| 461 | } |
| 462 | } |
| 463 | Action::ToolLibrary => self.open_library(None), |
| 464 | Action::CollectTools => { |
| 465 | let found = tools::collect_tools(&self.doc.entries); |
| 466 | let n = found.len(); |
| 467 | let added = self.library.merge(found); |
| 468 | self.status = format!("데이터셋에서 도구 정의 {n}개 발견, 라이브러리에 {added}개 추가"); |
| 469 | self.save_library_now(); |
| 470 | } |
| 471 | } |
| 472 | self.clamp_state(); |
| 473 | } |
| 474 | |
| 475 | fn after_history(&mut self, affected: Vec<usize>) { |
| 476 | self.clamp_state(); |
| 477 | if let Some(&first) = affected.first() |
| 478 | && !self.doc.is_empty() |
| 479 | { |
| 480 | let i = first.min(self.doc.len() - 1); |
| 481 | if self.current != Some(i) { |
| 482 | self.select_only_conv(i); |
| 483 | } else { |
| 484 | self.scroll_to_current = true; |
| 485 | } |
| 486 | } |
| 487 | self.clamp_state(); |
| 488 | } |
| 489 | |
| 490 | /// 현재 대화의 메시지를 고친다. 클로저는 새 메시지 선택 영역을 돌려준다(None이면 변경 없음). |
| 491 | fn modify_messages(&mut self, f: impl FnOnce(&mut Conversation) -> Option<Vec<usize>>) { |
| 492 | let Some(ci) = self.current else { |
| 493 | self.status = "대화 턴을 먼저 선택하세요".into(); |
| 494 | return; |
| 495 | }; |
| 496 | match self.doc.modify(ci, f) { |
| 497 | Ok(Some(sel)) => { |
| 498 | self.msg_anchor = sel.first().copied(); |
| 499 | self.msg_sel = sel.into_iter().collect(); |
| 500 | } |
| 501 | Ok(None) => {} |
| 502 | Err(e) => self.error = Some(format!("이 대화 턴은 파싱에 실패해서 편집할 수 없습니다.\n{e}")), |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | fn open_add_editor(&mut self) { |
| 507 | let Some(ci) = self.current else { |
| 508 | self.status = "대화 턴을 먼저 선택하거나 생성하세요".into(); |
| 509 | return; |
| 510 | }; |
| 511 | let Some(conv) = self.doc.entries.get_mut(ci).and_then(|e| e.conversation().ok()) else { |
| 512 | self.error = Some("이 대화 턴은 파싱에 실패해서 편집할 수 없습니다.".into()); |
| 513 | return; |
| 514 | }; |
| 515 | let at = self.msg_sel.last().map(|i| i + 1).unwrap_or(conv.messages.len()).min(conv.messages.len()); |
| 516 | let role = conv.default_role_at(at); |
| 517 | let mut msg = Message::new(role); |
| 518 | let EditorContext { conv_tools, call_choices, unanswered } = editor_context(conv, at); |
| 519 | if role == Role::Tool { |
| 520 | // 직전 assistant의 호출 중 아직 결과가 없는 id를 미리 채워 준다. |
| 521 | msg.tool_call_id = unanswered.clone().unwrap_or_default(); |
| 522 | } |
| 523 | self.editor = Some(MessageEditor { |
| 524 | conv: ci, |
| 525 | target: EditTarget::Insert(at), |
| 526 | msg, |
| 527 | focus_content: true, |
| 528 | conv_tools, |
| 529 | call_choices, |
| 530 | tools_json_tab: self.library.tools.is_empty(), |
| 531 | unanswered, |
| 532 | }); |
| 533 | } |
| 534 | |
| 535 | fn open_edit_editor(&mut self, i: usize) { |
| 536 | let Some(ci) = self.current else { return }; |
| 537 | let Some(conv) = self.doc.entries.get_mut(ci).and_then(|e| e.conversation().ok()) else { return }; |
| 538 | let Some(msg) = conv.messages.get(i).cloned() else { return }; |
| 539 | let EditorContext { conv_tools, call_choices, unanswered } = editor_context(conv, i); |
| 540 | self.msg_sel.clear(); |
| 541 | self.msg_sel.insert(i); |
| 542 | self.msg_anchor = Some(i); |
| 543 | let tools_json_tab = msg.role == Role::Tools && tools::parse_tool_list(&msg.content).is_err(); |
| 544 | self.editor = Some(MessageEditor { |
| 545 | conv: ci, |
| 546 | target: EditTarget::Edit(i), |
| 547 | msg, |
| 548 | focus_content: true, |
| 549 | conv_tools, |
| 550 | call_choices, |
| 551 | tools_json_tab, |
| 552 | unanswered, |
| 553 | }); |
| 554 | } |
| 555 | |
| 556 | fn library_path(&self) -> Option<PathBuf> { |
| 557 | self.doc.path.as_deref().map(ToolLibrary::path_for) |
| 558 | } |
| 559 | |
| 560 | fn open_library(&mut self, select: Option<&str>) { |
| 561 | let target = self.library_path().map(|p| p.display().to_string()); |
| 562 | self.library_editor = Some(LibraryEditor::new(&self.library, select, target)); |
| 563 | } |
| 564 | |
| 565 | fn apply_library(&mut self, le: LibraryEditor) { |
| 566 | if le.tools != self.library.tools { |
| 567 | self.library.tools = le.tools; |
| 568 | self.library.dirty = true; |
| 569 | self.status = format!("도구 라이브러리 갱신 — {}개", self.library.tools.len()); |
| 570 | } |
| 571 | self.save_library_now(); |
| 572 | } |
| 573 | |
| 574 | /// 라이브러리는 되돌리기 기록과 무관한 별도 파일이라, 데이터셋 경로가 있으면 바뀌는 즉시 저장한다. |
| 575 | /// 경로가 아직 없으면(새 파일) 데이터셋을 처음 저장할 때 함께 저장된다. |
| 576 | fn save_library_now(&mut self) { |
| 577 | if !self.library.dirty { |
| 578 | return; |
| 579 | } |
| 580 | let Some(lib_path) = self.library_path() else { return }; |
| 581 | match self.library.save(&lib_path) { |
| 582 | Ok(()) => { |
| 583 | let name = lib_path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); |
| 584 | self.status = format!("도구 라이브러리 저장됨 — {name} ({}개)", self.library.tools.len()); |
| 585 | } |
| 586 | Err(e) => self.error = Some(format!("도구 라이브러리를 저장하지 못했습니다.\n{}\n{e}", lib_path.display())), |
| 587 | } |
| 588 | } |
| 589 | |
| 590 | fn library_window(&mut self, ctx: &egui::Context) { |
| 591 | let Some(le) = &mut self.library_editor else { return }; |
| 592 | match le.show(ctx) { |
| 593 | Some(LibraryOutcome::Apply) => { |
| 594 | let le = self.library_editor.take().unwrap(); |
| 595 | self.apply_library(le); |
| 596 | } |
| 597 | Some(LibraryOutcome::Cancel) => self.library_editor = None, |
| 598 | None => {} |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | fn commit_editor(&mut self) { |
| 603 | let Some(ed) = self.editor.take() else { return }; |
| 604 | let MessageEditor { conv, target, msg, .. } = ed; |
| 605 | let res = self.doc.modify(conv, move |c| match target { |
| 606 | EditTarget::Insert(at) => { |
| 607 | let at = at.min(c.messages.len()); |
| 608 | c.messages.insert(at, msg); |
| 609 | Some(at) |
| 610 | } |
| 611 | EditTarget::Edit(i) => { |
| 612 | let slot = c.messages.get_mut(i)?; |
| 613 | *slot = msg; |
| 614 | Some(i) |
| 615 | } |
| 616 | }); |
| 617 | match res { |
| 618 | Ok(Some(i)) => { |
| 619 | if self.current == Some(conv) { |
| 620 | self.msg_sel.clear(); |
| 621 | self.msg_sel.insert(i); |
| 622 | self.msg_anchor = Some(i); |
| 623 | } |
| 624 | self.focus = Focus::Messages; |
| 625 | } |
| 626 | Ok(None) => {} |
| 627 | Err(e) => self.error = Some(e), |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | // ---- 파일 --------------------------------------------------------------- |
| 632 | |
| 633 | fn guard_unsaved(&mut self, ctx: &egui::Context, next: Pending) { |
| 634 | if self.is_dirty() { |
| 635 | self.pending = Some(next); |
| 636 | } else { |
| 637 | self.do_pending(ctx, next); |
| 638 | } |
| 639 | } |
| 640 | |
| 641 | fn do_pending(&mut self, ctx: &egui::Context, p: Pending) { |
| 642 | match p { |
| 643 | Pending::Load => self.load_dialog(), |
| 644 | Pending::Open(path) => { |
| 645 | if path.exists() { |
| 646 | self.open_path(&path); |
| 647 | } else { |
| 648 | self.recent.remove(&path); |
| 649 | self.error = Some(format!("파일이 없습니다. 최근 파일 목록에서 뺐습니다.\n{}", path.display())); |
| 650 | } |
| 651 | } |
| 652 | Pending::NewFile => { |
| 653 | self.doc = Document::new(); |
| 654 | self.current = None; |
| 655 | self.conv_sel.clear(); |
| 656 | self.msg_sel.clear(); |
| 657 | self.status = "새 파일".into(); |
| 658 | } |
| 659 | Pending::Quit => { |
| 660 | self.allow_close = true; |
| 661 | ctx.send_viewport_cmd(ViewportCommand::Close); |
| 662 | } |
| 663 | } |
| 664 | } |
| 665 | |
| 666 | fn dialog_dir(&self) -> Option<PathBuf> { |
| 667 | self.doc |
| 668 | .path |
| 669 | .as_ref() |
| 670 | .and_then(|p| p.parent().map(Path::to_path_buf)) |
| 671 | .or_else(|| std::env::current_dir().ok()) |
| 672 | } |
| 673 | |
| 674 | fn load_dialog(&mut self) { |
| 675 | let mut dlg = rfd::FileDialog::new() |
| 676 | .set_title("데이터셋 불러오기") |
| 677 | .add_filter("JSON Lines (*.jsonl)", &["jsonl"]) |
| 678 | .add_filter("모든 파일", &["*"]); |
| 679 | if let Some(d) = self.dialog_dir() { |
| 680 | dlg = dlg.set_directory(d); |
| 681 | } |
| 682 | if let Some(path) = dlg.pick_file() { |
| 683 | self.open_path(&path); |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | fn open_path(&mut self, path: &Path) { |
| 688 | let t = std::time::Instant::now(); |
| 689 | match Document::open(path) { |
| 690 | Ok(doc) => { |
| 691 | self.recent.add(path); |
| 692 | self.doc = doc; |
| 693 | self.load_library(path); |
| 694 | self.current = None; |
| 695 | self.conv_sel.clear(); |
| 696 | self.msg_sel.clear(); |
| 697 | if !self.doc.is_empty() { |
| 698 | self.select_only_conv(0); |
| 699 | } |
| 700 | self.status = format!( |
| 701 | "{} 불러옴 — 대화 턴 {}개 ({:.0} ms)", |
| 702 | self.file_name(), |
| 703 | self.doc.len(), |
| 704 | t.elapsed().as_secs_f64() * 1000.0 |
| 705 | ); |
| 706 | } |
| 707 | Err(e) => self.error = Some(format!("파일을 불러오지 못했습니다.\n{}\n{e}", path.display())), |
| 708 | } |
| 709 | } |
| 710 | |
| 711 | /// 데이터셋 옆의 도구 라이브러리를 읽는다. 없으면 데이터셋의 tools 메시지에서 모은다. |
| 712 | fn load_library(&mut self, dataset: &Path) { |
| 713 | let lib_path = ToolLibrary::path_for(dataset); |
| 714 | self.library = if lib_path.exists() { |
| 715 | match ToolLibrary::load(&lib_path) { |
| 716 | Ok(lib) => lib, |
| 717 | Err(e) => { |
| 718 | self.error = Some(format!("도구 라이브러리를 읽지 못했습니다.\n{}\n{e}", lib_path.display())); |
| 719 | ToolLibrary::default() |
| 720 | } |
| 721 | } |
| 722 | } else { |
| 723 | ToolLibrary { tools: tools::collect_tools(&self.doc.entries), dirty: false } |
| 724 | }; |
| 725 | } |
| 726 | |
| 727 | /// 저장에 성공하면 true. |
| 728 | fn save(&mut self) -> bool { |
| 729 | match self.doc.path.clone() { |
| 730 | Some(p) => self.save_to(&p), |
| 731 | None => self.save_as(), |
| 732 | } |
| 733 | } |
| 734 | |
| 735 | fn save_as(&mut self) -> bool { |
| 736 | let mut dlg = rfd::FileDialog::new() |
| 737 | .set_title("다른 이름으로 저장") |
| 738 | .add_filter("JSON Lines (*.jsonl)", &["jsonl"]) |
| 739 | .set_file_name(if self.doc.path.is_some() { self.file_name() } else { "dataset.jsonl".into() }); |
| 740 | if let Some(d) = self.dialog_dir() { |
| 741 | dlg = dlg.set_directory(d); |
| 742 | } |
| 743 | let Some(mut path) = dlg.save_file() else { return false }; |
| 744 | if path.extension().is_none() { |
| 745 | path.set_extension("jsonl"); |
| 746 | } |
| 747 | self.save_to(&path) |
| 748 | } |
| 749 | |
| 750 | fn save_to(&mut self, path: &Path) -> bool { |
| 751 | let lib_path = ToolLibrary::path_for(path); |
| 752 | let result = self.doc.save_to(path).and_then(|()| { |
| 753 | if !self.library.tools.is_empty() || lib_path.exists() { |
| 754 | self.library.save(&lib_path)?; |
| 755 | } |
| 756 | Ok(()) |
| 757 | }); |
| 758 | match result { |
| 759 | Ok(()) => { |
| 760 | self.recent.add(path); |
| 761 | self.status = format!("{} 저장됨 — 대화 턴 {}개", self.file_name(), self.doc.len()); |
| 762 | true |
| 763 | } |
| 764 | Err(e) => { |
| 765 | self.error = Some(format!("저장하지 못했습니다.\n{}\n{e}", path.display())); |
| 766 | false |
| 767 | } |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | // ---- 입력 --------------------------------------------------------------- |
| 772 | |
| 773 | fn handle_shortcuts(&mut self, ctx: &egui::Context) { |
| 774 | let cmd = Modifiers::COMMAND; |
| 775 | let cmd_shift = Modifiers::COMMAND | Modifiers::SHIFT; |
| 776 | // 편집 창이 열려 있어도 Ctrl+S는 동작한다: 열린 창의 내용을 먼저 반영하고 저장. |
| 777 | if (self.editor.is_some() || self.library_editor.is_some()) |
| 778 | && self.pending.is_none() |
| 779 | && self.error.is_none() |
| 780 | && self.quick.is_none() |
| 781 | { |
| 782 | let (save_as, save) = ctx.input_mut(|i| (i.consume_key(cmd_shift, Key::S), i.consume_key(cmd, Key::S))); |
| 783 | if save_as || save { |
| 784 | if let Some(le) = &mut self.library_editor { |
| 785 | if !le.finish() { |
| 786 | self.error = Some("도구 JSON에 오류가 있어 저장하지 않았습니다. 고친 뒤 다시 저장하세요.".into()); |
| 787 | return; |
| 788 | } |
| 789 | let le = self.library_editor.take().unwrap(); |
| 790 | self.apply_library(le); |
| 791 | } else { |
| 792 | self.commit_editor(); |
| 793 | } |
| 794 | if save_as { |
| 795 | self.save_as(); |
| 796 | } else { |
| 797 | self.save(); |
| 798 | } |
| 799 | } |
| 800 | return; |
| 801 | } |
| 802 | if self.overlay_open() || ctx.egui_wants_keyboard_input() { |
| 803 | return; |
| 804 | } |
| 805 | let mut actions = Vec::new(); |
| 806 | let mut open_quick = false; |
| 807 | let mut nav: i32 = 0; |
| 808 | let mut enter = false; |
| 809 | let mut escape = false; |
| 810 | ctx.input_mut(|i| { |
| 811 | // 더 구체적인 조합(Shift 포함)을 먼저 확인해야 한다. |
| 812 | if i.consume_key(cmd_shift, Key::S) { |
| 813 | actions.push(Action::SaveAs); |
| 814 | } |
| 815 | if i.consume_key(cmd, Key::S) { |
| 816 | actions.push(Action::Save); |
| 817 | } |
| 818 | if i.consume_key(cmd_shift, Key::Z) || i.consume_key(cmd, Key::Y) { |
| 819 | actions.push(Action::Redo); |
| 820 | } |
| 821 | if i.consume_key(cmd, Key::Z) { |
| 822 | actions.push(Action::Undo); |
| 823 | } |
| 824 | if i.consume_key(cmd, Key::O) { |
| 825 | actions.push(Action::Load); |
| 826 | } |
| 827 | if i.consume_key(cmd, Key::A) { |
| 828 | actions.push(Action::AddMessage); |
| 829 | } |
| 830 | if i.consume_key(cmd, Key::D) { |
| 831 | actions.push(Action::DuplicateMessages); |
| 832 | } |
| 833 | if i.consume_key(cmd, Key::ArrowUp) { |
| 834 | actions.push(Action::MoveMessagesUp); |
| 835 | } |
| 836 | if i.consume_key(cmd, Key::ArrowDown) { |
| 837 | actions.push(Action::MoveMessagesDown); |
| 838 | } |
| 839 | if i.consume_key(Modifiers::NONE, Key::Delete) { |
| 840 | actions.push(match self.focus { |
| 841 | Focus::Sidebar => Action::DeleteConversation, |
| 842 | Focus::Messages => Action::DeleteMessages, |
| 843 | }); |
| 844 | } |
| 845 | if i.consume_key(Modifiers::NONE, Key::Backtick) { |
| 846 | open_quick = true; |
| 847 | } |
| 848 | if i.consume_key(Modifiers::NONE, Key::ArrowUp) { |
| 849 | nav = -1; |
| 850 | } |
| 851 | if i.consume_key(Modifiers::NONE, Key::ArrowDown) { |
| 852 | nav = 1; |
| 853 | } |
| 854 | enter = i.consume_key(Modifiers::NONE, Key::Enter); |
| 855 | escape = i.consume_key(Modifiers::NONE, Key::Escape); |
| 856 | }); |
| 857 | for a in actions { |
| 858 | self.run(ctx, a); |
| 859 | if self.overlay_open() { |
| 860 | return; |
| 861 | } |
| 862 | } |
| 863 | if nav != 0 { |
| 864 | self.keyboard_nav(nav); |
| 865 | } |
| 866 | if enter && self.focus == Focus::Messages && self.msg_sel.len() == 1 { |
| 867 | self.run(ctx, Action::EditMessage); |
| 868 | } |
| 869 | if escape && self.focus == Focus::Messages { |
| 870 | self.msg_sel.clear(); |
| 871 | } |
| 872 | if open_quick { |
| 873 | let screen = ctx.content_rect(); |
| 874 | let p = ctx.input(|i| i.pointer.latest_pos()).unwrap_or(screen.center()); |
| 875 | let pos = Pos2::new(p.x.min(screen.right() - 380.0).max(0.0), p.y.min(screen.bottom() - 340.0).max(0.0)); |
| 876 | self.quick = Some(QuickMenu { pos, query: String::new(), selected: 0, focus_input: true }); |
| 877 | } |
| 878 | } |
| 879 | |
| 880 | fn keyboard_nav(&mut self, dir: i32) { |
| 881 | match self.focus { |
| 882 | Focus::Sidebar => { |
| 883 | let n = self.doc.len(); |
| 884 | if n == 0 { |
| 885 | return; |
| 886 | } |
| 887 | let cur = self.current.unwrap_or(0) as i64; |
| 888 | let next = (cur + dir as i64).clamp(0, n as i64 - 1) as usize; |
| 889 | self.select_only_conv(next); |
| 890 | } |
| 891 | Focus::Messages => { |
| 892 | let n = self.current_msg_count(); |
| 893 | if n == 0 { |
| 894 | return; |
| 895 | } |
| 896 | let cur = match (dir < 0, self.msg_sel.first(), self.msg_sel.last()) { |
| 897 | (true, Some(&f), _) => f as i64 - 1, |
| 898 | (false, _, Some(&l)) => l as i64 + 1, |
| 899 | _ => 0, |
| 900 | }; |
| 901 | let next = cur.clamp(0, n as i64 - 1) as usize; |
| 902 | self.msg_sel.clear(); |
| 903 | self.msg_sel.insert(next); |
| 904 | self.msg_anchor = Some(next); |
| 905 | } |
| 906 | } |
| 907 | } |
| 908 | |
| 909 | fn handle_close_request(&mut self, ctx: &egui::Context) { |
| 910 | if ctx.input(|i| i.viewport().close_requested()) && self.is_dirty() && !self.allow_close { |
| 911 | ctx.send_viewport_cmd(ViewportCommand::CancelClose); |
| 912 | self.pending = Some(Pending::Quit); |
| 913 | } |
| 914 | } |
| 915 | |
| 916 | fn update_title(&mut self, ctx: &egui::Context) { |
| 917 | let title = format!( |
| 918 | "{}{} — handmade-dataset-creator", |
| 919 | if self.is_dirty() { "*" } else { "" }, |
| 920 | self.file_name() |
| 921 | ); |
| 922 | if title != self.last_title { |
| 923 | ctx.send_viewport_cmd(ViewportCommand::Title(title.clone())); |
| 924 | self.last_title = title; |
| 925 | } |
| 926 | } |
| 927 | |
| 928 | // ---- 화면 --------------------------------------------------------------- |
| 929 | |
| 930 | fn menu_bar(&mut self, ui: &mut egui::Ui) { |
| 931 | let ctx = ui.ctx().clone(); |
| 932 | let mut action = None; |
| 933 | let mut open_recent: Option<PathBuf> = None; |
| 934 | let mut clear_recent = false; |
| 935 | ui.menu_button("파일", |ui| { |
| 936 | if shortcut_button(ui, "새 파일", "").clicked() { |
| 937 | action = Some(Action::NewFile); |
| 938 | } |
| 939 | if shortcut_button(ui, "불러오기…", "Ctrl+O").clicked() { |
| 940 | action = Some(Action::Load); |
| 941 | } |
| 942 | ui.menu_button("최근에 연 파일", |ui| { |
| 943 | if self.recent.paths.is_empty() { |
| 944 | ui.weak("최근에 연 파일이 없습니다"); |
| 945 | } |
| 946 | for (i, path) in self.recent.paths.iter().enumerate() { |
| 947 | let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); |
| 948 | let dir = path.parent().map(|d| d.display().to_string()).unwrap_or_default(); |
| 949 | let label = format!("{}. {name}", i + 1); |
| 950 | let mut b = Button::new(label).shortcut_text(dir); |
| 951 | if !path.exists() { |
| 952 | b = b.shortcut_text("(파일 없음)"); |
| 953 | } |
| 954 | if ui.add(b).on_hover_text(path.display().to_string()).clicked() { |
| 955 | open_recent = Some(path.clone()); |
| 956 | } |
| 957 | } |
| 958 | if !self.recent.paths.is_empty() { |
| 959 | ui.separator(); |
| 960 | if ui.button("목록 지우기").clicked() { |
| 961 | clear_recent = true; |
| 962 | } |
| 963 | } |
| 964 | }); |
| 965 | ui.separator(); |
| 966 | if shortcut_button(ui, "저장", "Ctrl+S").clicked() { |
| 967 | action = Some(Action::Save); |
| 968 | } |
| 969 | if shortcut_button(ui, "다른 이름으로 저장…", "Ctrl+Shift+S").clicked() { |
| 970 | action = Some(Action::SaveAs); |
| 971 | } |
| 972 | ui.separator(); |
| 973 | if shortcut_button(ui, "종료", "").clicked() { |
| 974 | ctx.send_viewport_cmd(ViewportCommand::Close); |
| 975 | } |
| 976 | }); |
| 977 | ui.menu_button("편집", |ui| { |
| 978 | if ui.add_enabled(self.doc.can_undo(), Button::new("되돌리기").shortcut_text("Ctrl+Z")).clicked() { |
| 979 | action = Some(Action::Undo); |
| 980 | } |
| 981 | if ui.add_enabled(self.doc.can_redo(), Button::new("다시하기").shortcut_text("Ctrl+Shift+Z")).clicked() { |
| 982 | action = Some(Action::Redo); |
| 983 | } |
| 984 | ui.separator(); |
| 985 | for a in [ |
| 986 | Action::NewConversation, |
| 987 | Action::DeleteConversation, |
| 988 | Action::AddMessage, |
| 989 | Action::EditMessage, |
| 990 | Action::DuplicateMessages, |
| 991 | Action::MoveMessagesUp, |
| 992 | Action::MoveMessagesDown, |
| 993 | Action::DeleteMessages, |
| 994 | ] { |
| 995 | if shortcut_button(ui, a.label(), a.shortcut()).clicked() { |
| 996 | action = Some(a); |
| 997 | } |
| 998 | } |
| 999 | }); |
| 1000 | ui.menu_button("도구", |ui| { |
| 1001 | if shortcut_button(ui, "도구 라이브러리…", "").clicked() { |
| 1002 | action = Some(Action::ToolLibrary); |
| 1003 | } |
| 1004 | if shortcut_button(ui, "데이터셋에서 도구 가져오기", "").clicked() { |
| 1005 | action = Some(Action::CollectTools); |
| 1006 | } |
| 1007 | }); |
| 1008 | ui.menu_button("도움말", |ui| { |
| 1009 | ui.label("` : 퀵 메뉴 (행동 검색)"); |
| 1010 | ui.label("Ctrl+A : 메시지 추가 Ctrl+D : 선택 메시지 복제"); |
| 1011 | ui.label("Ctrl+↑/↓ : 선택 메시지 이동 Del : 삭제"); |
| 1012 | ui.label("더블클릭 / Enter : 메시지 수정"); |
| 1013 | ui.label("Shift+클릭 : 범위 선택/해제 Ctrl+클릭 : 개별 선택/해제"); |
| 1014 | ui.label("메시지 편집 창: Ctrl+Enter 확인, Esc 취소"); |
| 1015 | ui.separator(); |
| 1016 | ui.label("서식 (입력란에서 선택 후): Ctrl+B 굵게 **…**, Ctrl+U 밑줄 <u>…</u>"); |
| 1017 | ui.label(" Ctrl+Shift+X 취소선 ~~…~~, Ctrl+M 강조 <mark>…</mark> (박스·음영 등)"); |
| 1018 | }); |
| 1019 | if let Some(a) = action { |
| 1020 | self.run(&ctx, a); |
| 1021 | } |
| 1022 | if let Some(path) = open_recent { |
| 1023 | self.guard_unsaved(&ctx, Pending::Open(path)); |
| 1024 | } |
| 1025 | if clear_recent { |
| 1026 | self.recent.clear(); |
| 1027 | } |
| 1028 | } |
| 1029 | |
| 1030 | fn status_bar(&mut self, ui: &mut egui::Ui) { |
| 1031 | ui.horizontal(|ui| { |
| 1032 | // 오른쪽 정보를 먼저 배치하고, 남은 공간에 상태 메시지를 잘라서 표시한다. |
| 1033 | ui.with_layout(Layout::right_to_left(Align::Center), |ui| { |
| 1034 | let path = self.doc.path.as_ref().map(|p| p.display().to_string()).unwrap_or_else(|| "저장 안 됨".into()); |
| 1035 | ui.weak(path); |
| 1036 | ui.separator(); |
| 1037 | if self.is_dirty() { |
| 1038 | ui.colored_label(Color32::from_rgb(230, 160, 60), "수정됨"); |
| 1039 | } else { |
| 1040 | ui.weak("저장됨"); |
| 1041 | } |
| 1042 | ui.separator(); |
| 1043 | ui.weak(format!("대화 턴 {}개", self.doc.len())); |
| 1044 | ui.separator(); |
| 1045 | ui.with_layout(Layout::left_to_right(Align::Center), |ui| { |
| 1046 | ui.add(egui::Label::new(self.status.as_str()).truncate()); |
| 1047 | }); |
| 1048 | }); |
| 1049 | }); |
| 1050 | } |
| 1051 | |
| 1052 | fn sidebar(&mut self, ui: &mut egui::Ui) { |
| 1053 | let ctx = ui.ctx().clone(); |
| 1054 | ui.add_space(4.0); |
| 1055 | ui.strong(format!("대화 턴 ({})", self.doc.len())); |
| 1056 | ui.separator(); |
| 1057 | |
| 1058 | // 빈 공간 클릭/우클릭을 받기 위한 배경. 항목들이 나중에 그려지므로 항목이 우선한다. |
| 1059 | let bg = ui.interact(ui.available_rect_before_wrap(), ui.scope_id().with("sidebar_bg"), Sense::click()); |
| 1060 | |
| 1061 | let row_h = ui.text_style_height(&TextStyle::Button) + 6.0; |
| 1062 | let row_step = row_h + ui.spacing().item_spacing.y; |
| 1063 | let n = self.doc.len(); |
| 1064 | let mut scroll = ScrollArea::vertical().auto_shrink(false).id_salt("conv_list"); |
| 1065 | if self.scroll_to_current |
| 1066 | && let Some(c) = self.current |
| 1067 | { |
| 1068 | let view_h = ui.available_height(); |
| 1069 | scroll = scroll.vertical_scroll_offset((c as f32 * row_step - view_h * 0.4).max(0.0)); |
| 1070 | self.scroll_to_current = false; |
| 1071 | } |
| 1072 | |
| 1073 | let mut clicked: Option<(usize, Modifiers)> = None; |
| 1074 | let mut right_clicked: Option<usize> = None; |
| 1075 | let mut action: Option<Action> = None; |
| 1076 | let current = self.current; |
| 1077 | let entries = &self.doc.entries; |
| 1078 | let conv_sel = &self.conv_sel; |
| 1079 | scroll.show_rows(ui, row_h, n, |ui, range| { |
| 1080 | for i in range { |
| 1081 | let selected = conv_sel.contains(&i); |
| 1082 | let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click()); |
| 1083 | if ui.is_rect_visible(rect) { |
| 1084 | let visuals = ui.visuals(); |
| 1085 | let text_color = if selected { |
| 1086 | visuals.selection.stroke.color |
| 1087 | } else if entries[i].has_error() { |
| 1088 | visuals.warn_fg_color |
| 1089 | } else { |
| 1090 | visuals.text_color() |
| 1091 | }; |
| 1092 | if selected { |
| 1093 | ui.painter().rect_filled(rect, 2.0, visuals.selection.bg_fill); |
| 1094 | } else if resp.hovered() { |
| 1095 | ui.painter().rect_filled(rect, 2.0, visuals.widgets.hovered.weak_bg_fill); |
| 1096 | } |
| 1097 | let mut text = RichText::new(format!("{:>4} {}", i + 1, entries[i].preview())).color(text_color); |
| 1098 | if current == Some(i) { |
| 1099 | text = text.strong(); |
| 1100 | } |
| 1101 | let galley = WidgetText::from(text).into_galley( |
| 1102 | ui, |
| 1103 | Some(TextWrapMode::Truncate), |
| 1104 | rect.width() - 8.0, |
| 1105 | TextStyle::Button, |
| 1106 | ); |
| 1107 | let pos = Pos2::new(rect.left() + 4.0, rect.center().y - galley.size().y / 2.0); |
| 1108 | ui.painter().galley(pos, galley, text_color); |
| 1109 | } |
| 1110 | if resp.clicked() { |
| 1111 | clicked = Some((i, ui.input(|inp| inp.modifiers))); |
| 1112 | } |
| 1113 | if resp.secondary_clicked() { |
| 1114 | right_clicked = Some(i); |
| 1115 | } |
| 1116 | resp.context_menu(|ui| { |
| 1117 | if ui.button("대화 턴 생성").clicked() { |
| 1118 | action = Some(Action::NewConversation); |
| 1119 | } |
| 1120 | if ui.button("대화 턴 삭제").clicked() { |
| 1121 | action = Some(Action::DeleteConversation); |
| 1122 | } |
| 1123 | }); |
| 1124 | } |
| 1125 | }); |
| 1126 | |
| 1127 | if let Some((i, mods)) = clicked { |
| 1128 | self.click_conv(i, mods); |
| 1129 | } |
| 1130 | if let Some(i) = right_clicked { |
| 1131 | self.focus = Focus::Sidebar; |
| 1132 | if !self.conv_sel.contains(&i) { |
| 1133 | self.conv_sel.clear(); |
| 1134 | self.conv_sel.insert(i); |
| 1135 | self.conv_anchor = Some(i); |
| 1136 | self.set_current(Some(i)); |
| 1137 | } |
| 1138 | } |
| 1139 | if bg.clicked() || bg.secondary_clicked() { |
| 1140 | self.focus = Focus::Sidebar; |
| 1141 | } |
| 1142 | bg.context_menu(|ui| { |
| 1143 | if ui.button("대화 턴 생성").clicked() { |
| 1144 | action = Some(Action::NewConversation); |
| 1145 | } |
| 1146 | }); |
| 1147 | if let Some(a) = action { |
| 1148 | self.run(&ctx, a); |
| 1149 | } |
| 1150 | } |
| 1151 | |
| 1152 | fn messages_view(&mut self, ui: &mut egui::Ui) { |
| 1153 | let ctx = ui.ctx().clone(); |
| 1154 | let Some(ci) = self.current else { |
| 1155 | ui.centered_and_justified(|ui| { |
| 1156 | ui.weak("왼쪽 목록에서 대화 턴을 선택하거나, 목록의 빈 곳을 우클릭해 대화 턴을 생성하세요.\n(` 키로 퀵 메뉴)"); |
| 1157 | }); |
| 1158 | return; |
| 1159 | }; |
| 1160 | let Some(entry) = self.doc.entries.get_mut(ci) else { return }; |
| 1161 | let conv = match entry.conversation() { |
| 1162 | Ok(c) => c, |
| 1163 | Err(e) => { |
| 1164 | ui.colored_label(ui.visuals().error_fg_color, format!("대화 턴 #{}을(를) 파싱하지 못했습니다: {e}", ci + 1)); |
| 1165 | ui.weak("이 줄은 수정하지 않으면 원문 그대로 저장됩니다."); |
| 1166 | ui.separator(); |
| 1167 | let raw = entry.raw().unwrap_or_default().to_string(); |
| 1168 | ScrollArea::vertical().auto_shrink(false).show(ui, |ui| { |
| 1169 | ui.add(egui::Label::new(RichText::new(raw).monospace()).wrap()); |
| 1170 | }); |
| 1171 | return; |
| 1172 | } |
| 1173 | }; |
| 1174 | |
| 1175 | ui.horizontal(|ui| { |
| 1176 | ui.strong(format!("대화 턴 #{}", ci + 1)); |
| 1177 | ui.weak(format!("메시지 {}개", conv.messages.len())); |
| 1178 | ui.with_layout(Layout::right_to_left(Align::Center), |ui| { |
| 1179 | ui.weak("Ctrl+A 추가 · 더블클릭 수정 · Ctrl+D 복제 · Ctrl+↑/↓ 이동 · Del 삭제"); |
| 1180 | }); |
| 1181 | }); |
| 1182 | ui.separator(); |
| 1183 | |
| 1184 | let bg = ui.interact(ui.available_rect_before_wrap(), ui.scope_id().with("msg_bg"), Sense::click()); |
| 1185 | let mut clicked: Option<(usize, Modifiers)> = None; |
| 1186 | let mut double: Option<usize> = None; |
| 1187 | let mut right: Option<usize> = None; |
| 1188 | let mut action: Option<Action> = None; |
| 1189 | let msg_sel = &self.msg_sel; |
| 1190 | |
| 1191 | ScrollArea::vertical().auto_shrink(false).id_salt(("messages", ci)).show(ui, |ui| { |
| 1192 | ui.style_mut().interaction.selectable_labels = false; |
| 1193 | for (i, m) in conv.messages.iter().enumerate() { |
| 1194 | let selected = msg_sel.contains(&i); |
| 1195 | let visuals = ui.visuals().clone(); |
| 1196 | let (fill, stroke) = if selected { |
| 1197 | (visuals.selection.bg_fill.gamma_multiply(0.35), visuals.selection.stroke) |
| 1198 | } else { |
| 1199 | (visuals.faint_bg_color, visuals.widgets.noninteractive.bg_stroke) |
| 1200 | }; |
| 1201 | let inner = Frame::new().fill(fill).stroke(stroke).corner_radius(4.0).inner_margin(8.0).show(ui, |ui| { |
| 1202 | ui.set_width(ui.available_width()); |
| 1203 | message_body(ui, i, m); |
| 1204 | }); |
| 1205 | let resp = ui.interact(inner.response.rect, ui.scope_id().with(("msg", i)), Sense::click()); |
| 1206 | if resp.double_clicked() { |
| 1207 | double = Some(i); |
| 1208 | } else if resp.clicked() { |
| 1209 | clicked = Some((i, ui.input(|inp| inp.modifiers))); |
| 1210 | } |
| 1211 | if resp.secondary_clicked() { |
| 1212 | right = Some(i); |
| 1213 | } |
| 1214 | resp.context_menu(|ui| { |
| 1215 | for a in [ |
| 1216 | Action::AddMessage, |
| 1217 | Action::EditMessage, |
| 1218 | Action::DuplicateMessages, |
| 1219 | Action::MoveMessagesUp, |
| 1220 | Action::MoveMessagesDown, |
| 1221 | Action::DeleteMessages, |
| 1222 | ] { |
| 1223 | if shortcut_button(ui, a.label(), a.shortcut()).clicked() { |
| 1224 | action = Some(a); |
| 1225 | } |
| 1226 | } |
| 1227 | }); |
| 1228 | ui.add_space(2.0); |
| 1229 | } |
| 1230 | ui.add_space(4.0); |
| 1231 | if ui.button("+ 메시지 추가 (Ctrl+A)").clicked() { |
| 1232 | action = Some(Action::AddMessage); |
| 1233 | } |
| 1234 | }); |
| 1235 | |
| 1236 | if let Some((i, mods)) = clicked { |
| 1237 | self.click_msg(i, mods); |
| 1238 | } |
| 1239 | if let Some(i) = right { |
| 1240 | self.focus = Focus::Messages; |
| 1241 | if !self.msg_sel.contains(&i) { |
| 1242 | self.msg_sel.clear(); |
| 1243 | self.msg_sel.insert(i); |
| 1244 | self.msg_anchor = Some(i); |
| 1245 | } |
| 1246 | } |
| 1247 | if let Some(i) = double { |
| 1248 | self.focus = Focus::Messages; |
| 1249 | self.open_edit_editor(i); |
| 1250 | } |
| 1251 | if bg.clicked() { |
| 1252 | self.focus = Focus::Messages; |
| 1253 | self.msg_sel.clear(); |
| 1254 | } |
| 1255 | if bg.secondary_clicked() { |
| 1256 | self.focus = Focus::Messages; |
| 1257 | } |
| 1258 | bg.context_menu(|ui| { |
| 1259 | if shortcut_button(ui, "메시지 추가", "Ctrl+A").clicked() { |
| 1260 | action = Some(Action::AddMessage); |
| 1261 | } |
| 1262 | }); |
| 1263 | if let Some(a) = action { |
| 1264 | self.run(&ctx, a); |
| 1265 | } |
| 1266 | } |
| 1267 | |
| 1268 | fn editor_window(&mut self, ctx: &egui::Context) { |
| 1269 | let Some(ed) = &mut self.editor else { return }; |
| 1270 | let library_open = self.library_editor.is_some(); |
| 1271 | let (mut commit, mut cancel) = if library_open { |
| 1272 | (false, false) |
| 1273 | } else { |
| 1274 | ctx.input_mut(|i| { |
| 1275 | (i.consume_key(Modifiers::COMMAND, Key::Enter), i.consume_key(Modifiers::NONE, Key::Escape)) |
| 1276 | }) |
| 1277 | }; |
| 1278 | let library_was_dirty = self.library.dirty; |
| 1279 | let library = &mut self.library; |
| 1280 | let mut open_library: Option<Option<String>> = None; |
| 1281 | let title = match ed.target { |
| 1282 | EditTarget::Insert(at) => format!("메시지 편집 창 — 새 메시지 (#{} 위치)", at + 1), |
| 1283 | EditTarget::Edit(i) => format!("메시지 편집 창 — 메시지 #{}", i + 1), |
| 1284 | }; |
| 1285 | let screen = ctx.content_rect(); |
| 1286 | // 화면 위쪽에 고정한다. 가운데 정렬하면 내용 높이가 바뀔 때 위치와 스크롤 영역 높이가 |
| 1287 | // 서로 영향을 주며 몇 프레임에 걸쳐 미끄러지듯 움직인다. |
| 1288 | let area = Modal::default_area(Id::unique("message_editor")).anchor(egui::Align2::CENTER_TOP, vec2(0.0, 32.0)); |
| 1289 | Modal::new(Id::unique("message_editor")).area(area).show(ctx, |ui| { |
| 1290 | ui.set_width((screen.width() - 80.0).clamp(320.0, 900.0)); |
| 1291 | ui.strong(title); |
| 1292 | ui.separator(); |
| 1293 | let mut role = ed.msg.role; |
| 1294 | ui.horizontal(|ui| { |
| 1295 | ui.label("역할"); |
| 1296 | ComboBox::from_id_salt("editor_role").selected_text(role.as_str()).show_ui(ui, |ui| { |
| 1297 | for r in Role::ALL { |
| 1298 | ui.selectable_value(&mut role, r, r.as_str()); |
| 1299 | } |
| 1300 | }); |
| 1301 | }); |
| 1302 | if role != ed.msg.role { |
| 1303 | ed.msg.set_role(role); |
| 1304 | ed.focus_content = true; |
| 1305 | if role == Role::Tool && ed.msg.tool_call_id.is_empty() { |
| 1306 | ed.msg.tool_call_id = ed.unanswered.clone().unwrap_or_default(); |
| 1307 | } |
| 1308 | } |
| 1309 | ui.add_space(4.0); |
| 1310 | ScrollArea::vertical().max_height((screen.height() - 190.0).max(200.0)).auto_shrink([false, true]).show(ui, |ui| { |
| 1311 | editor_fields(ui, ed, library, &mut open_library); |
| 1312 | }); |
| 1313 | ui.separator(); |
| 1314 | ui.horizontal(|ui| { |
| 1315 | if ui.button("확인 (Ctrl+Enter)").clicked() { |
| 1316 | commit = true; |
| 1317 | } |
| 1318 | if ui.button("취소 (Esc)").clicked() { |
| 1319 | cancel = true; |
| 1320 | } |
| 1321 | }); |
| 1322 | }); |
| 1323 | // tools 메시지 편집 중 "라이브러리에 추가"를 누른 경우 바로 저장. |
| 1324 | if !library_was_dirty && self.library.dirty { |
| 1325 | self.save_library_now(); |
| 1326 | } |
| 1327 | if let Some(select) = open_library { |
| 1328 | self.open_library(select.as_deref()); |
| 1329 | } |
| 1330 | if commit { |
| 1331 | self.commit_editor(); |
| 1332 | } else if cancel { |
| 1333 | self.editor = None; |
| 1334 | } |
| 1335 | } |
| 1336 | |
| 1337 | fn quick_menu(&mut self, ctx: &egui::Context) { |
| 1338 | let Some(q) = &mut self.quick else { return }; |
| 1339 | q.query.retain(|c| c != '`'); |
| 1340 | let matches: Vec<Action> = Action::QUICK.iter().copied().filter(|a| a.matches(&q.query)).collect(); |
| 1341 | let (up, down, enter, esc) = ctx.input_mut(|i| { |
| 1342 | let up = i.consume_key(Modifiers::NONE, Key::ArrowUp) || i.consume_key(Modifiers::SHIFT, Key::Tab); |
| 1343 | let down = i.consume_key(Modifiers::NONE, Key::ArrowDown) || i.consume_key(Modifiers::NONE, Key::Tab); |
| 1344 | (up, down, i.consume_key(Modifiers::NONE, Key::Enter), i.consume_key(Modifiers::NONE, Key::Escape)) |
| 1345 | }); |
| 1346 | if !matches.is_empty() { |
| 1347 | let n = matches.len(); |
| 1348 | q.selected = q.selected.min(n - 1); |
| 1349 | if up { |
| 1350 | q.selected = (q.selected + n - 1) % n; |
| 1351 | } |
| 1352 | if down { |
| 1353 | q.selected = (q.selected + 1) % n; |
| 1354 | } |
| 1355 | } |
| 1356 | let mut run = if enter { matches.get(q.selected).copied() } else { None }; |
| 1357 | let mut close = esc || (enter && run.is_none()); |
| 1358 | |
| 1359 | let area = Area::new(Id::unique("quick_menu")).fade_in(false).order(Order::Foreground).fixed_pos(q.pos).show(ctx, |ui| { |
| 1360 | Frame::popup(ui.style()).show(ui, |ui| { |
| 1361 | ui.set_width(360.0); |
| 1362 | let r = ui.add( |
| 1363 | TextEdit::singleline(&mut q.query) |
| 1364 | .id(Id::unique("quick_menu_input")) |
| 1365 | .hint_text("행동 검색…") |
| 1366 | .desired_width(f32::INFINITY), |
| 1367 | ); |
| 1368 | if q.focus_input { |
| 1369 | r.request_focus(); |
| 1370 | q.focus_input = false; |
| 1371 | } |
| 1372 | if r.changed() { |
| 1373 | q.selected = 0; |
| 1374 | } |
| 1375 | ui.add_space(2.0); |
| 1376 | if matches.is_empty() { |
| 1377 | ui.weak("일치하는 행동이 없습니다"); |
| 1378 | } |
| 1379 | for (k, a) in matches.iter().enumerate() { |
| 1380 | let b = Button::selectable(k == q.selected, a.label()) |
| 1381 | .shortcut_text(a.shortcut()) |
| 1382 | .min_size(vec2(ui.available_width(), 0.0)); |
| 1383 | let resp = ui.add(b); |
| 1384 | if resp.clicked() { |
| 1385 | run = Some(*a); |
| 1386 | } |
| 1387 | if resp.hovered() && ui.input(|i| i.pointer.delta() != egui::Vec2::ZERO) { |
| 1388 | q.selected = k; |
| 1389 | } |
| 1390 | } |
| 1391 | }); |
| 1392 | }); |
| 1393 | if area.response.clicked_elsewhere() { |
| 1394 | close = true; |
| 1395 | } |
| 1396 | if run.is_some() || close { |
| 1397 | self.quick = None; |
| 1398 | } |
| 1399 | if let Some(a) = run { |
| 1400 | self.run(ctx, a); |
| 1401 | } |
| 1402 | } |
| 1403 | |
| 1404 | fn unsaved_dialog(&mut self, ctx: &egui::Context) { |
| 1405 | let Some(p) = self.pending.clone() else { return }; |
| 1406 | let mut choice = None; |
| 1407 | if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { |
| 1408 | choice = Some(2); |
| 1409 | } |
| 1410 | Modal::new(Id::unique("unsaved_dialog")).show(ctx, |ui| { |
| 1411 | ui.label("저장되지 않은 변경사항이 있습니다. 저장하시겠습니까?"); |
| 1412 | ui.add_space(10.0); |
| 1413 | ui.horizontal(|ui| { |
| 1414 | if ui.button("저장하지 않고 계속").clicked() { |
| 1415 | choice = Some(0); |
| 1416 | } |
| 1417 | if ui.button("저장 후 계속").clicked() { |
| 1418 | choice = Some(1); |
| 1419 | } |
| 1420 | if ui.button("취소").clicked() { |
| 1421 | choice = Some(2); |
| 1422 | } |
| 1423 | }); |
| 1424 | }); |
| 1425 | match choice { |
| 1426 | Some(0) => { |
| 1427 | self.pending = None; |
| 1428 | self.do_pending(ctx, p); |
| 1429 | } |
| 1430 | Some(1) => { |
| 1431 | self.pending = None; |
| 1432 | if self.save() { |
| 1433 | self.do_pending(ctx, p); |
| 1434 | } |
| 1435 | } |
| 1436 | Some(_) => self.pending = None, |
| 1437 | None => {} |
| 1438 | } |
| 1439 | } |
| 1440 | |
| 1441 | fn error_dialog(&mut self, ctx: &egui::Context) { |
| 1442 | let Some(msg) = &self.error else { return }; |
| 1443 | let mut close = ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape) || i.consume_key(Modifiers::NONE, Key::Enter)); |
| 1444 | Modal::new(Id::unique("error_dialog")).show(ctx, |ui| { |
| 1445 | ui.set_max_width(560.0); |
| 1446 | ui.colored_label(ui.visuals().error_fg_color, "오류"); |
| 1447 | ui.label(msg.as_str()); |
| 1448 | ui.add_space(8.0); |
| 1449 | if ui.button("확인").clicked() { |
| 1450 | close = true; |
| 1451 | } |
| 1452 | }); |
| 1453 | if close { |
| 1454 | self.error = None; |
| 1455 | } |
| 1456 | } |
| 1457 | } |
| 1458 | |
| 1459 | impl eframe::App for App { |
| 1460 | fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { |
| 1461 | let ctx = ui.ctx().clone(); |
| 1462 | self.handle_close_request(&ctx); |
| 1463 | self.handle_shortcuts(&ctx); |
| 1464 | self.clamp_state(); |
| 1465 | self.update_title(&ctx); |
| 1466 | |
| 1467 | egui::Panel::top("menu_bar").show(ui, |ui| { |
| 1468 | egui::MenuBar::new().ui(ui, |ui| self.menu_bar(ui)); |
| 1469 | }); |
| 1470 | egui::Panel::bottom("status_bar").show(ui, |ui| self.status_bar(ui)); |
| 1471 | egui::Panel::left("sidebar").default_size(300.0).show(ui, |ui| self.sidebar(ui)); |
| 1472 | egui::CentralPanel::default().show(ui, |ui| self.messages_view(ui)); |
| 1473 | |
| 1474 | self.editor_window(&ctx); |
| 1475 | self.library_window(&ctx); |
| 1476 | self.quick_menu(&ctx); |
| 1477 | self.unsaved_dialog(&ctx); |
| 1478 | self.error_dialog(&ctx); |
| 1479 | } |
| 1480 | } |
| 1481 | |
| 1482 | // --------------------------------------------------------------------------- |
| 1483 | // 보조 함수 |
| 1484 | // --------------------------------------------------------------------------- |
| 1485 | |
| 1486 | /// 기본 글자 크기 16px 기준의 스타일. 애니메이션은 모두 끈다. |
| 1487 | fn apply_style(s: &mut egui::Style) { |
| 1488 | use egui::{FontFamily, FontId}; |
| 1489 | // egui의 UI 애니메이션(창/모달/메뉴/팝업 fade 등)은 전부 animation_time을 따른다. |
| 1490 | s.animation_time = 0.0; |
| 1491 | // 스크롤도 즉시: 목표 위치로 바로 이동하고, 관성/튕김(rubber band) 효과를 끈다. |
| 1492 | s.scroll_animation = egui::style::ScrollAnimation::none(); |
| 1493 | s.spacing.scroll.kinetic.decay_time = 0.0; |
| 1494 | s.spacing.scroll.kinetic.rubber_band = false; |
| 1495 | s.text_styles = [ |
| 1496 | (TextStyle::Small, FontId::new(12.0, FontFamily::Proportional)), |
| 1497 | (TextStyle::Body, FontId::new(16.0, FontFamily::Proportional)), |
| 1498 | (TextStyle::Button, FontId::new(16.0, FontFamily::Proportional)), |
| 1499 | (TextStyle::Heading, FontId::new(22.0, FontFamily::Proportional)), |
| 1500 | // 고정폭 글꼴은 같은 크기에서 더 커 보여서 한 단계 작게. |
| 1501 | (TextStyle::Monospace, FontId::new(15.0, FontFamily::Monospace)), |
| 1502 | ] |
| 1503 | .into(); |
| 1504 | // 글자에 맞춰 위젯 크기도 키운다 (기본 13px 기준 값을 약 1.2배). |
| 1505 | s.spacing.interact_size = vec2(48.0, 24.0); |
| 1506 | s.spacing.button_padding = vec2(8.0, 3.0); |
| 1507 | s.spacing.item_spacing = vec2(8.0, 4.0); |
| 1508 | s.spacing.icon_width = 17.0; |
| 1509 | s.spacing.icon_width_inner = 10.0; |
| 1510 | } |
| 1511 | |
| 1512 | fn shortcut_button(ui: &mut egui::Ui, label: &str, shortcut: &str) -> egui::Response { |
| 1513 | ui.add(Button::new(label).shortcut_text(shortcut)) |
| 1514 | } |
| 1515 | |
| 1516 | fn role_color(role: Role) -> Color32 { |
| 1517 | match role { |
| 1518 | Role::System => Color32::from_rgb(170, 120, 220), |
| 1519 | Role::Tools => Color32::from_rgb(220, 140, 50), |
| 1520 | Role::Tool => Color32::from_rgb(40, 170, 160), |
| 1521 | Role::User => Color32::from_rgb(70, 140, 230), |
| 1522 | Role::Assistant => Color32::from_rgb(70, 175, 90), |
| 1523 | } |
| 1524 | } |
| 1525 | |
| 1526 | /// 긴 메시지는 목록에서 잘라서 보여준다(전체는 편집 창에서). |
| 1527 | fn clip(s: &str, max_lines: usize, max_chars: usize) -> String { |
| 1528 | let mut out = String::new(); |
| 1529 | let mut lines = 0; |
| 1530 | let mut truncated = false; |
| 1531 | for (n, line) in s.lines().enumerate() { |
| 1532 | if n >= max_lines || out.chars().count() + line.chars().count() > max_chars { |
| 1533 | if n < max_lines && out.chars().count() < max_chars { |
| 1534 | let take = max_chars - out.chars().count(); |
| 1535 | out.extend(line.chars().take(take)); |
| 1536 | } |
| 1537 | truncated = true; |
| 1538 | break; |
| 1539 | } |
| 1540 | if n > 0 { |
| 1541 | out.push('\n'); |
| 1542 | } |
| 1543 | out.push_str(line); |
| 1544 | lines += 1; |
| 1545 | } |
| 1546 | if truncated { |
| 1547 | let rest = s.lines().count().saturating_sub(lines); |
| 1548 | out.push_str(&format!("\n… ({rest}줄 더)")); |
| 1549 | } |
| 1550 | out |
| 1551 | } |
| 1552 | |
| 1553 | fn message_body(ui: &mut egui::Ui, i: usize, m: &Message) { |
| 1554 | ui.horizontal(|ui| { |
| 1555 | ui.weak(format!("#{}", i + 1)); |
| 1556 | ui.label(RichText::new(m.role.as_str()).strong().color(role_color(m.role))); |
| 1557 | if m.role == Role::Tool && !m.tool_call_id.is_empty() { |
| 1558 | ui.weak(format!("tool_call_id: {}", m.tool_call_id)); |
| 1559 | } |
| 1560 | }); |
| 1561 | if m.role == Role::Assistant && !m.thinking.trim().is_empty() { |
| 1562 | ui.label(RichText::new("생각").small().weak()); |
| 1563 | markup_ui::label(ui, &clip(&m.thinking, 6, 600), true, true); |
| 1564 | } |
| 1565 | if m.role == Role::Tools |
| 1566 | && let Ok(list) = tools::parse_tool_list(&m.content) |
| 1567 | { |
| 1568 | if list.is_empty() { |
| 1569 | ui.weak("(도구 없음)"); |
| 1570 | } |
| 1571 | for t in &list { |
| 1572 | let line = RichText::new(format!("🧰 {}", tools_ui::signature(t))).monospace().strong(); |
| 1573 | ui.horizontal_wrapped(|ui| { |
| 1574 | ui.label(line); |
| 1575 | if !t.description.is_empty() { |
| 1576 | ui.weak(handmade_dataset_creator::model::one_line(&t.description, 100)); |
| 1577 | } |
| 1578 | }); |
| 1579 | } |
| 1580 | return; |
| 1581 | } |
| 1582 | if !m.content.is_empty() || m.tool_calls.is_empty() { |
| 1583 | let text = clip(&m.content, 15, 1500); |
| 1584 | let rt = if m.content_is_json || m.role == Role::Tools { RichText::new(&text).monospace() } else { RichText::new(&text) }; |
| 1585 | if m.content.is_empty() { |
| 1586 | ui.weak("(빈 메시지)"); |
| 1587 | } else if m.content_is_json { |
| 1588 | ui.add(egui::Label::new(rt).wrap()); |
| 1589 | } else { |
| 1590 | markup_ui::label(ui, &text, false, false); |
| 1591 | } |
| 1592 | } |
| 1593 | for tc in &m.tool_calls { |
| 1594 | let args = handmade_dataset_creator::model::one_line(&tc.arguments, 200); |
| 1595 | ui.add(egui::Label::new(RichText::new(format!("🔧 {}({})", tc.name, args)).monospace()).wrap()); |
| 1596 | } |
| 1597 | } |
| 1598 | |
| 1599 | fn editor_fields( |
| 1600 | ui: &mut egui::Ui, |
| 1601 | ed: &mut MessageEditor, |
| 1602 | library: &mut ToolLibrary, |
| 1603 | open_library: &mut Option<Option<String>>, |
| 1604 | ) { |
| 1605 | let focus = std::mem::take(&mut ed.focus_content); |
| 1606 | let msg = &mut ed.msg; |
| 1607 | let content_id = Id::unique("editor_content"); |
| 1608 | match msg.role { |
| 1609 | Role::Assistant => { |
| 1610 | ui.weak(markup_ui::SHORTCUT_HINT); |
| 1611 | ui.label("생각"); |
| 1612 | markup_ui::shortcuts(ui, Id::unique("editor_thinking"), &mut msg.thinking); |
| 1613 | ui.add( |
| 1614 | TextEdit::multiline(&mut msg.thinking) |
| 1615 | .id(Id::unique("editor_thinking")) |
| 1616 | .desired_rows(4) |
| 1617 | .desired_width(f32::INFINITY), |
| 1618 | ); |
| 1619 | ui.add_space(4.0); |
| 1620 | ui.label("메시지"); |
| 1621 | markup_ui::shortcuts(ui, content_id, &mut msg.content); |
| 1622 | let r = ui.add(TextEdit::multiline(&mut msg.content).id(content_id).desired_rows(8).desired_width(f32::INFINITY)); |
| 1623 | if focus { |
| 1624 | r.request_focus(); |
| 1625 | } |
| 1626 | ui.add_space(4.0); |
| 1627 | let (available, source) = match &ed.conv_tools { |
| 1628 | Some(list) => (list.as_slice(), "대화의 tools 메시지"), |
| 1629 | None => (library.tools.as_slice(), "도구 라이브러리"), |
| 1630 | }; |
| 1631 | tools_ui::tool_calls_fields(ui, &mut msg.tool_calls, available, source); |
| 1632 | } |
| 1633 | Role::Tool => { |
| 1634 | tools_ui::tool_call_id_field(ui, &mut msg.tool_call_id, &ed.call_choices); |
| 1635 | ui.label("도구 실행 결과"); |
| 1636 | markup_ui::shortcuts(ui, content_id, &mut msg.content); |
| 1637 | let r = ui.add(TextEdit::multiline(&mut msg.content).id(content_id).desired_rows(10).desired_width(f32::INFINITY)); |
| 1638 | if focus { |
| 1639 | r.request_focus(); |
| 1640 | } |
| 1641 | } |
| 1642 | Role::Tools => { |
| 1643 | tools_ui::tools_message_fields(ui, msg, &mut ed.tools_json_tab, library, open_library, focus); |
| 1644 | } |
| 1645 | Role::System | Role::User => { |
| 1646 | ui.weak(markup_ui::SHORTCUT_HINT); |
| 1647 | ui.label("메시지"); |
| 1648 | markup_ui::shortcuts(ui, content_id, &mut msg.content); |
| 1649 | let r = ui.add(TextEdit::multiline(&mut msg.content).id(content_id).desired_rows(12).desired_width(f32::INFINITY)); |
| 1650 | if focus { |
| 1651 | r.request_focus(); |
| 1652 | } |
| 1653 | } |
| 1654 | } |
| 1655 | } |
| 1656 | |
| 1657 | #[cfg(test)] |
| 1658 | mod tests { |
| 1659 | use super::*; |
| 1660 | use egui_kittest::Harness; |
| 1661 | |
| 1662 | fn ctrl(h: &mut Harness<'_, App>, key: Key) { |
| 1663 | h.key_press_modifiers(Modifiers::COMMAND, key); |
| 1664 | h.run(); |
| 1665 | } |
| 1666 | |
| 1667 | fn press(h: &mut Harness<'_, App>, key: Key) { |
| 1668 | h.key_press(key); |
| 1669 | h.run(); |
| 1670 | } |
| 1671 | |
| 1672 | fn type_text(h: &mut Harness<'_, App>, text: &str) { |
| 1673 | h.event(egui::Event::Text(text.to_string())); |
| 1674 | h.run(); |
| 1675 | } |
| 1676 | |
| 1677 | fn messages(h: &mut Harness<'_, App>) -> Vec<(Role, String)> { |
| 1678 | let app = h.state_mut(); |
| 1679 | let ci = app.current.unwrap(); |
| 1680 | app.doc.entries[ci].conversation().unwrap().messages.iter().map(|m| (m.role, m.content.clone())).collect() |
| 1681 | } |
| 1682 | |
| 1683 | fn add_message(h: &mut Harness<'_, App>, expected_role: Role, text: &str) { |
| 1684 | add_message_as(h, expected_role, expected_role, text); |
| 1685 | } |
| 1686 | |
| 1687 | /// 기본 역할이 `expected_role`인지 확인한 뒤 `role`로 바꿔서 입력한다. |
| 1688 | fn add_message_as(h: &mut Harness<'_, App>, expected_role: Role, role: Role, text: &str) { |
| 1689 | ctrl(h, Key::A); |
| 1690 | let ed = h.state_mut().editor.as_mut().expect("Ctrl+A는 메시지 편집 창을 연다"); |
| 1691 | assert_eq!(ed.msg.role, expected_role); |
| 1692 | ed.msg.set_role(role); |
| 1693 | ed.focus_content = true; |
| 1694 | h.run(); |
| 1695 | type_text(h, text); // 메시지 입력란에 자동 포커스되어 있어야 한다 |
| 1696 | ctrl(h, Key::Enter); |
| 1697 | assert!(h.state().editor.is_none()); |
| 1698 | } |
| 1699 | |
| 1700 | fn harness() -> Harness<'static, App> { |
| 1701 | let mut h = Harness::builder() |
| 1702 | .allow_missing_glyphs() |
| 1703 | .with_accessibility_check(false) |
| 1704 | .with_size(vec2(1100.0, 800.0)) |
| 1705 | .build_eframe(|cc| App::new(cc, None)); |
| 1706 | h.run(); |
| 1707 | h |
| 1708 | } |
| 1709 | |
| 1710 | #[test] |
| 1711 | fn editor_context_finds_unanswered_call() { |
| 1712 | let line = r#"{"messages":[{"role":"tools","content":[{"type":"function","function":{"name":"a"}}]},{"role":"assistant","content":"","tool_calls":[{"id":"c1","type":"function","function":{"name":"a","arguments":{}}},{"id":"c2","type":"function","function":{"name":"a","arguments":{}}}]},{"role":"tool","tool_call_id":"c1","content":"ok"}]}"#; |
| 1713 | let conv = Conversation::parse_line(line).unwrap(); |
| 1714 | let cx = editor_context(&conv, 3); |
| 1715 | assert_eq!(cx.unanswered.as_deref(), Some("c2")); |
| 1716 | assert_eq!(cx.call_choices.len(), 2); |
| 1717 | assert_eq!(cx.conv_tools.unwrap()[0].name, "a"); |
| 1718 | assert!(editor_context(&conv, 0).conv_tools.is_none()); |
| 1719 | } |
| 1720 | |
| 1721 | #[test] |
| 1722 | fn tools_workflow() { |
| 1723 | use egui_kittest::kittest::Queryable; |
| 1724 | let mut h = harness(); |
| 1725 | let weather = serde_json::json!({"type":"function","function":{"name":"get_weather","parameters":{ |
| 1726 | "type":"object","properties":{"city":{"type":"string"},"unit":{"type":"string","enum":["c","f"]}},"required":["city"]}}}); |
| 1727 | h.state_mut().library.tools.push(ToolDef::from_value(&weather).unwrap()); |
| 1728 | let ctx = h.ctx.clone(); |
| 1729 | h.state_mut().run(&ctx, Action::NewConversation); |
| 1730 | h.run(); |
| 1731 | |
| 1732 | // tools 메시지: 체크박스로 라이브러리 도구 넣기 |
| 1733 | ctrl(&mut h, Key::A); |
| 1734 | { |
| 1735 | let ed = h.state_mut().editor.as_mut().unwrap(); |
| 1736 | ed.msg.set_role(Role::Tools); |
| 1737 | assert!(!ed.tools_json_tab, "라이브러리가 있으면 선택 탭이 기본"); |
| 1738 | } |
| 1739 | h.run(); |
| 1740 | h.get_by_label("get_weather(city*, unit)").click(); |
| 1741 | h.run(); |
| 1742 | let content = h.state().editor.as_ref().unwrap().msg.content.clone(); |
| 1743 | assert_eq!(tools::parse_tool_list(&content).unwrap().len(), 1); |
| 1744 | ctrl(&mut h, Key::Enter); |
| 1745 | |
| 1746 | add_message(&mut h, Role::User, "날씨?"); |
| 1747 | |
| 1748 | // assistant: 도구 선택 → 필수 인자 뼈대 자동 입력 |
| 1749 | ctrl(&mut h, Key::A); |
| 1750 | { |
| 1751 | let ed = h.state().editor.as_ref().unwrap(); |
| 1752 | assert_eq!(ed.msg.role, Role::Assistant); |
| 1753 | assert!(ed.conv_tools.is_some(), "대화의 tools 메시지를 기준으로 자동완성"); |
| 1754 | } |
| 1755 | h.get_by_label("+ 도구 호출 추가").click(); |
| 1756 | h.run(); |
| 1757 | h.get(egui_kittest::kittest::By::new().value("도구 선택 ▾")).click(); |
| 1758 | h.run(); |
| 1759 | h.get_by_label("get_weather(city*, unit)").click(); |
| 1760 | h.run(); |
| 1761 | { |
| 1762 | let tc = &h.state().editor.as_ref().unwrap().msg.tool_calls[0]; |
| 1763 | assert_eq!(tc.name, "get_weather"); |
| 1764 | let args: serde_json::Value = serde_json::from_str(&tc.arguments).unwrap(); |
| 1765 | assert_eq!(args, serde_json::json!({"city": ""})); |
| 1766 | } |
| 1767 | // 폼: 문자열 인자에 따옴표/줄바꿈을 그대로 붙여넣어도 JSON이 깨지지 않는다 |
| 1768 | { |
| 1769 | let field = h.get( |
| 1770 | egui_kittest::kittest::By::new() |
| 1771 | .label("city *") |
| 1772 | .role(egui::accesskit::Role::MultilineTextInput), |
| 1773 | ); |
| 1774 | field.focus(); |
| 1775 | } |
| 1776 | h.run(); |
| 1777 | type_text(&mut h, "서울 \"강남구\"\n역삼동"); |
| 1778 | { |
| 1779 | let tc = &h.state().editor.as_ref().unwrap().msg.tool_calls[0]; |
| 1780 | let args: serde_json::Value = serde_json::from_str(&tc.arguments).unwrap(); |
| 1781 | assert_eq!(args, serde_json::json!({"city": "서울 \"강남구\"\n역삼동"})); |
| 1782 | } |
| 1783 | |
| 1784 | // 이름 자동완성: "get" 입력 → Tab으로 확정 (두 번째 호출) |
| 1785 | h.get_by_label("+ 도구 호출 추가").click(); |
| 1786 | h.run(); |
| 1787 | { |
| 1788 | let names = h.query_all( |
| 1789 | egui_kittest::kittest::By::new().label("이름").role(egui::accesskit::Role::TextInput), |
| 1790 | ); |
| 1791 | names.last().unwrap().focus(); |
| 1792 | } |
| 1793 | h.run(); |
| 1794 | type_text(&mut h, "get"); |
| 1795 | press(&mut h, Key::Tab); |
| 1796 | { |
| 1797 | let tc = &h.state().editor.as_ref().unwrap().msg.tool_calls[1]; |
| 1798 | assert_eq!(tc.name, "get_weather"); |
| 1799 | let args: serde_json::Value = serde_json::from_str(&tc.arguments).unwrap(); |
| 1800 | assert_eq!(args, serde_json::json!({"city": ""}), "확정하면 필수 인자 뼈대도 채움"); |
| 1801 | } |
| 1802 | |
| 1803 | ctrl(&mut h, Key::Enter); |
| 1804 | assert_eq!(messages(&mut h).len(), 3); |
| 1805 | assert!(h.state().is_dirty()); |
| 1806 | } |
| 1807 | |
| 1808 | #[test] |
| 1809 | fn library_is_saved_next_to_dataset() { |
| 1810 | use egui_kittest::kittest::Queryable; |
| 1811 | let dir = std::env::temp_dir().join(format!("hdc-lib-{}", std::process::id())); |
| 1812 | std::fs::create_dir_all(&dir).unwrap(); |
| 1813 | let data = dir.join("set.jsonl"); |
| 1814 | let lib_file = dir.join("set.tools.json"); |
| 1815 | let mut h = harness(); |
| 1816 | h.state_mut().doc.path = Some(data.clone()); |
| 1817 | let ctx = h.ctx.clone(); |
| 1818 | let saved_names = || -> Vec<String> { |
| 1819 | let text = std::fs::read_to_string(&lib_file).unwrap_or_default(); |
| 1820 | tools::parse_tool_list(&text).unwrap_or_default().into_iter().map(|t| t.name).collect() |
| 1821 | }; |
| 1822 | |
| 1823 | // 1) 라이브러리 창 안에서 Ctrl+S → 창 내용을 반영하고 데이터셋과 라이브러리를 저장 |
| 1824 | h.state_mut().run(&ctx, Action::ToolLibrary); |
| 1825 | h.run(); |
| 1826 | h.get_by_label("+ 새 도구").click(); |
| 1827 | h.run(); |
| 1828 | type_text(&mut h, "first"); |
| 1829 | ctrl(&mut h, Key::S); |
| 1830 | assert!(h.state().library_editor.is_none()); |
| 1831 | assert_eq!(saved_names(), ["first"]); |
| 1832 | assert!(data.exists()); |
| 1833 | assert!(!h.state().is_dirty()); |
| 1834 | |
| 1835 | // 2) 확인(Ctrl+Enter)만 눌러도 라이브러리 파일은 바로 저장 |
| 1836 | h.state_mut().run(&ctx, Action::ToolLibrary); |
| 1837 | h.run(); |
| 1838 | h.get_by_label("+ 새 도구").click(); |
| 1839 | h.run(); |
| 1840 | type_text(&mut h, "second"); |
| 1841 | ctrl(&mut h, Key::Enter); |
| 1842 | assert_eq!(saved_names(), ["first", "second"]); |
| 1843 | assert!(!h.state().library.dirty); |
| 1844 | std::fs::remove_dir_all(&dir).ok(); |
| 1845 | } |
| 1846 | |
| 1847 | #[test] |
| 1848 | fn recent_files_menu_reopens() { |
| 1849 | use egui_kittest::kittest::{By, Queryable}; |
| 1850 | let dir = std::env::temp_dir().join(format!("hdc-recent-ui-{}", std::process::id())); |
| 1851 | std::fs::create_dir_all(&dir).unwrap(); |
| 1852 | let a = dir.join("a.jsonl"); |
| 1853 | let b = dir.join("b.jsonl"); |
| 1854 | std::fs::write(&a, "{\"messages\":[{\"role\":\"user\",\"content\":\"A\"}]}\n").unwrap(); |
| 1855 | std::fs::write(&b, "").unwrap(); |
| 1856 | |
| 1857 | let mut h = harness(); |
| 1858 | h.state_mut().open_path(&a); |
| 1859 | h.state_mut().open_path(&b); |
| 1860 | assert_eq!(h.state().recent.paths.len(), 2); |
| 1861 | assert!(h.state().recent.paths[0].ends_with("b.jsonl"), "가장 최근 것이 맨 위"); |
| 1862 | |
| 1863 | // 파일 > 최근에 연 파일 > a.jsonl |
| 1864 | h.get_by_label("파일").click(); |
| 1865 | h.run(); |
| 1866 | h.get_by_label("최근에 연 파일").click(); |
| 1867 | h.run(); |
| 1868 | h.get(By::new().label_contains("a.jsonl")).click(); |
| 1869 | h.run(); |
| 1870 | assert!(h.state().doc.path.as_ref().unwrap().ends_with("a.jsonl")); |
| 1871 | assert_eq!(h.state().doc.len(), 1); |
| 1872 | assert!(h.state().recent.paths[0].ends_with("a.jsonl")); |
| 1873 | |
| 1874 | // 사라진 파일은 오류를 띄우고 목록에서 뺀다 |
| 1875 | std::fs::remove_file(&b).unwrap(); |
| 1876 | let gone = h.state().recent.paths[1].clone(); |
| 1877 | let ctx = h.ctx.clone(); |
| 1878 | h.state_mut().do_pending(&ctx, Pending::Open(gone)); |
| 1879 | assert!(h.state().error.is_some()); |
| 1880 | assert_eq!(h.state().recent.paths.len(), 1); |
| 1881 | std::fs::remove_dir_all(&dir).ok(); |
| 1882 | } |
| 1883 | |
| 1884 | #[test] |
| 1885 | fn markup_shortcuts_in_editor() { |
| 1886 | let mut h = harness(); |
| 1887 | let ctx = h.ctx.clone(); |
| 1888 | h.state_mut().run(&ctx, Action::NewConversation); |
| 1889 | h.run(); |
| 1890 | ctrl(&mut h, Key::A); // 메시지 편집 창 (system), 입력란에 자동 포커스 |
| 1891 | type_text(&mut h, "정보를 선별"); |
| 1892 | let content = |h: &Harness<'_, App>| h.state().editor.as_ref().unwrap().msg.content.clone(); |
| 1893 | |
| 1894 | ctrl(&mut h, Key::A); // 입력란 안에서는 전체 선택 |
| 1895 | ctrl(&mut h, Key::U); |
| 1896 | assert_eq!(content(&h), "<u>정보를 선별</u>"); |
| 1897 | ctrl(&mut h, Key::U); // 같은 선택으로 다시 누르면 해제 |
| 1898 | assert_eq!(content(&h), "정보를 선별"); |
| 1899 | ctrl(&mut h, Key::M); |
| 1900 | assert_eq!(content(&h), "<mark>정보를 선별</mark>"); |
| 1901 | h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::X); |
| 1902 | h.run(); |
| 1903 | assert_eq!(content(&h), "<mark>~~정보를 선별~~</mark>"); |
| 1904 | ctrl(&mut h, Key::B); |
| 1905 | assert_eq!(content(&h), "<mark>~~**정보를 선별**~~</mark>"); |
| 1906 | |
| 1907 | ctrl(&mut h, Key::Enter); |
| 1908 | assert_eq!(messages(&mut h)[0].1, "<mark>~~**정보를 선별**~~</mark>"); |
| 1909 | } |
| 1910 | |
| 1911 | #[test] |
| 1912 | fn keyboard_workflow() { |
| 1913 | let mut h = harness(); |
| 1914 | |
| 1915 | // 퀵 메뉴로 대화 생성 |
| 1916 | press(&mut h, Key::Backtick); |
| 1917 | assert!(h.state().quick.is_some()); |
| 1918 | type_text(&mut h, "대화 생성"); |
| 1919 | press(&mut h, Key::Enter); |
| 1920 | assert!(h.state().quick.is_none()); |
| 1921 | assert_eq!(h.state().doc.len(), 1); |
| 1922 | assert_eq!(h.state().current, Some(0)); |
| 1923 | |
| 1924 | add_message(&mut h, Role::System, "sys"); |
| 1925 | add_message_as(&mut h, Role::Tools, Role::User, "hi"); // system 다음 기본값은 tools |
| 1926 | add_message(&mut h, Role::Assistant, "hello"); |
| 1927 | |
| 1928 | // assistant 다음 기본 역할은 user, Esc로 취소 |
| 1929 | ctrl(&mut h, Key::A); |
| 1930 | assert_eq!(h.state().editor.as_ref().unwrap().msg.role, Role::User); |
| 1931 | press(&mut h, Key::Escape); |
| 1932 | assert!(h.state().editor.is_none()); |
| 1933 | assert_eq!(messages(&mut h).len(), 3); |
| 1934 | |
| 1935 | // 마지막 메시지(hello)가 선택된 상태 → 복제 후 위로 이동 |
| 1936 | ctrl(&mut h, Key::D); |
| 1937 | assert_eq!(messages(&mut h).len(), 4); |
| 1938 | ctrl(&mut h, Key::ArrowUp); |
| 1939 | ctrl(&mut h, Key::ArrowUp); |
| 1940 | let contents: Vec<String> = messages(&mut h).into_iter().map(|m| m.1).collect(); |
| 1941 | assert_eq!(contents, ["sys", "hello", "hi", "hello"]); |
| 1942 | |
| 1943 | // 되돌리기/다시하기 |
| 1944 | // 첫 Ctrl+↑는 같은 내용끼리 자리만 바뀌어 기록되지 않는다 → 두 번(이동, 복제) 되돌리면 3개. |
| 1945 | ctrl(&mut h, Key::Z); |
| 1946 | ctrl(&mut h, Key::Z); |
| 1947 | assert_eq!(messages(&mut h).len(), 3); |
| 1948 | h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z); |
| 1949 | h.run(); |
| 1950 | assert_eq!(messages(&mut h).len(), 4); |
| 1951 | |
| 1952 | // Del: 메시지 영역에 포커스가 있으면 선택한 메시지 삭제 |
| 1953 | press(&mut h, Key::Delete); |
| 1954 | assert_eq!(messages(&mut h).len(), 3); |
| 1955 | |
| 1956 | // 사이드바 포커스에서 Del → 대화 삭제 |
| 1957 | h.state_mut().focus = Focus::Sidebar; |
| 1958 | press(&mut h, Key::Delete); |
| 1959 | assert_eq!(h.state().doc.len(), 0); |
| 1960 | assert!(h.state().doc.is_dirty()); |
| 1961 | } |
| 1962 | } |