Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions crates/goose/src/acp/response_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ pub(super) fn session_meta(session: &Session) -> serde_json::Map<String, serde_j
"createdAt".to_string(),
serde_json::Value::String(session.created_at.to_rfc3339()),
);
if let Some(ref last_message_at) = session.last_message_at {
meta.insert(
"lastMessageAt".to_string(),
serde_json::Value::String(last_message_at.to_rfc3339()),
);
}
if let Some(ref archived_at) = session.archived_at {
meta.insert(
"archivedAt".to_string(),
Expand Down
69 changes: 61 additions & 8 deletions crates/goose/src/session/session_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::session::session_naming::{
generate_session_name, MSG_COUNT_FOR_SESSION_NAME_GENERATION,
};
use anyhow::Result;
use chrono::{DateTime, Utc};
use chrono::{DateTime, TimeZone, Utc};
use goose_providers::conversation::token_usage::Usage;
use goose_providers::model::ModelConfig;
use rmcp::model::Role;
Expand Down Expand Up @@ -80,6 +80,8 @@ pub struct Session {
pub user_recipe_values: Option<HashMap<String, String>>,
pub conversation: Option<Conversation>,
pub message_count: usize,
#[serde(default)]
pub last_message_at: Option<DateTime<Utc>>,
pub provider_name: Option<String>,
pub model_config: Option<ModelConfig>,
#[serde(default)]
Expand Down Expand Up @@ -594,6 +596,7 @@ impl Default for Session {
user_recipe_values: None,
conversation: None,
message_count: 0,
last_message_at: None,
provider_name: None,
model_config: None,
goose_mode: GooseMode::default(),
Expand Down Expand Up @@ -641,6 +644,12 @@ impl sqlx::FromRow<'_, sqlx::sqlite::SqliteRow> for Session {
.unwrap_or_else(|_| "user".to_string());
let session_type = session_type_str.parse().unwrap_or_default();

let last_message_at = row
.try_get::<Option<i64>, _>("last_message_timestamp")
.ok()
.flatten()
.and_then(|timestamp| Utc.timestamp_opt(timestamp, 0).single());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Normalize millisecond timestamps before exposing last_message_at

last_message_at is derived by interpreting every stored created_timestamp as Unix seconds. That is wrong for sessions populated by the terminal integration: handle_term_log writes chrono::Utc::now().timestamp_millis() into Message::created (crates/goose-cli/src/commands/term.rs:237-240), and add_message persists that value, so those sessions will now expose lastMessageAt/last_message_at dates tens of thousands of years in the future when listed or fetched. Normalize existing millisecond values or fix the writer before surfacing this field.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed: millisecond-epoch timestamps are now normalized before being interpreted as seconds, both in Rust (message_timestamp_to_datetime via MILLISECOND_TIMESTAMP_THRESHOLD) and in the SQL (normalized_message_timestamp_sql), so last_message_at no longer produces year-40000 dates.


Ok(Session {
id: row.try_get("id")?,
working_dir: PathBuf::from(row.try_get::<String, _>("working_dir")?),
Expand Down Expand Up @@ -677,6 +686,7 @@ impl sqlx::FromRow<'_, sqlx::sqlite::SqliteRow> for Session {
user_recipe_values,
conversation: None,
message_count: row.try_get("message_count").unwrap_or(0) as usize,
last_message_at,
provider_name: row.try_get("provider_name").ok().flatten(),
model_config,
goose_mode: row
Expand Down Expand Up @@ -1348,14 +1358,22 @@ impl SessionStorage {
if include_messages {
let conv = self.get_conversation(&session.id).await?;
session.message_count = conv.messages().len();
session.last_message_at = conv
.messages()
.iter()
.filter_map(|message| Utc.timestamp_opt(message.created, 0).single())
.max();
session.conversation = Some(conv);
} else {
let count =
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM messages WHERE session_id = ?")
.bind(&session.id)
.fetch_one(pool)
.await? as usize;
session.message_count = count;
let (count, last_message_timestamp): (i64, Option<i64>) = sqlx::query_as(
"SELECT COUNT(*), MAX(created_timestamp) FROM messages WHERE session_id = ?",
)
.bind(&session.id)
.fetch_one(pool)
.await?;
session.message_count = count as usize;
session.last_message_at = last_message_timestamp
.and_then(|timestamp| Utc.timestamp_opt(timestamp, 0).single());
}

Ok(session)
Expand Down Expand Up @@ -1670,7 +1688,8 @@ impl SessionStorage {
s.schedule_id, s.recipe_json, s.user_recipe_values_json,
s.provider_name, s.model_config_json, s.goose_mode,
s.archived_at, s.project_id,
COUNT(m.id) as message_count
COUNT(m.id) as message_count,
MAX(m.created_timestamp) as last_message_timestamp
FROM sessions s
{}
{}
Expand Down Expand Up @@ -2224,6 +2243,40 @@ mod tests {
.unwrap();
}

#[tokio::test]
async fn test_last_message_at_is_derived_from_messages() {
let temp_dir = TempDir::new().unwrap();
let sm = SessionManager::new(temp_dir.path().to_path_buf());
let session = sm
.create_session(
PathBuf::from("/tmp/test"),
"Session recency".to_string(),
SessionType::User,
GooseMode::default(),
)
.await
.unwrap();

let empty = sm.get_session(&session.id, false).await.unwrap();
assert_eq!(empty.message_count, 0);
assert_eq!(empty.last_message_at, None);

add_message_at(&sm, &session.id, "older", "2026-01-01T00:00:00Z").await;
add_message_at(&sm, &session.id, "newer", "2026-01-02T03:04:05Z").await;

let expected = chrono::DateTime::parse_from_rfc3339("2026-01-02T03:04:05Z")
.unwrap()
.with_timezone(&Utc);

let without_messages = sm.get_session(&session.id, false).await.unwrap();
assert_eq!(without_messages.message_count, 2);
assert_eq!(without_messages.last_message_at, Some(expected));

let with_messages = sm.get_session(&session.id, true).await.unwrap();
assert_eq!(with_messages.message_count, 2);
assert_eq!(with_messages.last_message_at, Some(expected));
}

#[tokio::test]
async fn test_maybe_update_name_updates_eligible_session() {
let temp_dir = TempDir::new().unwrap();
Expand Down
56 changes: 55 additions & 1 deletion crates/goose/tests/acp_server_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@ use common_tests::{
run_shell_terminal_false, run_shell_terminal_true,
};
use goose::config::GooseMode;
use goose::conversation::message::{Message, MessageMetadata};
use goose::conversation::message::{Message, MessageContent, MessageMetadata};
use goose::custom_requests::{GetSessionInfoRequest, GetSessionInfoResponse};
use goose::recipe::{Recipe, Settings};
use goose::recipe_deeplink;
use goose::session::{SessionManager, SessionType};
use rmcp::model::Role;
use std::path::Path;

tests_config_option_set_error!(AcpServerConnection);
Expand Down Expand Up @@ -138,6 +139,14 @@ fn last_message_snippet(session: &SessionInfo) -> Option<&str> {
.and_then(serde_json::Value::as_str)
}

fn last_message_at(session: &SessionInfo) -> Option<&str> {
session
.meta
.as_ref()
.and_then(|meta| meta.get("lastMessageAt"))
.and_then(serde_json::Value::as_str)
}

#[test]
fn test_config_mcp() {
run_test(async { run_config_mcp::<AcpServerConnection>().await });
Expand Down Expand Up @@ -226,6 +235,51 @@ fn test_list_sessions_emits_computed_snippet() {
});
}

#[test]
fn test_list_sessions_emits_last_message_at() {
run_test(async {
let data_root = tempfile::tempdir().unwrap();
let cwd = Path::new("/tmp/acp-session-list-last-message-at");
let session_manager = SessionManager::new(data_root.path().to_path_buf());
let session = session_manager
.create_session(
cwd.to_path_buf(),
"Session recency".to_string(),
SessionType::Acp,
GooseMode::default(),
)
.await
.unwrap();
let expected = chrono::DateTime::parse_from_rfc3339("2026-01-02T03:04:05Z")
.unwrap()
.with_timezone(&chrono::Utc);
session_manager
.add_message(
&session.id,
&Message::new(
Role::User,
expected.timestamp(),
vec![MessageContent::text("hello")],
),
)
.await
.unwrap();

let conn = new_connection(data_root.path()).await;
let response = list_sessions_request(&conn, ListSessionsRequest::new())
.await
.unwrap();

assert_eq!(response.sessions.len(), 1);
assert_eq!(
last_message_at(&response.sessions[0])
.and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
.map(|value| value.with_timezone(&chrono::Utc)),
Some(expected)
);
});
}

#[test]
fn test_list_sessions_pagination() {
run_test(async {
Expand Down
5 changes: 5 additions & 0 deletions ui/desktop/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -7978,6 +7978,11 @@
"id": {
"type": "string"
},
"last_message_at": {
"type": "string",
"format": "date-time",
"nullable": true
},
"last_message_snippet": {
"type": "string",
"nullable": true
Expand Down
4 changes: 4 additions & 0 deletions ui/desktop/src/acp/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type { Recipe } from '../recipe';
interface GooseSessionInfoMeta {
messageCount?: number;
createdAt?: string;
lastMessageAt?: string;
archivedAt?: string;
projectId?: string;
providerId?: string;
Expand All @@ -30,6 +31,7 @@ export interface SessionListItem {
workingDir: string;
updatedAt: string;
messageCount: number;
lastMessageAt?: string;
createdAt: string;
archivedAt?: string;
projectId?: string;
Expand Down Expand Up @@ -94,6 +96,7 @@ export function sessionInfoToSession(s: SessionInfo, loadMeta: LoadSessionMeta =
working_dir: loadMeta.workingDir ?? s.cwd,
created_at: createdAt,
updated_at: updatedAt,
last_message_at: meta.lastMessageAt,
message_count: meta.messageCount ?? 0,
extension_data: {},
archived_at: meta.archivedAt,
Expand All @@ -116,6 +119,7 @@ function sessionInfoToListItem(s: SessionInfo): SessionListItem {
workingDir: s.cwd,
updatedAt: s.updatedAt ?? '',
messageCount: meta.messageCount ?? 0,
lastMessageAt: meta.lastMessageAt,
createdAt: meta.createdAt ?? s.updatedAt ?? '',
archivedAt: meta.archivedAt,
projectId: meta.projectId,
Expand Down
1 change: 1 addition & 0 deletions ui/desktop/src/api/types.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1356,6 +1356,7 @@ export type Session = {
extension_data: ExtensionData;
goose_mode?: GooseMode;
id: string;
last_message_at?: string | null;
last_message_snippet?: string | null;
message_count: number;
model_config?: ModelConfig | null;
Expand Down
Loading