summaryrefslogtreecommitdiff
path: root/makima/src/server/handlers/history.rs
blob: 46be7acb506731a0f35e4da5543c5898fb1dc7f6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
//! HTTP handlers for history and conversation APIs.

use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    response::IntoResponse,
    Json,
};
use uuid::Uuid;

use crate::{
    db::{
        models::{flexible_datetime, ConversationMessage, HistoryQueryFilters, TaskConversationResponse},
        repository,
    },
    server::{auth::Authenticated, messages::ApiError, state::SharedState},
};

/// Query parameters for task conversation
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TaskConversationParams {
    pub include_tool_calls: Option<bool>,
    pub include_tool_results: Option<bool>,
    pub limit: Option<i32>,
}

/// Query parameters for timeline
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TimelineQueryFilters {
    pub task_id: Option<Uuid>,
    pub include_subtasks: Option<bool>,
    #[serde(default, deserialize_with = "flexible_datetime::deserialize")]
    pub from: Option<chrono::DateTime<chrono::Utc>>,
    #[serde(default, deserialize_with = "flexible_datetime::deserialize")]
    pub to: Option<chrono::DateTime<chrono::Utc>>,
    pub limit: Option<i32>,
}

#[utoipa::path(
    get,
    path = "/api/v1/mesh/tasks/{id}/conversation",
    params(
        ("id" = Uuid, Path, description = "Task ID"),
        ("include_tool_calls" = Option<bool>, Query, description = "Include tool call messages"),
        ("include_tool_results" = Option<bool>, Query, description = "Include tool result messages"),
        ("limit" = Option<i32>, Query, description = "Limit messages"),
    ),
    responses(
        (status = 200, description = "Task conversation", body = TaskConversationResponse),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 403, description = "Forbidden", body = ApiError),
        (status = 404, description = "Task not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError),
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "History"
)]
pub async fn get_task_conversation(
    State(state): State<SharedState>,
    Path(task_id): Path<Uuid>,
    Query(params): Query<TaskConversationParams>,
    Authenticated(auth): Authenticated,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Get task and verify ownership
    let task = match repository::get_task_for_owner(pool, task_id, auth.owner_id).await {
        Ok(Some(t)) => t,
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Task not found")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to get task {}: {}", task_id, e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    };

    // Get conversation messages
    let messages = match repository::get_task_conversation(
        pool,
        task_id,
        params.include_tool_calls.unwrap_or(true),
        params.include_tool_results.unwrap_or(true),
        params.limit,
    )
    .await
    {
        Ok(m) => m,
        Err(e) => {
            tracing::error!("Failed to get task conversation: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response();
        }
    };

    // Calculate totals
    let total_cost: f64 = messages.iter().filter_map(|m| m.cost_usd).sum();

    Json(TaskConversationResponse {
        task_id,
        task_name: task.name,
        status: task.status,
        messages,
        total_tokens: None,
        total_cost: if total_cost > 0.0 {
            Some(total_cost)
        } else {
            None
        },
    })
    .into_response()
}

/// GET /api/v1/timeline
/// Returns unified task-history timeline for the authenticated user.
#[utoipa::path(
    get,
    path = "/api/v1/timeline",
    responses(
        (status = 200, description = "Timeline events"),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "History"
)]
pub async fn get_timeline(
    State(state): State<SharedState>,
    Query(filters): Query<TimelineQueryFilters>,
    Authenticated(auth): Authenticated,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    let history_filters = HistoryQueryFilters {
        event_types: None,
        from: filters.from,
        to: filters.to,
        limit: filters.limit,
        cursor: None,
    };

    let result = if let Some(task_id) = filters.task_id {
        repository::get_task_history(pool, task_id, auth.owner_id, &history_filters).await
    } else {
        repository::get_timeline(pool, auth.owner_id, &history_filters).await
    };

    match result {
        Ok((events, total_count)) => Json(serde_json::json!({
            "entries": events,
            "totalCount": total_count,
        }))
        .into_response(),
        Err(e) => {
            tracing::error!("Failed to get timeline: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", e.to_string())),
            )
                .into_response()
        }
    }
}