summaryrefslogtreecommitdiff
path: root/makima/src
diff options
context:
space:
mode:
Diffstat (limited to 'makima/src')
-rw-r--r--makima/src/db/models.rs96
-rw-r--r--makima/src/db/repository.rs144
-rw-r--r--makima/src/llm/mod.rs2
-rw-r--r--makima/src/llm/tools.rs168
-rw-r--r--makima/src/server/handlers/chat.rs246
-rw-r--r--makima/src/server/handlers/mod.rs1
-rw-r--r--makima/src/server/handlers/versions.rs207
-rw-r--r--makima/src/server/mod.rs6
8 files changed, 862 insertions, 8 deletions
diff --git a/makima/src/db/models.rs b/makima/src/db/models.rs
index 8204b86..617e590 100644
--- a/makima/src/db/models.rs
+++ b/makima/src/db/models.rs
@@ -149,3 +149,99 @@ impl From<File> for FileSummary {
}
}
}
+
+// =============================================================================
+// Version History Types
+// =============================================================================
+
+/// Source of a version change
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, sqlx::Type)]
+#[sqlx(type_name = "varchar")]
+#[serde(rename_all = "lowercase")]
+pub enum VersionSource {
+ #[sqlx(rename = "user")]
+ User,
+ #[sqlx(rename = "llm")]
+ Llm,
+ #[sqlx(rename = "system")]
+ System,
+}
+
+impl std::fmt::Display for VersionSource {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ VersionSource::User => write!(f, "user"),
+ VersionSource::Llm => write!(f, "llm"),
+ VersionSource::System => write!(f, "system"),
+ }
+ }
+}
+
+impl std::str::FromStr for VersionSource {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s.to_lowercase().as_str() {
+ "user" => Ok(VersionSource::User),
+ "llm" => Ok(VersionSource::Llm),
+ "system" => Ok(VersionSource::System),
+ _ => Err(format!("Unknown version source: {}", s)),
+ }
+ }
+}
+
+/// Full version record from the database
+#[derive(Debug, Clone, FromRow, Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct FileVersion {
+ pub id: Uuid,
+ pub file_id: Uuid,
+ pub version: i32,
+ pub name: String,
+ pub description: Option<String>,
+ pub summary: Option<String>,
+ #[sqlx(json)]
+ pub body: Vec<BodyElement>,
+ pub source: String,
+ pub change_description: Option<String>,
+ pub created_at: DateTime<Utc>,
+}
+
+/// Summary of a version for list views
+#[derive(Debug, Clone, Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct FileVersionSummary {
+ pub version: i32,
+ pub source: String,
+ pub created_at: DateTime<Utc>,
+ pub change_description: Option<String>,
+}
+
+impl From<FileVersion> for FileVersionSummary {
+ fn from(v: FileVersion) -> Self {
+ Self {
+ version: v.version,
+ source: v.source,
+ created_at: v.created_at,
+ change_description: v.change_description,
+ }
+ }
+}
+
+/// Response for version list endpoint
+#[derive(Debug, Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct FileVersionListResponse {
+ pub versions: Vec<FileVersionSummary>,
+ pub total: i64,
+}
+
+/// Request to restore a file to a previous version
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct RestoreVersionRequest {
+ /// The version to restore to
+ pub target_version: i32,
+ /// The current version (for optimistic locking)
+ pub current_version: i32,
+}
diff --git a/makima/src/db/repository.rs b/makima/src/db/repository.rs
index 5b962ee..4137ba6 100644
--- a/makima/src/db/repository.rs
+++ b/makima/src/db/repository.rs
@@ -4,7 +4,7 @@ use chrono::Utc;
use sqlx::PgPool;
use uuid::Uuid;
-use super::models::{CreateFileRequest, File, UpdateFileRequest};
+use super::models::{CreateFileRequest, File, FileVersion, UpdateFileRequest};
/// Default owner ID for anonymous users.
pub const ANONYMOUS_OWNER_ID: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000002);
@@ -221,3 +221,145 @@ pub async fn count_files(pool: &PgPool) -> Result<i64, sqlx::Error> {
Ok(result.0)
}
+
+// =============================================================================
+// Version History Functions
+// =============================================================================
+
+/// Set the version source for the current transaction.
+/// This is used by the trigger to record who made the change.
+pub async fn set_version_source(pool: &PgPool, source: &str) -> Result<(), sqlx::Error> {
+ sqlx::query(&format!("SET LOCAL app.version_source = '{}'", source))
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// Set the change description for the current transaction.
+pub async fn set_change_description(pool: &PgPool, description: &str) -> Result<(), sqlx::Error> {
+ // Escape single quotes for SQL
+ let escaped = description.replace('\'', "''");
+ sqlx::query(&format!("SET LOCAL app.change_description = '{}'", escaped))
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// List all versions of a file, ordered by version DESC.
+pub async fn list_file_versions(pool: &PgPool, file_id: Uuid) -> Result<Vec<FileVersion>, sqlx::Error> {
+ // First get the current version from the files table
+ let current = get_file(pool, file_id).await?;
+
+ let mut versions = sqlx::query_as::<_, FileVersion>(
+ r#"
+ SELECT id, file_id, version, name, description, summary, body, source, change_description, created_at
+ FROM file_versions
+ WHERE file_id = $1
+ ORDER BY version DESC
+ "#,
+ )
+ .bind(file_id)
+ .fetch_all(pool)
+ .await?;
+
+ // Add the current version as the first entry if it exists
+ if let Some(file) = current {
+ let current_version = FileVersion {
+ id: file.id,
+ file_id: file.id,
+ version: file.version,
+ name: file.name,
+ description: file.description,
+ summary: file.summary,
+ body: file.body,
+ source: "user".to_string(), // Current version source
+ change_description: None,
+ created_at: file.updated_at,
+ };
+ versions.insert(0, current_version);
+ }
+
+ Ok(versions)
+}
+
+/// Get a specific version of a file.
+pub async fn get_file_version(
+ pool: &PgPool,
+ file_id: Uuid,
+ version: i32,
+) -> Result<Option<FileVersion>, sqlx::Error> {
+ // First check if this is the current version
+ if let Some(file) = get_file(pool, file_id).await? {
+ if file.version == version {
+ return Ok(Some(FileVersion {
+ id: file.id,
+ file_id: file.id,
+ version: file.version,
+ name: file.name,
+ description: file.description,
+ summary: file.summary,
+ body: file.body,
+ source: "user".to_string(),
+ change_description: None,
+ created_at: file.updated_at,
+ }));
+ }
+ }
+
+ // Otherwise, look in the versions table
+ sqlx::query_as::<_, FileVersion>(
+ r#"
+ SELECT id, file_id, version, name, description, summary, body, source, change_description, created_at
+ FROM file_versions
+ WHERE file_id = $1 AND version = $2
+ "#,
+ )
+ .bind(file_id)
+ .bind(version)
+ .fetch_optional(pool)
+ .await
+}
+
+/// Restore a file to a previous version.
+/// This creates a new version with the content from the target version.
+pub async fn restore_file_version(
+ pool: &PgPool,
+ file_id: Uuid,
+ target_version: i32,
+ current_version: i32,
+) -> Result<Option<File>, RepositoryError> {
+ // Get the target version content
+ let target = get_file_version(pool, file_id, target_version).await?;
+ let Some(target) = target else {
+ return Ok(None);
+ };
+
+ // Set version source and description for the trigger
+ set_version_source(pool, "system").await?;
+ set_change_description(pool, &format!("Restored from version {}", target_version)).await?;
+
+ // Update the file with the target version's content
+ // This will trigger the save_file_version trigger to save the current state first
+ let update_req = UpdateFileRequest {
+ name: Some(target.name),
+ description: target.description,
+ transcript: None,
+ summary: target.summary,
+ body: Some(target.body),
+ version: Some(current_version),
+ };
+
+ update_file(pool, file_id, update_req).await
+}
+
+/// Count versions for a file.
+pub async fn count_file_versions(pool: &PgPool, file_id: Uuid) -> Result<i64, sqlx::Error> {
+ let result: (i64,) = sqlx::query_as(
+ "SELECT COUNT(*) + 1 FROM file_versions WHERE file_id = $1", // +1 for current version
+ )
+ .bind(file_id)
+ .fetch_one(pool)
+ .await?;
+
+ Ok(result.0)
+}
diff --git a/makima/src/llm/mod.rs b/makima/src/llm/mod.rs
index 7de8afe..0df492d 100644
--- a/makima/src/llm/mod.rs
+++ b/makima/src/llm/mod.rs
@@ -6,7 +6,7 @@ pub mod tools;
pub use claude::{ClaudeClient, ClaudeModel};
pub use groq::GroqClient;
-pub use tools::{execute_tool_call, Tool, ToolCall, ToolResult, AVAILABLE_TOOLS};
+pub use tools::{execute_tool_call, Tool, ToolCall, ToolResult, VersionToolRequest, AVAILABLE_TOOLS};
/// Available LLM providers and models
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
diff --git a/makima/src/llm/tools.rs b/makima/src/llm/tools.rs
index e6b2954..35f321f 100644
--- a/makima/src/llm/tools.rs
+++ b/makima/src/llm/tools.rs
@@ -232,9 +232,62 @@ pub static AVAILABLE_TOOLS: once_cell::sync::Lazy<Vec<Tool>> =
"required": ["input", "filter"]
}),
},
+ // Version history tools
+ Tool {
+ name: "list_versions".to_string(),
+ description: "List all available versions of the current document. Returns version numbers, sources (user/llm/system), timestamps, and change descriptions.".to_string(),
+ parameters: json!({
+ "type": "object",
+ "properties": {},
+ "required": []
+ }),
+ },
+ Tool {
+ name: "read_version".to_string(),
+ description: "Read the content of a specific historical version of the document. This is read-only and does not modify the current document.".to_string(),
+ parameters: json!({
+ "type": "object",
+ "properties": {
+ "version": {
+ "type": "integer",
+ "description": "The version number to read"
+ }
+ },
+ "required": ["version"]
+ }),
+ },
+ Tool {
+ name: "restore_version".to_string(),
+ description: "Restore the document to a previous version. This creates a new version with the content from the target version. The current content will be preserved as a historical version.".to_string(),
+ parameters: json!({
+ "type": "object",
+ "properties": {
+ "target_version": {
+ "type": "integer",
+ "description": "The version number to restore to"
+ },
+ "reason": {
+ "type": "string",
+ "description": "Optional reason for the restore (will be recorded in change description)"
+ }
+ },
+ "required": ["target_version"]
+ }),
+ },
]
});
+/// Request for version-related operations that require async database access
+#[derive(Debug, Clone)]
+pub enum VersionToolRequest {
+ /// List all versions of the current file
+ ListVersions,
+ /// Read a specific version
+ ReadVersion { version: i32 },
+ /// Restore to a specific version
+ RestoreVersion { target_version: i32, reason: Option<String> },
+}
+
/// Result of executing a tool call with modified file state
#[derive(Debug)]
pub struct ToolExecutionResult {
@@ -242,6 +295,8 @@ pub struct ToolExecutionResult {
pub new_body: Option<Vec<BodyElement>>,
pub new_summary: Option<String>,
pub parsed_data: Option<serde_json::Value>,
+ /// Request for async version operations (handled by chat handler)
+ pub version_request: Option<VersionToolRequest>,
}
/// Execute a tool call and return the result along with any state changes
@@ -261,6 +316,10 @@ pub fn execute_tool_call(
"parse_csv" => execute_parse_csv(call),
"clear_body" => execute_clear_body(),
"jq" => execute_jq(call),
+ // Version history tools - return request for async handling
+ "list_versions" => execute_list_versions(),
+ "read_version" => execute_read_version(call),
+ "restore_version" => execute_restore_version(call),
_ => ToolExecutionResult {
result: ToolResult {
success: false,
@@ -269,6 +328,7 @@ pub fn execute_tool_call(
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
},
}
}
@@ -305,6 +365,7 @@ fn execute_add_heading(call: &ToolCall, current_body: &[BodyElement]) -> ToolExe
new_body: Some(new_body),
new_summary: None,
parsed_data: None,
+ version_request: None,
}
}
@@ -345,6 +406,7 @@ fn execute_add_paragraph(call: &ToolCall, current_body: &[BodyElement]) -> ToolE
new_body: Some(new_body),
new_summary: None,
parsed_data: None,
+ version_request: None,
}
}
@@ -410,6 +472,7 @@ fn execute_add_chart(call: &ToolCall, current_body: &[BodyElement]) -> ToolExecu
new_body: Some(new_body),
new_summary: None,
parsed_data: None,
+ version_request: None,
}
}
@@ -425,6 +488,7 @@ fn execute_remove_element(call: &ToolCall, current_body: &[BodyElement]) -> Tool
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
};
};
@@ -438,6 +502,7 @@ fn execute_remove_element(call: &ToolCall, current_body: &[BodyElement]) -> Tool
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
};
}
@@ -452,6 +517,7 @@ fn execute_remove_element(call: &ToolCall, current_body: &[BodyElement]) -> Tool
new_body: Some(new_body),
new_summary: None,
parsed_data: None,
+ version_request: None,
}
}
@@ -468,6 +534,7 @@ fn execute_update_element(call: &ToolCall, current_body: &[BodyElement]) -> Tool
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
};
};
@@ -480,6 +547,7 @@ fn execute_update_element(call: &ToolCall, current_body: &[BodyElement]) -> Tool
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
};
};
@@ -493,6 +561,7 @@ fn execute_update_element(call: &ToolCall, current_body: &[BodyElement]) -> Tool
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
};
}
@@ -530,6 +599,7 @@ fn execute_update_element(call: &ToolCall, current_body: &[BodyElement]) -> Tool
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
};
}
};
@@ -545,6 +615,7 @@ fn execute_update_element(call: &ToolCall, current_body: &[BodyElement]) -> Tool
new_body: Some(new_body),
new_summary: None,
parsed_data: None,
+ version_request: None,
}
}
@@ -561,6 +632,7 @@ fn execute_reorder_elements(call: &ToolCall, current_body: &[BodyElement]) -> To
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
};
};
@@ -579,6 +651,7 @@ fn execute_reorder_elements(call: &ToolCall, current_body: &[BodyElement]) -> To
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
};
}
@@ -594,6 +667,7 @@ fn execute_reorder_elements(call: &ToolCall, current_body: &[BodyElement]) -> To
new_body: Some(new_body),
new_summary: None,
parsed_data: None,
+ version_request: None,
}
}
@@ -613,6 +687,7 @@ fn execute_set_summary(call: &ToolCall, _current_summary: Option<&str>) -> ToolE
new_body: None,
new_summary: Some(summary),
parsed_data: None,
+ version_request: None,
}
}
@@ -633,6 +708,7 @@ fn execute_parse_csv(call: &ToolCall) -> ToolExecutionResult {
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
};
}
@@ -668,6 +744,7 @@ fn execute_parse_csv(call: &ToolCall) -> ToolExecutionResult {
new_body: None,
new_summary: None,
parsed_data: Some(json!(data)),
+ version_request: None,
}
}
@@ -680,6 +757,7 @@ fn execute_clear_body() -> ToolExecutionResult {
new_body: Some(vec![]),
new_summary: None,
parsed_data: None,
+ version_request: None,
}
}
@@ -695,6 +773,7 @@ fn execute_jq(call: &ToolCall) -> ToolExecutionResult {
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
};
}
};
@@ -710,6 +789,7 @@ fn execute_jq(call: &ToolCall) -> ToolExecutionResult {
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
};
}
};
@@ -729,6 +809,7 @@ fn execute_jq(call: &ToolCall) -> ToolExecutionResult {
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
};
}
@@ -741,6 +822,7 @@ fn execute_jq(call: &ToolCall) -> ToolExecutionResult {
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
};
};
@@ -755,6 +837,7 @@ fn execute_jq(call: &ToolCall) -> ToolExecutionResult {
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
};
}
@@ -779,6 +862,7 @@ fn execute_jq(call: &ToolCall) -> ToolExecutionResult {
new_body: None,
new_summary: None,
parsed_data: None,
+ version_request: None,
};
}
}
@@ -808,6 +892,90 @@ fn execute_jq(call: &ToolCall) -> ToolExecutionResult {
new_body: None,
new_summary: None,
parsed_data: Some(output),
+ version_request: None,
+ }
+}
+
+// =============================================================================
+// Version History Tool Execution Functions
+// =============================================================================
+// These return version_request instead of performing the operation directly,
+// because they require async database access which is handled in the chat handler.
+
+fn execute_list_versions() -> ToolExecutionResult {
+ ToolExecutionResult {
+ result: ToolResult {
+ success: true,
+ message: "Listing versions...".to_string(),
+ },
+ new_body: None,
+ new_summary: None,
+ parsed_data: None,
+ version_request: Some(VersionToolRequest::ListVersions),
+ }
+}
+
+fn execute_read_version(call: &ToolCall) -> ToolExecutionResult {
+ let version = call.arguments.get("version").and_then(|v| v.as_i64());
+
+ let Some(version) = version else {
+ return ToolExecutionResult {
+ result: ToolResult {
+ success: false,
+ message: "Missing version parameter".to_string(),
+ },
+ new_body: None,
+ new_summary: None,
+ parsed_data: None,
+ version_request: None,
+ };
+ };
+
+ ToolExecutionResult {
+ result: ToolResult {
+ success: true,
+ message: format!("Reading version {}...", version),
+ },
+ new_body: None,
+ new_summary: None,
+ parsed_data: None,
+ version_request: Some(VersionToolRequest::ReadVersion { version: version as i32 }),
+ }
+}
+
+fn execute_restore_version(call: &ToolCall) -> ToolExecutionResult {
+ let target_version = call.arguments.get("target_version").and_then(|v| v.as_i64());
+ let reason = call
+ .arguments
+ .get("reason")
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string());
+
+ let Some(target_version) = target_version else {
+ return ToolExecutionResult {
+ result: ToolResult {
+ success: false,
+ message: "Missing target_version parameter".to_string(),
+ },
+ new_body: None,
+ new_summary: None,
+ parsed_data: None,
+ version_request: None,
+ };
+ };
+
+ ToolExecutionResult {
+ result: ToolResult {
+ success: true,
+ message: format!("Restoring to version {}...", target_version),
+ },
+ new_body: None,
+ new_summary: None,
+ parsed_data: None,
+ version_request: Some(VersionToolRequest::RestoreVersion {
+ target_version: target_version as i32,
+ reason,
+ }),
}
}
diff --git a/makima/src/server/handlers/chat.rs b/makima/src/server/handlers/chat.rs
index 3bdbc74..396c973 100644
--- a/makima/src/server/handlers/chat.rs
+++ b/makima/src/server/handlers/chat.rs
@@ -10,12 +10,12 @@ use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
-use crate::db::{models::BodyElement, repository};
+use crate::db::{models::BodyElement, repository::{self, RepositoryError}};
use crate::llm::{
claude::{self, ClaudeClient, ClaudeError, ClaudeModel},
execute_tool_call,
groq::{GroqClient, GroqError, Message, ToolCallResponse},
- LlmModel, ToolCall, ToolResult, AVAILABLE_TOOLS,
+ LlmModel, ToolCall, ToolResult, VersionToolRequest, AVAILABLE_TOOLS,
};
use crate::server::state::{FileUpdateNotification, SharedState};
@@ -236,6 +236,10 @@ pub async fn chat_handler(
let mut current_summary = file.summary.clone();
let mut all_tool_call_infos: Vec<ToolCallInfo> = Vec::new();
let mut final_response: Option<String> = None;
+ // Track if a version restore already happened (to avoid double-saving)
+ let mut version_restored = false;
+ // Track if there were modifications after a restore
+ let mut has_changes_after_restore = false;
// Multi-turn tool calling loop
for round in 0..MAX_TOOL_ROUNDS {
@@ -320,15 +324,49 @@ pub async fn chat_handler(
// Execute each tool call and add results to conversation
for (i, tool_call) in result.tool_calls.iter().enumerate() {
- let execution_result =
+ let mut execution_result =
execute_tool_call(tool_call, &current_body, current_summary.as_deref());
- // Apply state changes
+ // Handle version tool requests that need async database access
+ if let Some(version_request) = &execution_result.version_request {
+ let version_result = handle_version_request(
+ pool,
+ id,
+ version_request,
+ &current_body,
+ current_summary.as_deref(),
+ file.version,
+ )
+ .await;
+
+ // Update execution result with actual version operation result
+ execution_result.result = version_result.result;
+ execution_result.parsed_data = version_result.data;
+
+ // Apply state changes from restore operation
+ if let Some(new_body) = version_result.new_body {
+ current_body = new_body;
+ // Mark that a restore happened - file was already saved
+ version_restored = true;
+ }
+ if let Some(new_summary) = version_result.new_summary {
+ current_summary = Some(new_summary);
+ }
+ }
+
+ // Apply state changes from regular tools
if let Some(new_body) = execution_result.new_body {
current_body = new_body;
+ // If this is a regular tool (not a version operation), track it
+ if execution_result.version_request.is_none() && version_restored {
+ has_changes_after_restore = true;
+ }
}
if let Some(new_summary) = execution_result.new_summary {
current_summary = Some(new_summary);
+ if execution_result.version_request.is_none() && version_restored {
+ has_changes_after_restore = true;
+ }
}
// Build tool result message content
@@ -378,7 +416,9 @@ pub async fn chat_handler(
}
// Save changes to database if any tools were executed
- if !all_tool_call_infos.is_empty() {
+ // Skip if a version restore already happened (file was already saved during restore)
+ // UNLESS there were additional modifications after the restore
+ if !all_tool_call_infos.is_empty() && (!version_restored || has_changes_after_restore) {
let update_req = crate::db::models::UpdateFileRequest {
name: None,
description: None,
@@ -506,3 +546,199 @@ fn build_file_context(file: &crate::db::models::File) -> String {
context
}
+
+/// Result of handling a version tool request
+struct VersionRequestResult {
+ result: ToolResult,
+ data: Option<serde_json::Value>,
+ new_body: Option<Vec<BodyElement>>,
+ new_summary: Option<String>,
+}
+
+/// Handle version tool requests that require async database access
+async fn handle_version_request(
+ pool: &sqlx::PgPool,
+ file_id: Uuid,
+ request: &VersionToolRequest,
+ _current_body: &[BodyElement],
+ _current_summary: Option<&str>,
+ current_version: i32,
+) -> VersionRequestResult {
+ match request {
+ VersionToolRequest::ListVersions => {
+ match repository::list_file_versions(pool, file_id).await {
+ Ok(versions) => {
+ let version_data: Vec<serde_json::Value> = versions
+ .iter()
+ .map(|v| {
+ serde_json::json!({
+ "version": v.version,
+ "source": v.source,
+ "createdAt": v.created_at.to_rfc3339(),
+ "changeDescription": v.change_description,
+ })
+ })
+ .collect();
+
+ VersionRequestResult {
+ result: ToolResult {
+ success: true,
+ message: format!("Found {} versions. Current version is {}.", versions.len(), current_version),
+ },
+ data: Some(serde_json::json!({
+ "currentVersion": current_version,
+ "versions": version_data,
+ })),
+ new_body: None,
+ new_summary: None,
+ }
+ }
+ Err(e) => VersionRequestResult {
+ result: ToolResult {
+ success: false,
+ message: format!("Failed to list versions: {}", e),
+ },
+ data: None,
+ new_body: None,
+ new_summary: None,
+ },
+ }
+ }
+ VersionToolRequest::ReadVersion { version } => {
+ match repository::get_file_version(pool, file_id, *version).await {
+ Ok(Some(ver)) => {
+ // Convert body elements to a readable format
+ let body_preview: Vec<String> = ver
+ .body
+ .iter()
+ .enumerate()
+ .map(|(i, element)| {
+ let desc = match element {
+ BodyElement::Heading { level, text } => format!("H{}: {}", level, text),
+ BodyElement::Paragraph { text } => {
+ let preview = if text.len() > 100 {
+ format!("{}...", &text[..100])
+ } else {
+ text.clone()
+ };
+ format!("Paragraph: {}", preview)
+ }
+ BodyElement::Chart { chart_type, title, .. } => {
+ format!(
+ "Chart ({:?}){}",
+ chart_type,
+ title.as_ref().map(|t| format!(": {}", t)).unwrap_or_default()
+ )
+ }
+ BodyElement::Image { alt, .. } => {
+ format!("Image{}", alt.as_ref().map(|a| format!(": {}", a)).unwrap_or_default())
+ }
+ };
+ format!("[{}] {}", i, desc)
+ })
+ .collect();
+
+ VersionRequestResult {
+ result: ToolResult {
+ success: true,
+ message: format!(
+ "Version {} from {} (source: {}). {} body elements.",
+ ver.version,
+ ver.created_at.format("%Y-%m-%d %H:%M"),
+ ver.source,
+ ver.body.len()
+ ),
+ },
+ data: Some(serde_json::json!({
+ "version": ver.version,
+ "source": ver.source,
+ "createdAt": ver.created_at.to_rfc3339(),
+ "summary": ver.summary,
+ "bodyPreview": body_preview,
+ "changeDescription": ver.change_description,
+ })),
+ new_body: None,
+ new_summary: None,
+ }
+ }
+ Ok(None) => VersionRequestResult {
+ result: ToolResult {
+ success: false,
+ message: format!("Version {} not found", version),
+ },
+ data: None,
+ new_body: None,
+ new_summary: None,
+ },
+ Err(e) => VersionRequestResult {
+ result: ToolResult {
+ success: false,
+ message: format!("Failed to read version: {}", e),
+ },
+ data: None,
+ new_body: None,
+ new_summary: None,
+ },
+ }
+ }
+ VersionToolRequest::RestoreVersion { target_version, reason } => {
+ // Set change description if provided
+ if let Some(reason) = reason {
+ let _ = repository::set_change_description(pool, reason).await;
+ }
+
+ match repository::restore_file_version(pool, file_id, *target_version, current_version).await {
+ Ok(Some(restored_file)) => {
+ VersionRequestResult {
+ result: ToolResult {
+ success: true,
+ message: format!(
+ "Restored to version {}. New version is {}.",
+ target_version, restored_file.version
+ ),
+ },
+ data: Some(serde_json::json!({
+ "previousVersion": current_version,
+ "restoredFromVersion": target_version,
+ "newVersion": restored_file.version,
+ })),
+ new_body: Some(restored_file.body),
+ new_summary: restored_file.summary,
+ }
+ }
+ Ok(None) => VersionRequestResult {
+ result: ToolResult {
+ success: false,
+ message: format!("Version {} not found", target_version),
+ },
+ data: None,
+ new_body: None,
+ new_summary: None,
+ },
+ Err(RepositoryError::VersionConflict { expected, actual }) => {
+ VersionRequestResult {
+ result: ToolResult {
+ success: false,
+ message: format!(
+ "Version conflict: expected {}, actual {}. Document was modified.",
+ expected, actual
+ ),
+ },
+ data: None,
+ new_body: None,
+ new_summary: None,
+ }
+ }
+ Err(e) => VersionRequestResult {
+ result: ToolResult {
+ success: false,
+ message: format!("Failed to restore version: {}", e),
+ },
+ data: None,
+ new_body: None,
+ new_summary: None,
+ },
+ }
+ }
+ }
+}
diff --git a/makima/src/server/handlers/mod.rs b/makima/src/server/handlers/mod.rs
index c08f1bd..3211f94 100644
--- a/makima/src/server/handlers/mod.rs
+++ b/makima/src/server/handlers/mod.rs
@@ -4,3 +4,4 @@ pub mod chat;
pub mod file_ws;
pub mod files;
pub mod listen;
+pub mod versions;
diff --git a/makima/src/server/handlers/versions.rs b/makima/src/server/handlers/versions.rs
new file mode 100644
index 0000000..15118d6
--- /dev/null
+++ b/makima/src/server/handlers/versions.rs
@@ -0,0 +1,207 @@
+//! HTTP handlers for file version history operations.
+
+use axum::{
+ extract::{Path, State},
+ http::StatusCode,
+ response::IntoResponse,
+ Json,
+};
+use uuid::Uuid;
+
+use crate::db::models::{FileVersionListResponse, FileVersionSummary, RestoreVersionRequest};
+use crate::db::repository::{self, RepositoryError};
+use crate::server::messages::ApiError;
+use crate::server::state::{FileUpdateNotification, SharedState};
+
+/// List all versions of a file.
+#[utoipa::path(
+ get,
+ path = "/api/v1/files/{id}/versions",
+ params(
+ ("id" = Uuid, Path, description = "File ID")
+ ),
+ responses(
+ (status = 200, description = "List of file versions", body = FileVersionListResponse),
+ (status = 404, description = "File not found", body = ApiError),
+ (status = 503, description = "Database not configured", body = ApiError),
+ (status = 500, description = "Internal server error", body = ApiError),
+ ),
+ tag = "Versions"
+)]
+pub async fn list_versions(
+ State(state): State<SharedState>,
+ Path(file_id): Path<Uuid>,
+) -> impl IntoResponse {
+ let Some(ref pool) = state.db_pool else {
+ return (
+ StatusCode::SERVICE_UNAVAILABLE,
+ Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
+ )
+ .into_response();
+ };
+
+ // Check if file exists
+ match repository::get_file(pool, file_id).await {
+ Ok(None) => {
+ return (
+ StatusCode::NOT_FOUND,
+ Json(ApiError::new("NOT_FOUND", "File not found")),
+ )
+ .into_response();
+ }
+ Err(e) => {
+ tracing::error!("Failed to check file {}: {}", file_id, e);
+ return (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ApiError::new("DB_ERROR", e.to_string())),
+ )
+ .into_response();
+ }
+ Ok(Some(_)) => {}
+ }
+
+ match repository::list_file_versions(pool, file_id).await {
+ Ok(versions) => {
+ let summaries: Vec<FileVersionSummary> =
+ versions.into_iter().map(FileVersionSummary::from).collect();
+ let total = summaries.len() as i64;
+ Json(FileVersionListResponse {
+ versions: summaries,
+ total,
+ })
+ .into_response()
+ }
+ Err(e) => {
+ tracing::error!("Failed to list versions for file {}: {}", file_id, e);
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ApiError::new("DB_ERROR", e.to_string())),
+ )
+ .into_response()
+ }
+ }
+}
+
+/// Get a specific version of a file.
+#[utoipa::path(
+ get,
+ path = "/api/v1/files/{id}/versions/{version}",
+ params(
+ ("id" = Uuid, Path, description = "File ID"),
+ ("version" = i32, Path, description = "Version number")
+ ),
+ responses(
+ (status = 200, description = "Version details", body = crate::db::models::FileVersion),
+ (status = 404, description = "Version not found", body = ApiError),
+ (status = 503, description = "Database not configured", body = ApiError),
+ (status = 500, description = "Internal server error", body = ApiError),
+ ),
+ tag = "Versions"
+)]
+pub async fn get_version(
+ State(state): State<SharedState>,
+ Path((file_id, version)): Path<(Uuid, i32)>,
+) -> impl IntoResponse {
+ let Some(ref pool) = state.db_pool else {
+ return (
+ StatusCode::SERVICE_UNAVAILABLE,
+ Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
+ )
+ .into_response();
+ };
+
+ match repository::get_file_version(pool, file_id, version).await {
+ Ok(Some(version)) => Json(version).into_response(),
+ Ok(None) => (
+ StatusCode::NOT_FOUND,
+ Json(ApiError::new("NOT_FOUND", "Version not found")),
+ )
+ .into_response(),
+ Err(e) => {
+ tracing::error!("Failed to get version {} for file {}: {}", version, file_id, e);
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ApiError::new("DB_ERROR", e.to_string())),
+ )
+ .into_response()
+ }
+ }
+}
+
+/// Restore a file to a previous version.
+#[utoipa::path(
+ post,
+ path = "/api/v1/files/{id}/versions/restore",
+ params(
+ ("id" = Uuid, Path, description = "File ID")
+ ),
+ request_body = RestoreVersionRequest,
+ responses(
+ (status = 200, description = "File restored to previous version", body = crate::db::models::File),
+ (status = 404, description = "File or version not found", body = ApiError),
+ (status = 409, description = "Version conflict", body = ApiError),
+ (status = 503, description = "Database not configured", body = ApiError),
+ (status = 500, description = "Internal server error", body = ApiError),
+ ),
+ tag = "Versions"
+)]
+pub async fn restore_version(
+ State(state): State<SharedState>,
+ Path(file_id): Path<Uuid>,
+ Json(req): Json<RestoreVersionRequest>,
+) -> impl IntoResponse {
+ let Some(ref pool) = state.db_pool else {
+ return (
+ StatusCode::SERVICE_UNAVAILABLE,
+ Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
+ )
+ .into_response();
+ };
+
+ match repository::restore_file_version(pool, file_id, req.target_version, req.current_version).await {
+ Ok(Some(file)) => {
+ // Broadcast update notification
+ state.broadcast_file_update(FileUpdateNotification {
+ file_id,
+ version: file.version,
+ updated_fields: vec!["body".to_string(), "summary".to_string()],
+ updated_by: "system".to_string(),
+ });
+ Json(file).into_response()
+ }
+ Ok(None) => (
+ StatusCode::NOT_FOUND,
+ Json(ApiError::new("NOT_FOUND", "File or version not found")),
+ )
+ .into_response(),
+ Err(RepositoryError::VersionConflict { expected, actual }) => {
+ tracing::info!(
+ "Version conflict on file {} restore: expected {}, actual {}",
+ file_id,
+ expected,
+ actual
+ );
+ (
+ StatusCode::CONFLICT,
+ Json(serde_json::json!({
+ "code": "VERSION_CONFLICT",
+ "message": format!(
+ "File was modified by another user. Expected version {}, actual version {}",
+ expected, actual
+ ),
+ "expectedVersion": expected,
+ "actualVersion": actual,
+ })),
+ )
+ .into_response()
+ }
+ Err(RepositoryError::Database(e)) => {
+ tracing::error!("Failed to restore file {} to version {}: {}", file_id, req.target_version, e);
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ApiError::new("DB_ERROR", e.to_string())),
+ )
+ .into_response()
+ }
+ }
+}
diff --git a/makima/src/server/mod.rs b/makima/src/server/mod.rs
index f132cf4..ee5e9bd 100644
--- a/makima/src/server/mod.rs
+++ b/makima/src/server/mod.rs
@@ -17,7 +17,7 @@ use tower_http::trace::TraceLayer;
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;
-use crate::server::handlers::{chat, file_ws, files, listen};
+use crate::server::handlers::{chat, file_ws, files, listen, versions};
use crate::server::openapi::ApiDoc;
use crate::server::state::SharedState;
@@ -52,6 +52,10 @@ pub fn make_router(state: SharedState) -> Router {
.delete(files::delete_file),
)
.route("/files/{id}/chat", post(chat::chat_handler))
+ // Version history endpoints
+ .route("/files/{id}/versions", get(versions::list_versions))
+ .route("/files/{id}/versions/{version}", get(versions::get_version))
+ .route("/files/{id}/versions/restore", post(versions::restore_version))
.with_state(state);
let swagger = SwaggerUi::new("/swagger-ui")