${hits.map((h, i) => {
const b = bot(h.bot) || {};
- const where = h.thread != null ? `過去的對話` : "";
+ // (Which past conversation: its name — a project's, when the person named it.)
+ const where = h.thread != null ? `${esc(h.thread_title || "過去的對話")}` : "";
const what = (h.file ? "📎 " + h.file + " " : "") + (h.snippet || "");
return `
${avatarSvg(b.shape, b.color)}
${esc(h.bot_name || b.name || "")}${where}
${esc(what)}
${ago(h.at)}
`;
}).join("")}
`;
@@ -1600,8 +1602,10 @@ async function openHit(i) {
const h = ((S.hits || {}).hits || [])[i];
if (!h) return;
if (h.thread != null) {
+ const b = bot(h.bot) || {};
+ if (b.busy) { toast(`「${b.name || h.bot_name}」正在工作。等它做完(或先按停止),再換對話。`); return; }
if (!await confirmSheet("回到這段對話?", `「${h.thread_title || "對話"}」會換回來,現在的對話留在「過去的對話」裡。`, "回到這段對話", false)) return;
- try { await api(base() + `api/bots/${h.bot}/restore`, {json: {index: h.thread}}); } catch (e) { toast(e.message); return; }
+ try { await api(base() + `api/bots/${h.bot}/restore`, {json: {index: h.thread, at: h.thread_at || 0, was: h.thread_title || ""}}); } catch (e) { toast(e.message); return; }
}
go("chat", {bot: h.bot, at: h.at});
}
@@ -1796,7 +1800,7 @@ $("b-me").onclick = () => {
"use strict";
// ---------- chat ----------
$("isl-chev").innerHTML = ic("chevron-right", 14);
-$("b-newchat").innerHTML = ic("pen", 19); $("b-chatmore").innerHTML = ic("ellipsis", 20);
+$("b-newchat").innerHTML = ic("pen", 19); $("b-chats").innerHTML = ic("history", 19); $("b-chatmore").innerHTML = ic("ellipsis", 20);
$("b-plus").innerHTML = ic("plus", 16); $("b-mic").innerHTML = ic("mic", 18); $("b-down").innerHTML = ic("arrow-down", 18);
const ST = {waiting: "circle-alert", running: "loader", done: "circle-check", denied: "minus", failed: "circle-x"};
// What the bot is doing, in the words the desktop uses (its status line, or a waiting question).
@@ -1804,7 +1808,8 @@ function chatSub(b) {
const a = S.approvals.find((x) => x.bot === b.id);
if (a) return ["wait", a.kind === "handoff" ? "需要你的輸入" : a.kind === "question" ? "等你回答" : "需要你核准"];
if (b.busy) return ["busy", b.status || "工作中…"];
- return ["", b.model || ""];
+ // (A conversation the person named says which one this is.)
+ return ["", b.chat_named ? b.chat_title + (b.model ? " · " + b.model : "") : b.model || ""];
}
function chatHead() {
const b = bot(S.open);
@@ -1815,6 +1820,8 @@ function chatHead() {
$("isl-sub").className = "s " + cls; $("isl-sub").textContent = text;
$("input").placeholder = "傳訊息給 " + b.name;
$("b-newchat").style.display = owner() ? "" : "none";
+ // (A team member can't change conversations: the brain refuses it.)
+ $("b-chats").style.display = owner() ? "" : "none";
}
$("island").onclick = () => go("details", {bot: S.open});
// 存在這支手機上的(這個網址自己的儲存空間,登出就全部清掉):每台電腦上次的狀態、看過的聊天、
@@ -3006,23 +3013,47 @@ $("b-chatmore").onclick = () => {
const b = bot(S.open); if (!b) return;
const items = [
{icon: "info", label: "對話詳細資訊", on: () => go("details", {bot: b.id})},
- {icon: "history", label: "過去的對話", x: String((b.threads || []).length || ""), on: () => threads(b)},
+ ...(owner() ? [{icon: "history", label: "對話", x: String(b.threads_total || (b.threads || []).length || ""), on: () => threads(b)}] : []),
{icon: "copy", label: "複製整段對話", on: () => copyText(S.msgs.filter((m) => m.text && !m.summary).map((m) => (m.role === "user" ? "我:" : b.name + ":") + m.text).join("\n\n"))},
...(owner() ? [{icon: "download", label: "匯出文字記錄(.md)", on: () => exportAs("export_transcript", b.id)}] : []),
];
if (owner()) items.splice(1, 0, {icon: "refresh", label: "重新產生上一個回答", on: regen});
if (isOwner()) items.push({icon: "settings", label: "Bot 設定", on: () => go("botset", {bot: b.id})});
- if (isOwner()) items.push({icon: "trash", label: "清除聊天記錄", danger: true, on: async () => { if (await confirmSheet("清除聊天記錄?", "這段對話的訊息會全部刪除,無法復原。", "清除")) { await act("clear", {bot: b.id}); setTimeout(() => loadChat(true), 500); } }});
+ if (isOwner()) items.push({icon: "trash", label: "清除聊天記錄", danger: true, on: async () => { if (await confirmSheet("清除聊天記錄?", "這段對話的訊息會全部刪除,無法復原。", "清除")) { await act("clear", {bot: b.id, was: b.chat_title || ""}); setTimeout(() => loadChat(true), 500); } }});
sheet(b.name, items);
};
+// 對話 (the title bar's 🕘, 更多 › 對話): the open conversation (a tap names it), then 過去的對話,
+// newest first (a tap: 回到這段對話 or 重新命名). Each is found by its last message's time too: a
+// list that moved since (one opened on another device) still names the same one.
function threads(b) {
- const list = b.threads || [];
- if (!list.length) { toast("還沒有過去的對話"); return; }
- sheet("過去的對話", list.map((t) => ({icon: "message", label: t.title || "對話", x: ago(t.at), on: async () => {
- if (!await confirmSheet("回到這段對話?", "現在的對話會留在「過去的對話」裡。", "回到這段對話", false)) return;
- try { await api(base() + `api/bots/${b.id}/restore`, {json: {index: t.index}}); toast("已回到那段對話"); S.unfold = {}; setTimeout(() => loadChat(true), 700); } catch (e) { toast(e.message); }
- }})));
+ const list = b.threads || [], total = b.threads_total || list.length;
+ // (A brain from before names: no 命名 — it would answer 「沒有這個動作」.)
+ const named = b.chat_title !== undefined;
+ sheet("對話", [
+ {group: "目前的對話"},
+ {icon: "message", label: b.chat_title || "對話", x: named ? "命名" : "", on: () => named ? renameChat(b, null) : toast("這台大腦還不能為對話取名:先更新它的 AnyBot")},
+ {group: list.length ? (total > list.length ? `過去的對話(最新 ${list.length} 段,共 ${total} 段)` : "過去的對話") : "還沒有過去的對話"},
+ ...list.map((t) => ({icon: "history", label: t.title || "對話", x: ago(t.at), on: () => threadActions(b, t)})),
+ ]);
}
+function threadActions(b, t) {
+ sheet(t.title || "對話", [
+ {icon: "history", label: "回到這段對話", on: async () => {
+ // (Not while it works: changing the conversation would stop it.)
+ if ((bot(b.id) || b).busy) { toast(`「${b.name}」正在工作。等它做完(或先按停止),再換對話。`); return; }
+ try { await api(base() + `api/bots/${b.id}/restore`, {json: {index: t.index, at: t.at, was: t.title || ""}}); toast("已回到那段對話"); S.unfold = {}; kick(); setTimeout(() => loadChat(true), 700); } catch (e) { toast(e.message); }
+ }},
+ ...(b.chat_title !== undefined ? [{icon: "pen", label: "重新命名", on: () => renameChat(b, t)}] : []),
+ {label: "取消"},
+ ], `
回到這段對話時,現在的對話留在「過去的對話」裡。
`);
+}
+async function renameChat(b, t) {
+ const name = await ask(t ? "為這段對話命名" : "為目前的對話命名", t ? t.title || "" : (b.chat_named ? b.chat_title : ""), "例如:網站改版(空白=用第一句話)");
+ if (name === null) return;
+ // (With the name it showed: another device may have opened or renamed another meanwhile.)
+ try { await api(base() + `api/bots/${b.id}/rename`, {json: t ? {index: t.index, at: t.at, was: t.title || "", title: name} : {was: b.chat_title || "", title: name}}); toast(name ? `已命名「${name}」` : "改回用第一句話"); kick(); } catch (e) { toast(e.message); }
+}
+$("b-chats").onclick = () => { const b = bot(S.open); if (b) threads(b); };
// At the newest message, it stays in view while what is above it grows after being drawn (a
// picture that loads, a preview); scrolled up to read, nothing moves. (A question card taller
// than the screen is left where renderQuestion put it: its question, not its buttons.)
@@ -3509,7 +3540,7 @@ async function renderBotset(id) {
else if (k === "ctx") sheet("模型可讀長度", CTX.map(([n, l]) => ({label: l + " 個 token", check: n === d.context_tokens, on: async () => { if (await act("bot", {bot: id, key: "context", value: n}, "已更新")) refresh(); }})));
else if (k === "folder") moveToFolder(b);
else if (k === "restart") act("restart_bot", {bot: id});
- else if (k === "clear") { if (await confirmSheet("清除聊天記錄?", "這段對話的訊息會全部刪除,無法復原。", "清除")) act("clear", {bot: id}); }
+ else if (k === "clear") { if (await confirmSheet("清除聊天記錄?", "這段對話的訊息會全部刪除,無法復原。", "清除")) act("clear", {bot: id, was: (bot(id) || {}).chat_title || ""}); }
else if (k === "delete") deleteBot(b);
});
}
diff --git a/src/agent.rs b/src/agent.rs
index 6e9510f..d8d0064 100644
--- a/src/agent.rs
+++ b/src/agent.rs
@@ -358,7 +358,7 @@ fn parse_verdict(text: &str) -> ReviewVerdict {
/// the person tells the bot to keep is another matter: that is `remember`, the bot's own call.)
pub(crate) fn worth_noting(turn: &[Message]) -> bool {
let calls: Vec<&str> = turn.iter().flat_map(|m| m.tool_calls.iter().map(|c| c.name.as_str())).collect();
- let quiet = |n: &str| only_looks(n) || matches!(n, "remember" | "forget" | "search_memory" | "search_documents" | "use_skill" | "react" | "show_card" | crate::ask::TOOL | "list_routines" | crate::tasks::TOOL | "list_bots" | "list_computers");
+ let quiet = |n: &str| only_looks(n) || matches!(n, "remember" | "forget" | "search_memory" | "search_documents" | "use_skill" | "react" | "show_card" | crate::ask::TOOL | "list_routines" | crate::tasks::TOOL | "list_bots" | "list_computers" | "list_conversations");
calls.iter().any(|n| !quiet(n)) || calls.len() >= NOTE_MIN_LOOKS
}
/// This many steps of only looking are a piece of work too (a long research).
@@ -1685,7 +1685,7 @@ pub const QUICK_TROUBLE_MAX: usize = 2;
fn only_looks(name: &str) -> bool {
matches!(
name,
- "computer_use_screenshot" | "computer_use_zoom" | "computer_use_show" | "computer_use_check_permissions" | crate::outputs::TOOL | "browser_read" | "browser_screenshot" | "browser_elements" | "browser_find" | "browser_table" | "browser_tabs" | "browser_wait" | "browser_sent_log" | "anybot_guide" | "web_fetch" | "read_file" | "list_dir" | "search" | "read_terminal" | "list_computers" | "list_bots" | "list_routines" | crate::tasks::TOOL | "read_page" | "use_skill" | "react" | "show_card" | "search_documents" | "search_memory"
+ "computer_use_screenshot" | "computer_use_zoom" | "computer_use_show" | "computer_use_check_permissions" | crate::outputs::TOOL | "browser_read" | "browser_screenshot" | "browser_elements" | "browser_find" | "browser_table" | "browser_tabs" | "browser_wait" | "browser_sent_log" | "anybot_guide" | "web_fetch" | "read_file" | "list_dir" | "search" | "read_terminal" | "list_computers" | "list_bots" | "list_routines" | "list_conversations" | crate::tasks::TOOL | "read_page" | "use_skill" | "react" | "show_card" | "search_documents" | "search_memory"
)
}
diff --git a/src/app.rs b/src/app.rs
index b306098..d4d7e6c 100644
--- a/src/app.rs
+++ b/src/app.rs
@@ -289,6 +289,8 @@ pub struct App {
/// 「/compact」 summaries finished on their thread: (bot, (messages replaced, summary, first kept message's time)).
#[allow(clippy::type_complexity)]
compact_out: Arc)>>>,
+ /// Bots whose 「/compact」 is being written (its summary goes into the open conversation).
+ compacting: HashMap,
/// Bots whose running turn came from someone else's message (a channel, a teammate):
/// 一律放行 doesn't answer for them.
strangers: std::collections::HashSet,
@@ -426,6 +428,10 @@ pub struct App {
typed_on: Option,
/// 右側面板 and its tab (None = closed).
panel: Option,
+ /// 對話欄's 重新命名 under way.
+ chat_rename: Option,
+ /// The 對話欄 is open only because it was left open last time (not opened since).
+ chats_remembered: bool,
/// When each emoji reaction appeared (for its pop) and when each message first showed (fade-in).
popped: HashMap<(u64, usize, String), Instant>,
appeared: HashMap<(u64, usize), Instant>,
@@ -600,6 +606,7 @@ impl App {
ask_keys: Default::default(),
settled_by_direct: Default::default(),
compact_out: Default::default(),
+ compacting: Default::default(),
managed: if demo { policy::Managed::default() } else { policy::read() },
settings_was_open: false,
exe_built: crate::version::exe_modified(),
@@ -677,6 +684,8 @@ impl App {
asking: false,
typed_on: None,
panel: None,
+ chat_rename: None,
+ chats_remembered: false,
popped: HashMap::new(),
appeared: HashMap::new(),
steps_open: Default::default(),
@@ -709,6 +718,11 @@ impl App {
app.drafts.insert(b.id, b.draft.clone());
}
}
+ // 對話欄, left open last time.
+ if app.state.chats_column {
+ app.panel = Some(panel_ui::PanelTab::Chats);
+ app.chats_remembered = true;
+ }
crate::i18n::set(&app.state.language);
app.computers_start();
@@ -1426,9 +1440,10 @@ impl App {
if std::env::var("ANYBOT_SHOT_NOPOPUP").is_ok() {
app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id));
}
- // ANYBOT_SHOT_PANEL=1: the right panel open on any demo view (without starting the box).
- if std::env::var("ANYBOT_SHOT_PANEL").is_ok() {
- app.panel = Some(panel_ui::PanelTab::Activity);
+ // ANYBOT_SHOT_PANEL=1: the right panel open on any demo view (without starting the box);
+ // =chats: the 對話欄.
+ if let Ok(v) = std::env::var("ANYBOT_SHOT_PANEL") {
+ app.panel = Some(if v == "chats" { panel_ui::PanelTab::Chats } else { panel_ui::PanelTab::Activity });
}
// ANYBOT_SHOT_TAB=: 設定 open on that page (each page checked at any window size).
if let Ok(tab) = std::env::var("ANYBOT_SHOT_TAB") {
@@ -1646,6 +1661,12 @@ impl App {
if text.trim().is_empty() && !self.has_pending_attachments(bot_id) {
return;
}
+ // A new message to an idle bot: the person goes on here — a 換對話 it promised is off.
+ if !self.streams.contains_key(&bot_id) {
+ if let Some(b) = self.state.bot_mut(bot_id) {
+ b.chat_after = None;
+ }
+ }
// 診斷: 「/doctor」 checks this computer — here even on a screen of a brain, and above
// all when the brain can't be reached.
if crate::doctor::command(&text) {
@@ -2774,6 +2795,11 @@ impl App {
self.start_reply(ctx, id);
}
self.pending_turns.extend(held);
+ // 換對話 a bot was asked for in chat: now that its turn and what followed are over.
+ let asked: Vec = self.state.bots.iter().filter(|b| b.chat_after.is_some()).map(|b| b.id).collect();
+ for id in asked {
+ self.chat_after_turn(id);
+ }
}
/// The running turn of a bot is someone else's — a routine's, an event's, a workflow step's,
@@ -2867,6 +2893,11 @@ impl App {
}
fn stop(&mut self, bot_id: u64) {
+ // 停止 (and what stops it: 清除聊天記錄, 重新啟動, quitting) calls off a 換對話 the bot
+ // promised — the person stepped in; and it is never done under what stopping writes.
+ if let Some(b) = self.state.bot_mut(bot_id) {
+ b.chat_after = None;
+ }
if self.mir.on {
if self.streams.contains_key(&bot_id) || self.approvals.contains_key(&bot_id) {
self.mirror_act(serde_json::json!({"bot": bot_id, "action": "stop"}));
@@ -3939,6 +3970,8 @@ impl App {
memories: vec![],
members: vec![],
threads: Default::default(),
+ chat_title: String::new(),
+ chat_after: None,
context_tokens: agent::DEFAULT_CONTEXT_TOKENS,
model_limits: Default::default(),
follow_ups: vec![],
@@ -4164,23 +4197,7 @@ impl App {
}
// 討論串: put this conversation aside and start fresh; earlier ones can come back.
if menu_ui::item(ui, p, Icon::NewChat, "開始新對話").clicked() {
- if !self.mir.on {
- self.goal_drop(id);
- }
- self.stop(id);
- if self.mir.on {
- self.mirror_act(serde_json::json!({"bot": id, "action": "new"}));
- } else if let Some(b) = self.state.bot_mut(id) {
- if !b.messages.is_empty() {
- let title = b.messages.iter().find(|m| m.role == Role::User).map(|m| first_line(&m.text, 24)).unwrap_or_else(|| "對話".into());
- let mut msgs = std::mem::take(&mut b.messages);
- // (An earlier conversation keeps its words, not its screenshots in memory.)
- msgs.iter_mut().for_each(|m| m.images.clear());
- b.threads.insert(0, (title, msgs.into_inner()));
- b.threads.truncate(50);
- }
- }
- self.mark();
+ self.new_chat(id);
ui.close();
}
let threads: Vec = b.threads.iter().map(|t| t.0.clone()).collect();
@@ -4253,12 +4270,14 @@ impl App {
if self.mir.on {
// The chat lives on the brain: clearing only this copy left the brain sure this
// screen still had it, and its next changes landed in the wrong place.
- self.mirror_act(serde_json::json!({"bot": id, "action": "clear"}));
+ let was = self.state.bot(id).map(|b| b.chat_name()).unwrap_or_default();
+ self.mirror_act(serde_json::json!({"bot": id, "action": "clear", "was": was}));
} else {
self.goal_drop(id);
self.stop(id);
if let Some(b) = self.state.bot_mut(id) {
b.messages.clear();
+ b.chat_title.clear();
}
self.mark();
}
@@ -4414,6 +4433,21 @@ impl App {
right.spacing_mut().item_spacing.x = 8.0;
let more = pill_icon(&mut right, crate::icons::Icon::More, p).on_hover_text(t("更多"));
egui::Popup::menu(&more).show(|ui| self.bot_menu_items(ui, bot.id));
+ // 對話: which conversation this is (its name, once it has one); a click opens the column
+ // of this bot's conversations beside the chat, to switch in one click (it took ⋯ ›
+ // 過去的對話 › a name before).
+ // (Not beside a 工作流 canvas: no column is drawn there.) The name gets what room the
+ // title has left once the bot's name keeps its own; little room, just 「對話」.
+ if !self.wf.open {
+ let chats_on = self.panel == Some(PanelTab::Chats);
+ let room = (bar.width() - 420.0).min(150.0);
+ let label = if bot.chat_title.is_empty() || room < 48.0 { t("對話") } else { sidebar_ui::shorten_width(&right, &bot.chat_title, room, 13.0) };
+ let tip = if bot.threads.is_empty() { t("這個 Bot 的對話") } else { t("這個 Bot 的對話(過去的 {n} 段)").replace("{n}", &bot.threads.len().to_string()) };
+ let tip = if bot.chat_title.is_empty() || label == bot.chat_title { tip } else { format!("{}\n{tip}", bot.chat_title) };
+ if crate::icons::pill(&mut right, crate::icons::Icon::History, &label, if chats_on { p.active } else { Color32::TRANSPARENT }, p.text, 36.0).on_hover_text(tip).clicked() {
+ self.set_panel(if chats_on { None } else { Some(PanelTab::Chats) });
+ }
+ }
if pill_text(&mut right, &t("分享"), p).on_hover_text(t("匯出 Bot(分享給別人)…")).clicked() {
let (text, name) = (crate::share::export(bot), format!("{}.anybot", bot.name));
let note = self.ch.note.clone();
@@ -4456,9 +4490,10 @@ impl App {
ui.painter().galley(tag_rect.min, tag, tag_col);
ui.interact(tag_rect.expand(4.0), egui::Id::unique(("runs-tag", bot.id)), egui::Sense::hover()).on_hover_text(format!("{} · {}\n{}", bot.provider.label(), bot.model, runs.words(self.brain_for_words().as_deref())));
let _ = color;
- let open = self.panel.is_some();
+ // (The 對話欄 open, the name opens the details in its place.)
+ let open = self.panel.is_some_and(|t| t != PanelTab::Chats);
if r.on_hover_text(t(if open { "關閉對話詳細資訊" } else { "查看對話詳細資訊" })).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
- self.panel = if open { None } else { Some(PanelTab::Activity) };
+ self.set_panel(if open { None } else { Some(PanelTab::Activity) });
}
}
@@ -4728,27 +4763,75 @@ impl App {
}
}
- /// 過去的對話 number `i` becomes the open one (the open one goes to the top of the list). The
- /// bot's running turn, if any, is stopped first.
- fn open_thread(&mut self, id: u64, i: usize) {
- self.stop(id);
+ /// 開始新對話: the open conversation goes to 過去的對話 and the chat is empty (its goal and
+ /// running turn, if any, stop).
+ fn new_chat(&mut self, id: u64) {
+ // (A running turn is stopped, as before; a summary, a 支線 or a colleague's report on the
+ // way can't be, and would land in the new conversation.)
+ if let Some(why) = self.chat_pending(id, false) {
+ self.notice = Some(why);
+ return;
+ }
if self.mir.on {
- self.mirror_act(serde_json::json!({"bot": id, "action": "restore", "index": i}));
- } else if let Some(b) = self.state.bot_mut(id) {
- if i < b.threads.len() {
- let (_, msgs) = b.threads.remove(i);
- if !b.messages.is_empty() {
- let cur_title = b.messages.iter().find(|m| m.role == Role::User).map(|m| first_line(&m.text, 24)).unwrap_or_else(|| "對話".into());
- let mut cur = std::mem::take(&mut b.messages);
- cur.iter_mut().for_each(|m| m.images.clear());
- b.threads.insert(0, (cur_title, cur.into_inner()));
- }
- b.messages = msgs.into();
+ // (The brain stops the running turn itself, and only once it starts the new one: a
+ // stop sent first ended the turn even when the brain then kept the conversation for
+ // something this screen couldn't see.)
+ self.mirror_act(serde_json::json!({"bot": id, "action": "new"}));
+ } else {
+ self.leave_conversation(id);
+ self.stop(id);
+ if let Some(b) = self.state.bot_mut(id) {
+ b.put_aside();
}
}
self.mark();
}
+ /// 過去的對話 number `i` becomes the open one (the open one goes to the top of the list); not
+ /// while the bot works (it says so).
+ fn open_thread(&mut self, id: u64, i: usize) {
+ // Not while something is still to land in the open conversation (the same everywhere a
+ // conversation is opened): it would land in this one.
+ if let Some(why) = self.chat_pending(id, true) {
+ self.notice = Some(why);
+ return;
+ }
+ if !self.mir.on && self.state.bot(id).is_some_and(|b| i < b.threads.len()) {
+ self.leave_conversation(id);
+ }
+ if self.mir.on {
+ // (With its last message's time and its name: the brain's list may have moved since.)
+ let t = self.state.bot(id).and_then(|b| b.threads.get(i));
+ let (at, was) = (t.and_then(|t| t.1.last()).map(|m| m.at).unwrap_or(0), t.map(|t| t.0.clone()).unwrap_or_default());
+ self.mirror_act(serde_json::json!({"bot": id, "action": "restore", "index": i, "at": at, "was": was}));
+ } else if let Some(b) = self.state.bot_mut(id) {
+ b.open_thread(i);
+ }
+ self.mark();
+ }
+
+ /// 重新命名 a conversation: the open one (`None`) or 過去的對話 number `i` (on a screen of a
+ /// brain, the brain does it: the chats live there).
+ pub(super) fn rename_chat(&mut self, id: u64, which: Option, name: &str) {
+ if self.mir.on {
+ let Some(b) = self.state.bot(id) else { return };
+ let (at, was) = match which.and_then(|i| b.threads.get(i)) {
+ Some(t) => (t.1.last().map(|m| m.at).unwrap_or(0), t.0.clone()),
+ None => (0, b.chat_name()),
+ };
+ let sent = self.mirror_can_send();
+ self.mirror_act(serde_json::json!({"bot": id, "action": "rename", "index": which, "at": at, "was": was, "title": name}));
+ if !sent {
+ return;
+ }
+ }
+ // (Here too on a screen, so the name shows now; the brain's comes back the same.)
+ if let Some(b) = self.state.bot_mut(id) {
+ b.rename_chat(which, name);
+ }
+ self.mark();
+ }
+
/// 問題卡, the last thing in the chat (it used to be docked above the input, where a card
/// with several choices covered most of what the bot had just said): it scrolls with the
/// messages, as tall as its content, and the chat comes to it when it appears or moves to
@@ -8423,15 +8506,7 @@ fn tidy_dots(s: &str) -> String {
/// The avatar's picture on a notification (pixels; the system scales it down).
const NOTICE_PX: u32 = 128;
-fn first_line(s: &str, max: usize) -> String {
- let line = s.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("");
- let line = line.trim_start_matches(['#', '-', '*', ' ']);
- let mut out: String = line.chars().take(max).collect();
- if line.chars().count() > max {
- out.push('…');
- }
- out
-}
+use crate::model::first_line;
fn icon_button(ui: &mut egui::Ui, icon: &str, tip: &str, p: Palette) -> egui::Response {
if let Some(ic) = crate::icons::Icon::from_name(icon) {
diff --git a/src/app/commands.rs b/src/app/commands.rs
index 79efb9b..bef682f 100644
--- a/src/app/commands.rs
+++ b/src/app/commands.rs
@@ -227,7 +227,9 @@ impl App {
self.goal_note(bot_id, "對話還是空的,沒有東西可以分岔。");
return;
}
- let what = if name.is_empty() { words.iter().find(|m| m.role == Role::User).map(|m| first_line(&m.text, 24)).unwrap_or_else(|| "對話".into()) } else { name.to_string() };
+ // (Named after the conversation: its name, when it has one.)
+ // (A fork of a fork is 「分岔:名字」 again, not 「分岔:分岔:名字」.)
+ let what = if name.is_empty() { b.chat_name().trim_start_matches(FORK_PREFIX).to_string() } else { name.to_string() };
let title = format!("{FORK_PREFIX}{what}");
let Some(b) = self.state.bot_mut(bot_id) else { return };
let mut copy = b.messages.to_vec();
diff --git a/src/app/context_ui.rs b/src/app/context_ui.rs
index b178493..7a8fbae 100644
--- a/src/app/context_ui.rs
+++ b/src/app/context_ui.rs
@@ -55,6 +55,7 @@ impl App {
m => Some(m.to_string()),
};
self.goal_note(bot_id, "正在把較早的對話整理成摘要…");
+ self.compacting.insert(bot_id, Instant::now());
let (out, repaint) = (self.compact_out.clone(), self.repaint_fn());
std::thread::spawn(move || {
agent::set_turn_bot(bot_id);
@@ -70,6 +71,7 @@ impl App {
pub(super) fn compact_tick(&mut self) {
let done = std::mem::take(&mut *self.compact_out.lock().unwrap());
for (bot_id, got) in done {
+ self.compacting.remove(&bot_id);
match got {
Some((n, summary, boundary)) => {
if let Some(b) = self.state.bot_mut(bot_id) {
diff --git a/src/app/goal_ui.rs b/src/app/goal_ui.rs
index b27eddf..529394d 100644
--- a/src/app/goal_ui.rs
+++ b/src/app/goal_ui.rs
@@ -137,6 +137,106 @@ impl App {
crate::remote::notify(crate::remote::Notice::Done, &name, &body, bot_id);
}
+ /// What is still to land in this bot's open conversation (None: nothing), said for the
+ /// person: opening another one now would put it there. `turn`: its own running turn counts
+ /// (開始新對話 stops that one instead). A message too late to steer, a wake, a group's next
+ /// member, a colleague's report held for it; a 「/compact」 being written; a 支線 working;
+ /// a colleague working on what it handed over.
+ pub(super) fn chat_pending(&self, bot_id: u64, turn: bool) -> Option {
+ let name = self.state.bot(bot_id).map(|b| b.name.clone()).unwrap_or_default();
+ let queued = self.pending_turns.iter().any(|(id, _)| *id == bot_id) || self.waiting_wakes.iter().any(|(id, _)| *id == bot_id) || self.group_next.contains(&bot_id) || self.reports.iter().any(|(id, _)| *id == bot_id);
+ if (turn && self.streams.contains_key(&bot_id)) || queued {
+ return Some(t("「{name}」正在工作。等它做完(或先按停止),再換對話。").replace("{name}", &name));
+ }
+ // (One whose summary never came back — its thread gone — holds nothing after 10 minutes.)
+ if self.compacting.get(&bot_id).is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(600)) {
+ return Some(t("「{name}」正在把較早的對話整理成摘要:整理好再換對話。").replace("{name}", &name));
+ }
+ // (Running, or still to start: seeing whether it clashes, or waiting for the turn — it
+ // starts from the open conversation and reports there.)
+ if self.state.branch_bots.iter().any(|b| b.branch_of == bot_id) || self.state.bot(bot_id).is_some_and(|b| b.branches.iter().any(|r| r.state.open())) {
+ return Some(t("「{name}」還有支線在做,做完會回報到這段:等它做完(或在支線卡上停止),再換對話。").replace("{name}", &name));
+ }
+ // A colleague working now on what this bot handed it: its report comes here when its turn
+ // ends — said by name, with the way out (stopping it there reports 「沒有做完」 at once).
+ // (One still waiting behind the colleague's other work doesn't hold the conversation: it
+ // could be any time.)
+ let handed = |m: &Message| m.from_bot == bot_id && !m.asked;
+ let colleague = self.streams.keys().filter(|id| **id != bot_id).find(|id| self.state.bot(**id).and_then(|b| b.messages.iter().rev().find(|m| m.role == Role::User && !m.steer && !m.interrupted)).is_some_and(handed));
+ if let Some(c) = colleague.and_then(|c| self.state.bot(*c)) {
+ return Some(t("「{name}」交辦給「{other}」的事正在做,做完會回報到這段:等它回報(或到「{other}」按停止),再換對話。").replace("{name}", &name).replace("{other}", &c.name));
+ }
+ None
+ }
+
+ /// The open conversation is put aside (開始新對話) or another opened in its place: its
+ /// 目標 and 計畫 were about it and stop — said in it first, so going back to it shows what
+ /// was left and how to go on (they used to carry on in the other conversation, or go
+ /// without a word). A 換對話 the bot was asked for and hasn't done yet is off too.
+ pub(super) fn leave_conversation(&mut self, bot_id: u64) {
+ let Some(b) = self.state.bot(bot_id) else { return };
+ let mut what = vec![];
+ if let Some(g) = &b.goal {
+ what.push(format!("目標「{}」", crate::model::first_line(&g.condition, 40)));
+ }
+ if let Some(p) = &b.plan {
+ what.push(format!("計畫「{}」(做到 {}/{} 步)", crate::model::first_line(&p.task, 40), p.done(), p.steps.len()));
+ }
+ let unread = b.unread;
+ if !what.is_empty() && !b.messages.is_empty() {
+ self.goal_note(bot_id, &format!("換到另一段對話,這段的{}停了:它們只屬於這段對話。回到這裡要接著做,再打 /goal 或 /plan。", what.join("和")));
+ }
+ if let Some(b) = self.state.bot_mut(bot_id) {
+ // (The line is in the conversation put aside: nothing new to read in the open one.)
+ b.unread = unread;
+ b.chat_after = None;
+ }
+ self.goal_drop(bot_id);
+ }
+
+ /// 換對話 the bot was asked for in chat (switch_conversation): on a tick (tick_routines),
+ /// once its turn is over and nothing else is to follow in this conversation — a message
+ /// that came too late to steer, AnyBot's correction, a group's next member, a colleague's
+ /// report held for it — or those would run in the other one. Never from inside a turn's
+ /// end (settle): 停止 and the stall watchdog go on writing to the conversation after it.
+ /// 停止 and 清除聊天記錄 call it off (stop).
+ pub(super) fn chat_after_turn(&mut self, bot_id: u64) {
+ if self.state.bot(bot_id).is_none_or(|b| b.chat_after.is_none()) || self.chat_pending(bot_id, true).is_some() {
+ return;
+ }
+ let Some(to) = self.state.bot_mut(bot_id).and_then(|b| b.chat_after.take()) else { return };
+ // A turn that didn't end well (an error, the stall watchdog): the person stays where its
+ // trouble is, not moved away from it.
+ if self.state.bot(bot_id).and_then(|b| b.last_turn.as_ref()).is_some_and(|t| t.outcome != crate::model::TurnOutcome::Success) {
+ self.goal_note(bot_id, "沒有換對話:這一輪沒有順利做完,留在這段。要換再說一次。");
+ return;
+ }
+ let which = match &to {
+ crate::model::ChatAfter::New { .. } => Some(None),
+ crate::model::ChatAfter::Open { title, at, .. } => self.state.bot(bot_id).and_then(|b| b.find_thread(usize::MAX, *at, title)).map(Some),
+ };
+ let Some(which) = which else {
+ if let crate::model::ChatAfter::Open { title, .. } = to {
+ self.goal_note(bot_id, &format!("沒有換到「{title}」:那段已經不在過去的對話裡了(換過、改了名,或被收掉)。"));
+ }
+ return;
+ };
+ self.leave_conversation(bot_id);
+ if let Some(b) = self.state.bot_mut(bot_id) {
+ match which {
+ None => b.put_aside(),
+ Some(i) => {
+ b.open_thread(i);
+ }
+ }
+ let (crate::model::ChatAfter::New { name } | crate::model::ChatAfter::Open { name, .. }) = to;
+ if !name.is_empty() {
+ b.rename_chat(None, &name);
+ }
+ }
+ self.mark();
+ }
+
/// 清除聊天記錄 / 開始新對話: the goal goes with the chat it was set in (Claude Code's /clear
/// removes it too). Before the turn is stopped, so stopping doesn't leave a 「目標暫停」 line
/// in the new chat.
diff --git a/src/app/layout_audit.rs b/src/app/layout_audit.rs
index 95148d8..d992d1d 100644
--- a/src/app/layout_audit.rs
+++ b/src/app/layout_audit.rs
@@ -310,6 +310,20 @@ fn scenes() -> Vec<(&'static str, Open)> {
}
}),
),
+ (
+ "對話欄(長名字、改名中)",
+ Box::new(|a: &mut App| {
+ a.state.selected = 1;
+ a.panel = Some(panel_ui::PanelTab::Chats);
+ if let Some(b) = a.state.bot_mut(1) {
+ b.chat_title = "這是一個名字取得非常非常長的專案對話,看看會不會被切掉".into();
+ let long = "第二季官網改版:首頁、產品頁、價格頁和部落格全部重新設計,還有後台".to_string();
+ b.threads = vec![(long, vec![Message { at: crate::model::now_ms() - 3_600_000, ..Message::user("x") }]), ("報價單".into(), vec![Message { at: 5, ..Message::user("報價單") }])].into();
+ }
+ // (Its last message's time, as a row being renamed is known by.)
+ a.chat_rename = Some(panel_ui::ChatRename { bot: 1, which: Some((1, 5)), shown: "報價單".into(), text: "Q3 報價(改名中)".into(), focused: true });
+ }),
+ ),
(
"右側面板 › 資料庫",
Box::new(|a: &mut App| {
@@ -638,6 +652,117 @@ fn a_connector_is_renamed_when_done_and_its_field_keeps_the_keyboard() {
}
+/// 對話欄: the title's 「對話」 opens it (and it is there again after a restart); ✎ names the
+/// open conversation (Enter takes it, Esc doesn't); a click on a past one opens it, its name
+/// with it — not while the bot works (that would stop it), and a name being typed is taken when
+/// the person goes on.
+#[test]
+fn the_chats_column_names_and_switches_conversations() {
+ let ctx = egui::Context::default();
+ crate::load_fonts(&ctx);
+ let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-chats-column-test.png")));
+ app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id));
+ app.state.selected = 1;
+ app.streams.clear();
+ {
+ let b = app.state.bot_mut(1).unwrap();
+ b.messages = vec![Message { at: 300, ..Message::user("現在這段") }].into();
+ b.chat_title.clear();
+ b.threads = vec![("網站改版".into(), vec![Message { at: 200, ..Message::user("首頁") }]), ("報價單".into(), vec![Message { at: 100, ..Message::user("報價單") }])].into();
+ }
+ app.set_panel(Some(panel_ui::PanelTab::Chats));
+ assert!(app.state.chats_column, "remembered on this computer");
+ let size = vec2(1200.0, 800.0);
+ let shapes = draw(&mut app, &ctx, size);
+ let texts: Vec = words(&shapes).into_iter().map(|w| w.text).collect();
+ for want in ["現在這段", "網站改版", "報價單"] {
+ assert!(texts.iter().any(|t| t == want), "{want} in {texts:?}");
+ }
+ // Name the open one: typed, then Esc — nothing; typed, then Enter — named.
+ let type_name = |app: &mut App, words: &str, end: egui::Key| {
+ app.chat_rename = Some(panel_ui::ChatRename { bot: 1, which: None, shown: app.state.bot(1).unwrap().chat_name(), text: String::new(), focused: false });
+ step(app, &ctx, size, vec![]);
+ step(app, &ctx, size, vec![egui::Event::Text(words.into())]);
+ step(app, &ctx, size, vec![key(end)]);
+ step(app, &ctx, size, vec![]);
+ };
+ type_name(&mut app, "不要的名字", egui::Key::Escape);
+ assert_eq!(app.state.bot(1).unwrap().chat_title, "");
+ assert!(app.chat_rename.is_none(), "the field is gone after Esc");
+ type_name(&mut app, "官網專案", egui::Key::Enter);
+ assert_eq!(app.state.bot(1).unwrap().chat_title, "官網專案");
+ assert!(app.chat_rename.is_none());
+ let shapes = draw(&mut app, &ctx, size);
+ assert!(words(&shapes).iter().filter(|w| w.text == "官網專案").count() >= 2, "in the column and on the title's 對話");
+ // A past one: its ✎ (shown under the pointer) is pressed — the row isn't opened — and
+ // the name typed is taken when the person then closes the column.
+ // (A press right after another reads as a double click: each click comes after a pause
+ // longer than that — frames without a time are 1/60 s apart.)
+ let press = |app: &mut App, at: egui::Pos2| {
+ step(app, &ctx, size, vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }]);
+ step(app, &ctx, size, vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }]);
+ };
+ let click = |app: &mut App, at: egui::Pos2| {
+ for _ in 0..30 {
+ step(app, &ctx, size, vec![]);
+ }
+ step(app, &ctx, size, vec![egui::Event::PointerMoved(at)]);
+ step(app, &ctx, size, vec![egui::Event::PointerMoved(at)]);
+ step(app, &ctx, size, vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }]);
+ step(app, &ctx, size, vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }]);
+ };
+ let row = |app: &mut App, name: &str| {
+ let shapes = draw(app, &ctx, size);
+ words(&shapes).into_iter().find(|w| w.text == name).map(|w| w.rect).expect("the row")
+ };
+ // (✎ sits 20 px in from the row's right end; the row ends at the column's 16 px margin.)
+ let pen = egui::pos2(size.x - 16.0 - 20.0, row(&mut app, "報價單").center().y + 8.0);
+ click(&mut app, pen);
+ assert_eq!(app.state.bot(1).unwrap().messages[0].text, "現在這段", "✎ doesn't open the row");
+ assert!(app.chat_rename.as_ref().is_some_and(|e| e.which == Some((1, 100))), "✎ starts naming that one");
+ step(&mut app, &ctx, size, vec![]);
+ step(&mut app, &ctx, size, vec![key(egui::Key::End)]);
+ for _ in 0..3 {
+ step(&mut app, &ctx, size, vec![key(egui::Key::Backspace)]);
+ }
+ step(&mut app, &ctx, size, vec![egui::Event::Text("報價".into())]);
+ app.set_panel(None);
+ assert_eq!(app.state.bot(1).unwrap().threads[1].0, "報價");
+ assert!(!app.state.chats_column, "closing the column itself forgets it");
+ // The title's 對話 (it carries the open one's name) opens the column; the details opened
+ // over it and closed bring it back.
+ let pill = row(&mut app, "官網專案");
+ click(&mut app, pill.center());
+ assert_eq!(app.panel, Some(panel_ui::PanelTab::Chats));
+ app.set_panel(Some(panel_ui::PanelTab::Activity));
+ assert!(app.state.chats_column, "still remembered under the details");
+ app.set_panel(None);
+ assert_eq!(app.panel, Some(panel_ui::PanelTab::Chats), "back when the details close");
+ // Opening one while the bot works: refused, said why.
+ let now = Instant::now();
+ app.streams.insert(1, Live { cancel: Arc::new(AtomicBool::new(false)), started: now, last: now, produced: true, status: None, paused: false, paused_at: None, unattended: false, steer: Arc::new(Mutex::new(vec![])), direct: Arc::new(AtomicBool::new(false)), turn_id: "t".into(), turn: 1 });
+ let at = row(&mut app, "網站改版").center();
+ click(&mut app, at);
+ assert_eq!(app.state.bot(1).unwrap().messages[0].text, "現在這段", "not while it works");
+ assert!(app.notice.as_deref().is_some_and(|n| n.contains("正在工作")), "{:?}", app.notice);
+ // Done working: the click opens it; the open one goes to the top of the list with its name.
+ app.streams.clear();
+ app.notice = None;
+ let at = row(&mut app, "網站改版").center();
+ click(&mut app, at);
+ let b = app.state.bot(1).unwrap();
+ assert_eq!((b.messages[0].text.as_str(), b.chat_title.as_str()), ("首頁", "網站改版"));
+ assert_eq!(b.threads.iter().map(|t| t.0.as_str()).collect::>(), ["官網專案", "報價"]);
+ // A double click on a past one opens it once: the second press lands on the row the list
+ // moved under it (the one just put aside), and isn't taken as opening that one again.
+ let at = row(&mut app, "報價").center();
+ click(&mut app, at);
+ press(&mut app, at);
+ let b = app.state.bot(1).unwrap();
+ assert_eq!((b.messages[0].text.as_str(), b.chat_title.as_str()), ("報價單", "報價"), "opened once");
+ assert_eq!(b.threads.iter().map(|t| t.0.as_str()).collect::>(), ["網站改版", "官網專案"]);
+}
+
/// Esc while typing a connector's new name puts the old one back.
#[test]
fn esc_puts_a_connectors_name_back() {
diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs
index b340a62..ac304f3 100644
--- a/src/app/mirror_ui.rs
+++ b/src/app/mirror_ui.rs
@@ -17,7 +17,7 @@ use std::hash::{Hash, Hasher};
use std::sync::atomic::AtomicU64;
/// Settings that belong to each computer, never to the brain.
-const LOCAL_KEYS: &[&str] = &["remote", "theme", "accent", "sidebar_collapsed", "sidebar_width", "selected", "machine_label", "local_execution", "local_never", "messages_send", "messages_no_ask"];
+const LOCAL_KEYS: &[&str] = &["remote", "theme", "accent", "sidebar_collapsed", "sidebar_width", "chats_column", "selected", "machine_label", "local_execution", "local_never", "messages_send", "messages_no_ask"];
/// 外觀 (底色、強調色、對比、密度、慶祝動畫): kept in this computer's own file and put back over the
/// brain's whenever the brain's settings come — an update restarted the screen on its copy of the
/// brain's, and a brain that doesn't know these (an older one) answered with 紙 and its clay every
@@ -34,6 +34,7 @@ fn copy_own(to: &mut State, from: &State) {
to.accent = from.accent;
to.sidebar_collapsed = from.sidebar_collapsed;
to.sidebar_width = from.sidebar_width;
+ to.chats_column = from.chats_column;
to.machine_label = from.machine_label.clone();
to.local_execution = from.local_execution;
to.local_never = from.local_never;
@@ -47,7 +48,7 @@ fn copy_own(to: &mut State, from: &State) {
to.motion = from.motion.clone();
}
/// Bot fields the brain alone changes (its chat, and what a turn leaves behind).
-const BOT_RUNTIME: &[&str] = &["id", "messages", "threads", "unread", "last_turn", "tasks", "context_tokens", "goal", "plan", "regen_undo", "branches", "branch_of"];
+const BOT_RUNTIME: &[&str] = &["id", "messages", "threads", "chat_title", "unread", "last_turn", "tasks", "context_tokens", "goal", "plan", "regen_undo", "branches", "branch_of"];
/// Stands in for a key or token the brain doesn't hand out.
pub const REDACTED: &str = "••••(已設定,在大腦上)";
@@ -1464,6 +1465,8 @@ impl App {
let b = &mut self.state.bots[i];
let msgs = std::mem::take(&mut b.messages);
let threads = std::mem::take(&mut b.threads);
+ // (Not saved, so not in the JSON: a 換對話 the bot promised isn't lost to a setting.)
+ let chat_after = b.chat_after.take();
let mut v = serde_json::to_value(&*b).unwrap_or(Value::Null);
let mut value = value;
unredact(&mut value, &v[key]);
@@ -1486,6 +1489,7 @@ impl App {
let b = &mut self.state.bots[i];
b.messages = msgs;
b.threads = threads;
+ b.chat_after = chat_after;
ok
}
@@ -3228,6 +3232,7 @@ mod tests {
from.accent = crate::model::Accent::BotColor;
from.sidebar_collapsed = !from.sidebar_collapsed;
from.sidebar_width += 40.0;
+ from.chats_column = !from.chats_column;
from.machine_label = "工作機".into();
from.local_execution = !from.local_execution;
from.local_never = !from.local_never;
diff --git a/src/app/panel_ui.rs b/src/app/panel_ui.rs
index 7d019a1..93195e2 100644
--- a/src/app/panel_ui.rs
+++ b/src/app/panel_ui.rs
@@ -13,6 +13,20 @@ pub enum PanelTab {
Activity,
/// 資料庫
Library,
+ /// 對話欄: this bot's conversations, the open one and 過去的對話 (the chat's top 「對話」).
+ Chats,
+}
+
+/// 重新命名 in the 對話欄: which conversation (None: the open one; Some: 過去的對話 number i,
+/// with its last message's time, to find it if the list moved meanwhile) and the words so far.
+pub struct ChatRename {
+ pub bot: u64,
+ pub which: Option<(usize, i64)>,
+ /// Its name when the person started (another device may open or rename another meanwhile:
+ /// then this one isn't renamed).
+ pub shown: String,
+ pub text: String,
+ pub focused: bool,
}
pub const PANEL_WIDTH: f32 = 280.0;
@@ -30,7 +44,18 @@ impl App {
// Next to the chat when the chat keeps its minimum width; otherwise it floats over the
// chat, so a narrow window never squeezes the chat.
let avail = root.available_width();
+ // The 對話欄 remembered from last time, in a window too narrow to set it beside the
+ // chat: not floated over the chat at start (it covered the title's buttons and 送出);
+ // the title's 對話 opens it.
+ // (Still remembered for a wider window next time.)
+ if tab == PanelTab::Chats && self.chats_remembered && avail - PANEL_MIN_WIDTH < CHAT_MIN_WIDTH {
+ self.panel = None;
+ self.chats_remembered = false;
+ return;
+ }
if avail - PANEL_MIN_WIDTH >= CHAT_MIN_WIDTH {
+ // (Shown beside the chat once: from here on it is simply open.)
+ self.chats_remembered = false;
let w = (avail - CHAT_MIN_WIDTH).min(PANEL_WIDTH);
egui::Panel::right("bot-panel").exact_size(w).resizable(false).frame(Frame::new().fill(p.pane).inner_margin(Margin { left: 16, right: 16, top: 10, bottom: 12 })).show(root, |ui| keep_width(ui, |ui| self.panel_contents(ui, &ctx, bot, tab)));
} else {
@@ -47,12 +72,15 @@ impl App {
}
fn panel_contents(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot, tab: PanelTab) {
+ if tab == PanelTab::Chats {
+ return self.chats_column(ui, bot);
+ }
let p = self.pal;
// ✕ at the top right (36 px round, like the original).
ui.horizontal(|ui| {
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if round_button(ui, p, 36.0).on_hover_text(t("關閉")).clicked() {
- self.panel = None;
+ self.set_panel(None);
}
});
});
@@ -91,11 +119,186 @@ impl App {
match tab {
PanelTab::Activity => self.panel_activity(ui, ctx, bot),
PanelTab::Library => self.panel_library(ui, bot),
+ PanelTab::Chats => {}
}
ui.add_space(16.0);
});
}
+ /// The right panel open on `tab` (None: closed). The 對話欄 is remembered on this computer:
+ /// it is there again after a restart, for someone who moves between projects all day.
+ /// The details (動態、資料庫) open over a remembered 對話欄 for a while: closed, the column
+ /// is back; only closing the column itself forgets it.
+ pub(super) fn set_panel(&mut self, tab: Option) {
+ if tab != Some(PanelTab::Chats) {
+ self.finish_chat_rename(true);
+ }
+ let back = tab.is_none() && self.panel.is_some_and(|t| t != PanelTab::Chats) && self.state.chats_column;
+ let tab = if back { Some(PanelTab::Chats) } else { tab };
+ // (Back by itself, not pressed: in a window too narrow it doesn't float over the chat.)
+ self.chats_remembered = back;
+ self.panel = tab;
+ let keep = match tab {
+ Some(PanelTab::Chats) => true,
+ None => false,
+ Some(_) => self.state.chats_column,
+ };
+ if self.state.chats_column != keep {
+ self.state.chats_column = keep;
+ self.mark();
+ }
+ }
+
+ /// The name typed in the 對話欄 is done: taken (`keep`; Enter, a click elsewhere, leaving)
+ /// or not (Esc). It goes to the conversation it was typed for, found again by its time if
+ /// the list moved meanwhile (gone: nothing); the same name as before changes nothing.
+ pub(super) fn finish_chat_rename(&mut self, keep: bool) {
+ let Some(e) = self.chat_rename.take() else { return };
+ let Some(bot) = self.state.bot(e.bot).filter(|_| keep) else { return };
+ let which = match e.which {
+ None => (bot.chat_name() == e.shown).then_some(None),
+ Some((i, at)) => bot.find_thread(i, at, &e.shown).map(Some),
+ };
+ let was = match which {
+ Some(None) => Some(bot.chat_title.clone()),
+ Some(Some(i)) => bot.threads.get(i).map(|t| t.0.clone()),
+ None => None,
+ };
+ if let (Some(which), Some(was)) = (which, was) {
+ if crate::model::clean_title(&e.text) != was {
+ self.rename_chat(e.bot, which, &e.text);
+ }
+ }
+ }
+
+ /// 對話欄: this bot's conversations, the open one on top (its name, or its first line), then
+ /// 過去的對話, newest first. A click opens one; + starts a new one; ✎, a double click on the
+ /// open one or the right-click menu names one. Not while the bot works: changing the
+ /// conversation would stop it (the same as 搜尋's hits in past conversations).
+ fn chats_column(&mut self, ui: &mut egui::Ui, bot: &Bot) {
+ let p = self.pal;
+ let mut new_chat = false;
+ ui.horizontal(|ui| {
+ ui.add_space(6.0);
+ ui.label(RichText::new(t("對話")).size(FONT_H3).strong().family(crate::bold()).color(p.text));
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
+ if round_button(ui, p, 36.0).on_hover_text(t("關閉")).clicked() {
+ self.set_panel(None);
+ }
+ ui.add_space(4.0);
+ // (+, not the pen: ✎ on the rows names one.)
+ new_chat = crate::icons::button(ui, crate::icons::Icon::Plus, 32.0, p.text2, p.hover).on_hover_text(t("開始新對話")).clicked();
+ });
+ });
+ ui.add_space(10.0);
+ let now = crate::model::now_ms();
+ let last_at = |m: &[Message]| m.last().map(|m| m.at).unwrap_or(0);
+ // (The rows: which, name, the grey line, the time to find it by.)
+ let mut rows: Vec<(Option, String, String, i64)> = vec![(None, bot.chat_name(), if bot.messages.is_empty() { t("還沒有訊息") } else { t("目前的對話") }, 0)];
+ for (i, (title, msgs)) in bot.threads.iter().enumerate() {
+ let at = last_at(msgs);
+ rows.push((Some(i), title.clone(), if at > 0 { crate::pages::ago(at, now) } else { String::new() }, at));
+ }
+ // A name being typed for another bot's conversation (the person went to another bot
+ // with the keyboard): taken now, not left to come back when that bot is opened again.
+ if self.chat_rename.as_ref().is_some_and(|e| e.bot != bot.id) {
+ self.finish_chat_rename(true);
+ }
+ let (mut open, mut rename, mut done): (Option, Option