Chat tabs, chat mode, own modes, compaction notice, CLI binaries again
- Terminals and file managers as tabs of a chat; chat terminals keep running on the server (no idle timeout) and re-attach from any device - "Just chat" in New session and a built-in chat mode with a lean prompt and only web tools; custom modes with kind (coding/conversation), read-only and tool picker - Mode selector as a dropdown - The chat shows running compactions (automatic: tokens and share of the limit) and labels summaries - Docker image builds and serves the terminal client binaries again - Fix: atomic session updates; background title/usage writes no longer undo each other (auto compaction triggered one turn late) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
242b80605c
commit
c850586a81
29 files changed
+831
-187
No files matched your search
+67
-40
@@ -69,6 +69,7 @@ pub fn router(app: AppState) -> Router {
|
||||
.route("/providers/reload", post(reload_providers))
|
||||
.route("/models", get(models))
|
||||
.route("/agents", get(agents))
|
||||
.route("/agents/tools", get(agent_tools))
|
||||
.route("/agents/{name}", delete(delete_agent))
|
||||
.route("/commands", get(commands))
|
||||
.route("/sessions", get(list_sessions).post(create_session))
|
||||
@@ -325,6 +326,16 @@ async fn agents(Extension(user): Extension<User>, State(app): State<AppState>, Q
|
||||
}
|
||||
|
||||
/// Delete a user-defined agent: its config entry and/or its Markdown file.
|
||||
/// Built-in tools for the mode editor (name, read-only, first line of the description).
|
||||
async fn agent_tools(Extension(user): Extension<User>) -> ApiResult {
|
||||
require_admin(&user)?;
|
||||
let list: Vec<Value> = crate::tools::builtin_tools()
|
||||
.iter()
|
||||
.map(|t| json!({"name": t.name(), "read_only": t.read_only(), "description": t.description().split(['.', '\n']).next().unwrap_or("").trim()}))
|
||||
.collect();
|
||||
Ok(Json(json!(list)))
|
||||
}
|
||||
|
||||
async fn delete_agent(Extension(user): Extension<User>, State(app): State<AppState>, Path(name): Path<String>, Query(q): Query<CwdQuery>) -> ApiResult {
|
||||
let (root, cwd) = scope(&app, &user, q.cwd);
|
||||
let agent = prompts::agents(&app, &root, &cwd).into_iter().find(|a| a.name == name).ok_or_else(|| not_found("agent"))?;
|
||||
@@ -702,47 +713,47 @@ struct UpdateSession {
|
||||
}
|
||||
|
||||
async fn update_session(Extension(user): Extension<User>, State(app): State<AppState>, Path(id): Path<String>, Json(body): Json<UpdateSession>) -> ApiResult {
|
||||
let mut s = writable(&app, &user, &id)?;
|
||||
writable(&app, &user, &id)?;
|
||||
// Organising the list must not move the session to "today".
|
||||
let organise_only = body.title.is_none() && body.model.is_none() && body.agent.is_none() && body.clean_room.is_none() && body.permission_mode.is_none();
|
||||
if let Some(t) = body.title {
|
||||
s.title = t;
|
||||
if let Some(m) = &body.model {
|
||||
app.registry().resolve(m)?;
|
||||
}
|
||||
if let Some(m) = body.model {
|
||||
app.registry().resolve(&m)?;
|
||||
s.model = m;
|
||||
if body.permission_mode.as_deref().is_some_and(|p| !crate::permission::MODES.contains(&p)) {
|
||||
return Err(ApiError(StatusCode::BAD_REQUEST, "invalid permission mode".into()));
|
||||
}
|
||||
if let Some(a) = body.agent {
|
||||
s.agent = a;
|
||||
}
|
||||
if let Some(c) = body.clean_room {
|
||||
s.clean_room = Some(c);
|
||||
}
|
||||
if let Some(p) = body.pinned {
|
||||
s.pinned = p;
|
||||
}
|
||||
if let Some(a) = body.archived {
|
||||
s.archived = a;
|
||||
if a {
|
||||
s.pinned = false;
|
||||
// Atomic: a running turn updates the same session (usage, title, todos) meanwhile.
|
||||
let s = app.modify_session(&id, !organise_only, |s| {
|
||||
if let Some(t) = body.title {
|
||||
s.title = t;
|
||||
}
|
||||
}
|
||||
if let Some(f) = body.folder {
|
||||
let f = f.trim().chars().take(60).collect::<String>();
|
||||
s.folder = (!f.is_empty()).then_some(f);
|
||||
}
|
||||
if organise_only {
|
||||
app.store.save_session(&s)?;
|
||||
app.emit(Event::SessionUpdated { session: s.clone() });
|
||||
return Ok(Json(json!(s)));
|
||||
}
|
||||
if let Some(p) = body.permission_mode {
|
||||
if !crate::permission::MODES.contains(&p.as_str()) {
|
||||
return Err(ApiError(StatusCode::BAD_REQUEST, "invalid permission mode".into()));
|
||||
if let Some(m) = body.model {
|
||||
s.model = m;
|
||||
}
|
||||
s.permission_mode = p;
|
||||
}
|
||||
Ok(Json(json!(app.save_session(s)?)))
|
||||
if let Some(a) = body.agent {
|
||||
s.agent = a;
|
||||
}
|
||||
if let Some(c) = body.clean_room {
|
||||
s.clean_room = Some(c);
|
||||
}
|
||||
if let Some(p) = body.pinned {
|
||||
s.pinned = p;
|
||||
}
|
||||
if let Some(a) = body.archived {
|
||||
s.archived = a;
|
||||
if a {
|
||||
s.pinned = false;
|
||||
}
|
||||
}
|
||||
if let Some(f) = body.folder {
|
||||
let f = f.trim().chars().take(60).collect::<String>();
|
||||
s.folder = (!f.is_empty()).then_some(f);
|
||||
}
|
||||
if let Some(p) = body.permission_mode {
|
||||
s.permission_mode = p;
|
||||
}
|
||||
})?;
|
||||
Ok(Json(json!(s)))
|
||||
}
|
||||
|
||||
async fn delete_session(Extension(user): Extension<User>, State(app): State<AppState>, Path(id): Path<String>) -> ApiResult {
|
||||
@@ -751,6 +762,7 @@ async fn delete_session(Extension(user): Extension<User>, State(app): State<AppS
|
||||
app.emit(Event::SessionDeleted { session_id: id.clone() });
|
||||
runner::abort(&app, &id);
|
||||
crate::shells::kill_session(&app, &id);
|
||||
app.terminals.kill_session(&id);
|
||||
app.store.delete_session(&id)?;
|
||||
Ok(Json(json!({"ok": true})))
|
||||
}
|
||||
@@ -841,7 +853,7 @@ async fn do_compact(app: AppState, id: String) {
|
||||
let cancel = tokio_util::sync::CancellationToken::new();
|
||||
app.with_runtime(&id, |r| r.cancel = Some(cancel.clone()));
|
||||
app.emit(Event::SessionStatus { session_id: id.clone(), busy: true });
|
||||
if let Err(e) = runner::compact(app.clone(), &id, cancel).await {
|
||||
if let Err(e) = runner::compact(app.clone(), &id, cancel, None).await {
|
||||
app.emit(Event::Error { session_id: id.clone(), message: format!("compaction failed: {e:#}") });
|
||||
}
|
||||
app.with_runtime(&id, |r| r.cancel = None);
|
||||
@@ -1544,20 +1556,35 @@ async fn put_git_settings(Extension(user): Extension<User>, State(app): State<Ap
|
||||
|
||||
// --- web terminal ------------------------------------------------------------------
|
||||
|
||||
async fn list_terminals(Extension(user): Extension<User>, State(app): State<AppState>) -> ApiResult {
|
||||
Ok(Json(json!(app.terminals.list(&user.id))))
|
||||
#[derive(Deserialize)]
|
||||
struct TerminalQuery {
|
||||
session: Option<String>,
|
||||
}
|
||||
|
||||
/// All terminals of the user, or the tabs of one chat (?session=…).
|
||||
async fn list_terminals(Extension(user): Extension<User>, State(app): State<AppState>, Query(q): Query<TerminalQuery>) -> ApiResult {
|
||||
Ok(Json(json!(match q.session {
|
||||
Some(s) => app.terminals.for_session(&s, &user.id),
|
||||
None => app.terminals.list(&user.id),
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct OpenTerminal {
|
||||
cwd: Option<String>,
|
||||
/// Open as a tab of this chat (in its folder unless `cwd` is given).
|
||||
session_id: Option<String>,
|
||||
cols: Option<u16>,
|
||||
rows: Option<u16>,
|
||||
}
|
||||
|
||||
async fn open_terminal(Extension(user): Extension<User>, State(app): State<AppState>, headers: axum::http::HeaderMap, Json(b): Json<OpenTerminal>) -> ApiResult {
|
||||
let cwd = validate_cwd(&app, &user, b.cwd)?;
|
||||
let term = crate::terminal::spawn(&app, &user, &cwd, b.cols.unwrap_or(100), b.rows.unwrap_or(30)).map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("{e:#}")))?;
|
||||
let session = match &b.session_id {
|
||||
Some(id) => Some(writable(&app, &user, id)?),
|
||||
None => None,
|
||||
};
|
||||
let cwd = validate_cwd(&app, &user, b.cwd.or_else(|| session.as_ref().map(|s| s.cwd.clone())))?;
|
||||
let term = crate::terminal::spawn(&app, &user, &cwd, session.map(|s| s.id), b.cols.unwrap_or(100), b.rows.unwrap_or(30)).map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("{e:#}")))?;
|
||||
app.audit(Some(&user), "terminal.open", cwd.display().to_string(), &crate::auth::client_ip(&headers));
|
||||
Ok(Json(term.info()))
|
||||
}
|
||||
|
||||
+23
-3
@@ -46,6 +46,8 @@ pub struct Runtime {
|
||||
}
|
||||
|
||||
pub struct App {
|
||||
/// Serializes read-modify-write of sessions (see `update_session`).
|
||||
session_write: Mutex<()>,
|
||||
config_path: PathBuf,
|
||||
config: RwLock<Arc<Config>>,
|
||||
registry: RwLock<Arc<Registry>>,
|
||||
@@ -101,6 +103,7 @@ impl App {
|
||||
let registry = Registry::build(&cfg).await;
|
||||
let (events, _) = broadcast::channel(4096);
|
||||
let app = Arc::new(Self {
|
||||
session_write: Mutex::new(()),
|
||||
config_path,
|
||||
config: RwLock::new(Arc::new(cfg)),
|
||||
registry: RwLock::new(Arc::new(registry)),
|
||||
@@ -326,10 +329,27 @@ impl App {
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// Load, change and save a session atomically: background tasks (title, usage, phase,
|
||||
/// todos) change different fields at the same time and must not undo each other.
|
||||
pub fn update_session(&self, id: &str, f: impl FnOnce(&mut Session)) -> Result<Session> {
|
||||
self.modify_session(id, true, f)
|
||||
}
|
||||
|
||||
/// Like `update_session`; `touch = false` keeps `updated_at` (organising the list).
|
||||
pub fn modify_session(&self, id: &str, touch: bool, f: impl FnOnce(&mut Session)) -> Result<Session> {
|
||||
let _guard = self.session_write.lock().unwrap();
|
||||
let mut s = self.session(id)?;
|
||||
f(&mut s);
|
||||
if touch {
|
||||
return self.save_session(s);
|
||||
}
|
||||
self.store.save_session(&s)?;
|
||||
self.emit(Event::SessionUpdated { session: s.clone() });
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
pub fn set_todos(&self, session_id: &str, todos: Value) -> Result<()> {
|
||||
let mut s = self.session(session_id)?;
|
||||
s.todos = todos;
|
||||
self.save_session(s)?;
|
||||
self.update_session(session_id, |s| s.todos = todos)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -385,6 +385,13 @@ pub struct AgentConfig {
|
||||
pub tools: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
pub prompt: Option<String>,
|
||||
/// Only read-only tools (like plan mode).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub read_only: Option<bool>,
|
||||
/// "coding" (default: project context and coding instructions) or "chat" (plain
|
||||
/// conversation with only this prompt, like the built-in chat mode).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub style: Option<String>,
|
||||
/// Max. instances of this subagent running at the same time.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub max_parallel: Option<usize>,
|
||||
|
||||
@@ -53,7 +53,7 @@ pub fn markdown(s: &Session, messages: &[Message]) -> String {
|
||||
for p in &m.parts {
|
||||
match p {
|
||||
Part::Text { text } => out.push_str(&format!("{}\n\n", text.trim())),
|
||||
Part::Summary { text } => out.push_str(&format!("<details><summary>Summary of the earlier conversation</summary>\n\n{}\n\n</details>\n\n", text.trim())),
|
||||
Part::Summary { text, .. } => out.push_str(&format!("<details><summary>Summary of the earlier conversation</summary>\n\n{}\n\n</details>\n\n", text.trim())),
|
||||
Part::Reasoning { text, .. } if !text.trim().is_empty() => {
|
||||
out.push_str(&format!("<details><summary>Thinking</summary>\n\n{}\n\n</details>\n\n", text.trim()))
|
||||
}
|
||||
|
||||
+29
-7
@@ -23,6 +23,8 @@ pub struct Agent {
|
||||
/// Allowed tools; None = all.
|
||||
pub tools: Option<Vec<String>>,
|
||||
pub read_only: bool,
|
||||
/// "coding" or "chat" (plain conversation prompt).
|
||||
pub style: String,
|
||||
pub model: Option<String>,
|
||||
/// "builtin", "config" or "file".
|
||||
pub source: String,
|
||||
@@ -41,11 +43,12 @@ pub use codecraft_core::prompts::*;
|
||||
pub fn builtin_agents(clean_room: bool) -> Vec<Agent> {
|
||||
let craft = craft_prompt(clean_room);
|
||||
vec![
|
||||
Agent { name: "build".into(), description: "Full access: implement, edit, run".into(), mode: "primary".into(), prompt: BUILD_PROMPT.into(), tools: None, read_only: false, model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "plan".into(), description: "Read-only: analyse and propose a plan".into(), mode: "primary".into(), prompt: PLAN_PROMPT.into(), tools: None, read_only: true, model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "craft".into(), description: "Study a target, build your own version, check and refine".into(), mode: "primary".into(), prompt: craft, tools: None, read_only: false, model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "general".into(), description: "General-purpose subagent for multi-step tasks".into(), mode: "subagent".into(), prompt: GENERAL_PROMPT.into(), tools: None, read_only: false, model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "explore".into(), description: "Read-only subagent for fast codebase searches".into(), mode: "subagent".into(), prompt: EXPLORE_PROMPT.into(), tools: None, read_only: true, model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "build".into(), description: "Full access: implement, edit, run".into(), mode: "primary".into(), prompt: BUILD_PROMPT.into(), tools: None, read_only: false, style: "coding".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "plan".into(), description: "Read-only: analyse and propose a plan".into(), mode: "primary".into(), prompt: PLAN_PROMPT.into(), tools: None, read_only: true, style: "coding".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "chat".into(), description: "Just talk: answers, explanations, web search – no files or shell".into(), mode: "primary".into(), prompt: CHAT_PROMPT.into(), tools: Some(vec!["web_search".into(), "web_fetch".into()]), read_only: true, style: "chat".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "craft".into(), description: "Study a target, build your own version, check and refine".into(), mode: "primary".into(), prompt: craft, tools: None, read_only: false, style: "coding".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "general".into(), description: "General-purpose subagent for multi-step tasks".into(), mode: "subagent".into(), prompt: GENERAL_PROMPT.into(), tools: None, read_only: false, style: "coding".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
Agent { name: "explore".into(), description: "Read-only subagent for fast codebase searches".into(), mode: "subagent".into(), prompt: EXPLORE_PROMPT.into(), tools: None, read_only: true, style: "coding".into(), model: None, source: "builtin".into(), max_parallel: None, refine: None, path: None },
|
||||
]
|
||||
}
|
||||
|
||||
@@ -113,7 +116,8 @@ pub fn agents(app: &App, root: &Path, cwd: &Path) -> Vec<Agent> {
|
||||
mode: meta.get("mode").cloned().unwrap_or_else(|| "subagent".into()),
|
||||
prompt: body,
|
||||
tools,
|
||||
read_only: false,
|
||||
read_only: meta.get("read_only").is_some_and(|v| v == "true"),
|
||||
style: meta.get("style").filter(|v| *v == "chat").cloned().unwrap_or_else(|| "coding".into()),
|
||||
model: meta.get("model").filter(|m| m.contains('/')).cloned(),
|
||||
source: "file".into(),
|
||||
max_parallel: meta.get("max_parallel").and_then(|v| v.parse().ok()),
|
||||
@@ -131,7 +135,8 @@ pub fn agents(app: &App, root: &Path, cwd: &Path) -> Vec<Agent> {
|
||||
mode: a.mode.clone().or(base.as_ref().map(|b| b.mode.clone())).unwrap_or_else(|| "subagent".into()),
|
||||
prompt: a.prompt.clone().or(base.as_ref().map(|b| b.prompt.clone())).unwrap_or_default(),
|
||||
tools: a.tools.clone().or(base.as_ref().and_then(|b| b.tools.clone())),
|
||||
read_only: base.as_ref().is_some_and(|b| b.read_only),
|
||||
read_only: a.read_only.unwrap_or_else(|| base.as_ref().is_some_and(|b| b.read_only)),
|
||||
style: a.style.clone().filter(|s| s == "chat" || s == "coding").or(base.as_ref().map(|b| b.style.clone())).unwrap_or_else(|| "coding".into()),
|
||||
model: a.model.clone().filter(|m| !m.is_empty()).or(base.as_ref().and_then(|b| b.model.clone())),
|
||||
source: "config".into(),
|
||||
max_parallel: a.max_parallel.or(base.as_ref().and_then(|b| b.max_parallel)),
|
||||
@@ -177,7 +182,24 @@ fn instruction_files(app: &App, root: &Path, cwd: &Path) -> Vec<(PathBuf, String
|
||||
out
|
||||
}
|
||||
|
||||
/// The plain chat mode: no coding instructions, project files or memory – only the
|
||||
/// date, the model and what the user keeps in their personal memory.
|
||||
fn chat_prompt(app: &App, agent: &Agent, model: &str, owner: Option<&crate::store::User>) -> String {
|
||||
let mut s = agent.prompt.clone();
|
||||
s.push_str(&format!("\n\n# Context\n- Date: {}\n- Model: {model}\n", chrono::Local::now().format("%A, %Y-%m-%d")));
|
||||
if let Some(u) = owner {
|
||||
let memory: String = app.store.user_setting(&u.id, "memory").unwrap_or_default();
|
||||
if !memory.trim().is_empty() {
|
||||
s.push_str(&format!("\n# About the user (personal memory)\n{}\n", memory.trim()));
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
pub fn system_prompt(app: &App, agent: &Agent, root: &Path, cwd: &Path, model: &str, permission_mode: &str, owner: Option<&crate::store::User>) -> String {
|
||||
if agent.style == "chat" {
|
||||
return chat_prompt(app, agent, model, owner);
|
||||
}
|
||||
let mut s = String::from(BASE_PROMPT);
|
||||
s.push_str("\n\n");
|
||||
s.push_str(&agent.prompt);
|
||||
|
||||
+32
-19
@@ -284,7 +284,7 @@ pub async fn run_session(app: Arc<App>, session_id: &str, cancel: CancellationTo
|
||||
if let (Some(u), Some(ctx_len)) = (&session.last_usage, model.context) {
|
||||
let threshold = app.config().server.auto_compact_threshold;
|
||||
if threshold > 0.0 && u.context_tokens() as f64 > ctx_len as f64 * threshold {
|
||||
compact(app.clone(), session_id, cancel.clone()).await?;
|
||||
compact(app.clone(), session_id, cancel.clone(), Some((u.context_tokens(), ctx_len))).await?;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -746,7 +746,7 @@ fn estimate_prompt_tokens(req: &ChatRequest) -> u64 {
|
||||
for m in &req.messages {
|
||||
for p in &m.parts {
|
||||
match p {
|
||||
Part::Text { text } | Part::Reasoning { text, .. } | Part::Summary { text } => chars += text.len(),
|
||||
Part::Text { text } | Part::Reasoning { text, .. } | Part::Summary { text, .. } => chars += text.len(),
|
||||
Part::ToolCall { input, .. } => chars += input.to_string().len(),
|
||||
Part::ToolResult { content, images: imgs, .. } => {
|
||||
chars += content.len();
|
||||
@@ -913,9 +913,7 @@ async fn stream_step(
|
||||
app.store.add_message(&session.id, &message)?;
|
||||
app.emit(Event::MessageAdded { session_id: session.id.clone(), message: message.clone() });
|
||||
}
|
||||
let mut s = app.session(&session.id)?;
|
||||
s.last_usage = Some(usage);
|
||||
app.save_session(s)?;
|
||||
app.update_session(&session.id, |s| s.last_usage = Some(usage))?;
|
||||
return Ok(Step { message, stop_reason });
|
||||
}
|
||||
}
|
||||
@@ -995,11 +993,12 @@ fn maybe_generate_title(app: Arc<App>, session_id: &str, text: &str) {
|
||||
Ok((title, usage)) => {
|
||||
record_side_usage(&app, &session, &spec, &model, &usage, "title");
|
||||
let title = title.lines().find(|l| !l.trim().is_empty()).unwrap_or("").trim().trim_matches('"').to_string();
|
||||
if let (false, Ok(mut s)) = (title.is_empty(), app.session(&session.id)) {
|
||||
if s.title.is_empty() {
|
||||
s.title = title.chars().take(80).collect();
|
||||
let _ = app.save_session(s);
|
||||
}
|
||||
if !title.is_empty() {
|
||||
let _ = app.update_session(&session.id, |s| {
|
||||
if s.title.is_empty() {
|
||||
s.title = title.chars().take(80).collect();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::debug!("title generation failed: {e:#}"),
|
||||
@@ -1096,7 +1095,7 @@ fn infer_phase(tool: &str, input: &Value, deep: bool) -> Option<&'static str> {
|
||||
/// Move the craft phase forward (never backwards); `only_from` restricts the transition.
|
||||
fn advance_phase(app: &App, session_id: &str, phase: &str, only_from: Option<&str>) {
|
||||
let root = app.root_session_id(session_id);
|
||||
let Ok(mut s) = app.session(&root) else { return };
|
||||
let Ok(s) = app.session(&root) else { return };
|
||||
let cur = s.phase.as_deref().and_then(|p| PHASES.iter().position(|x| *x == p));
|
||||
if let Some(from) = only_from {
|
||||
if s.phase.as_deref() != Some(from) {
|
||||
@@ -1113,8 +1112,7 @@ fn advance_phase(app: &App, session_id: &str, phase: &str, only_from: Option<&st
|
||||
if s.phase.as_deref() == Some(phase) {
|
||||
return;
|
||||
}
|
||||
s.phase = Some(phase.to_string());
|
||||
let _ = app.save_session(s);
|
||||
let _ = app.update_session(&root, |s| s.phase = Some(phase.to_string()));
|
||||
}
|
||||
|
||||
/// Review the last turn against the user's request. Returns feedback for the
|
||||
@@ -1217,7 +1215,7 @@ pub fn transcript_of(history: &[Message]) -> String {
|
||||
for p in &m.parts {
|
||||
match p {
|
||||
Part::Text { text } => body.push_str(&format!("{text}\n")),
|
||||
Part::Summary { text } => body.push_str(&format!("[Summary of the earlier conversation]\n{text}\n")),
|
||||
Part::Summary { text, .. } => body.push_str(&format!("[Summary of the earlier conversation]\n{text}\n")),
|
||||
Part::ToolCall { name, input, .. } => body.push_str(&format!("[tool call {name}: {}]\n", clip(&input.to_string(), 1500))),
|
||||
Part::ToolResult { name, content, is_error, .. } => {
|
||||
body.push_str(&format!("[{} of {name}]\n{}\n", if *is_error { "error" } else { "result" }, clip(content, 3000)))
|
||||
@@ -1234,7 +1232,23 @@ pub fn transcript_of(history: &[Message]) -> String {
|
||||
}
|
||||
|
||||
/// Replace the active history with a summary (the old messages stay visible in the UI).
|
||||
pub async fn compact(app: Arc<App>, session_id: &str, cancel: CancellationToken) -> Result<()> {
|
||||
/// Summarize the history. `auto` = (context tokens, context limit) when triggered by a
|
||||
/// nearly full context; the chat shows the progress and the reason.
|
||||
pub async fn compact(app: Arc<App>, session_id: &str, cancel: CancellationToken, auto: Option<(u64, u64)>) -> Result<()> {
|
||||
let event = |state: &str| Event::Compaction {
|
||||
session_id: session_id.to_string(),
|
||||
state: state.into(),
|
||||
auto: auto.is_some(),
|
||||
tokens: auto.map(|a| a.0),
|
||||
limit: auto.map(|a| a.1),
|
||||
};
|
||||
app.emit(event("started"));
|
||||
let res = compact_inner(app.clone(), session_id, cancel, auto).await;
|
||||
app.emit(event(if res.is_ok() { "done" } else { "failed" }));
|
||||
res
|
||||
}
|
||||
|
||||
async fn compact_inner(app: Arc<App>, session_id: &str, cancel: CancellationToken, auto: Option<(u64, u64)>) -> Result<()> {
|
||||
let session = app.session(session_id)?;
|
||||
let history = active_history(app.store.messages(session_id)?);
|
||||
if history.is_empty() {
|
||||
@@ -1273,12 +1287,11 @@ pub async fn compact(app: Arc<App>, session_id: &str, cancel: CancellationToken)
|
||||
if summary.trim().is_empty() {
|
||||
bail!("compaction produced an empty summary");
|
||||
}
|
||||
save_user_parts(&app, session_id, vec![Part::Summary { text: summary }])?;
|
||||
let mut s = app.session(session_id)?;
|
||||
s.last_usage = None;
|
||||
let tokens = auto.map(|a| a.0).or_else(|| session.last_usage.as_ref().map(|u| u.context_tokens()));
|
||||
save_user_parts(&app, session_id, vec![Part::Summary { text: summary, auto: auto.is_some(), tokens }])?;
|
||||
app.update_session(session_id, |s| s.last_usage = None)?;
|
||||
// Files must be re-read after compaction before editing.
|
||||
app.with_runtime(session_id, |r| r.read_files.clear());
|
||||
app.save_session(s)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -239,7 +239,7 @@ impl Store {
|
||||
if let Some(m) = mdata.and_then(|d| serde_json::from_str::<Message>(&d).ok()) {
|
||||
for p in &m.parts {
|
||||
let text = match p {
|
||||
Part::Text { text } | Part::Summary { text } | Part::Reasoning { text, .. } => text.as_str(),
|
||||
Part::Text { text } | Part::Summary { text, .. } | Part::Reasoning { text, .. } => text.as_str(),
|
||||
Part::ToolResult { content, .. } => content.as_str(),
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
+33
-4
@@ -18,13 +18,16 @@ use tokio::sync::broadcast;
|
||||
|
||||
/// Output kept for re-attaching clients.
|
||||
const SCROLLBACK: usize = 256 * 1024;
|
||||
/// Detached terminals are stopped after this time.
|
||||
/// Detached terminals outside a chat are stopped after this time; terminals that
|
||||
/// belong to a chat stay open until they are closed, exit or the chat is deleted.
|
||||
const DETACHED_TTL: Duration = Duration::from_secs(30 * 60);
|
||||
const MAX_PER_USER: usize = 8;
|
||||
const MAX_PER_USER: usize = 16;
|
||||
|
||||
pub struct Term {
|
||||
pub id: String,
|
||||
pub owner_id: String,
|
||||
/// Chat the terminal is a tab of.
|
||||
pub session_id: Option<String>,
|
||||
pub cwd: PathBuf,
|
||||
pub created_at: i64,
|
||||
writer: tokio::sync::Mutex<pty_process::OwnedWritePty>,
|
||||
@@ -57,6 +60,7 @@ impl Term {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"cwd": self.cwd,
|
||||
"session_id": self.session_id,
|
||||
"created_at": self.created_at,
|
||||
"alive": self.alive(),
|
||||
"attached": *self.attached.lock().unwrap() > 0,
|
||||
@@ -76,6 +80,30 @@ impl Terminals {
|
||||
v.into_iter().map(|(_, i)| i).collect()
|
||||
}
|
||||
|
||||
/// Terminals of one chat (oldest first).
|
||||
pub fn for_session(&self, session_id: &str, owner_id: &str) -> Vec<Value> {
|
||||
let mut v: Vec<_> = self
|
||||
.map
|
||||
.lock()
|
||||
.unwrap()
|
||||
.values()
|
||||
.filter(|t| t.owner_id == owner_id && t.session_id.as_deref() == Some(session_id))
|
||||
.map(|t| (t.created_at, t.info()))
|
||||
.collect();
|
||||
v.sort_by_key(|(c, _)| *c);
|
||||
v.into_iter().map(|(_, i)| i).collect()
|
||||
}
|
||||
|
||||
/// Close all terminals of a deleted chat.
|
||||
pub fn kill_session(&self, session_id: &str) {
|
||||
let gone: Vec<Arc<Term>> = {
|
||||
let mut map = self.map.lock().unwrap();
|
||||
let ids: Vec<String> = map.values().filter(|t| t.session_id.as_deref() == Some(session_id)).map(|t| t.id.clone()).collect();
|
||||
ids.iter().filter_map(|id| map.remove(id)).collect()
|
||||
};
|
||||
gone.iter().for_each(|t| t.kill());
|
||||
}
|
||||
|
||||
pub fn get(&self, id: &str, owner_id: &str) -> Option<Arc<Term>> {
|
||||
self.map.lock().unwrap().get(id).filter(|t| t.owner_id == owner_id).cloned()
|
||||
}
|
||||
@@ -100,7 +128,7 @@ impl Terminals {
|
||||
pub fn reap(&self) {
|
||||
let mut map = self.map.lock().unwrap();
|
||||
map.retain(|_, t| {
|
||||
let stale = t.detached_since.lock().unwrap().is_some_and(|d| d.elapsed() > DETACHED_TTL);
|
||||
let stale = t.session_id.is_none() && t.detached_since.lock().unwrap().is_some_and(|d| d.elapsed() > DETACHED_TTL);
|
||||
let gone = !t.alive() && *t.attached.lock().unwrap() == 0;
|
||||
if stale || gone {
|
||||
t.kill();
|
||||
@@ -113,7 +141,7 @@ impl Terminals {
|
||||
}
|
||||
|
||||
/// Start a shell for `user` in `cwd` (already access-checked).
|
||||
pub fn spawn(app: &Arc<App>, user: &User, cwd: &Path, cols: u16, rows: u16) -> Result<Arc<Term>> {
|
||||
pub fn spawn(app: &Arc<App>, user: &User, cwd: &Path, session_id: Option<String>, cols: u16, rows: u16) -> Result<Arc<Term>> {
|
||||
if app.terminals.list(&user.id).iter().filter(|t| t["alive"] == true).count() >= MAX_PER_USER {
|
||||
anyhow::bail!("too many open terminals (max {MAX_PER_USER}) – close one first");
|
||||
}
|
||||
@@ -142,6 +170,7 @@ pub fn spawn(app: &Arc<App>, user: &User, cwd: &Path, cols: u16, rows: u16) -> R
|
||||
let term = Arc::new(Term {
|
||||
id: crate::types::new_id(),
|
||||
owner_id: user.id.clone(),
|
||||
session_id,
|
||||
cwd: cwd.to_path_buf(),
|
||||
created_at: crate::types::now_ms(),
|
||||
writer: tokio::sync::Mutex::new(writer),
|
||||
|
||||
Reference in new issue
Block a user