How to Retrieve Chat History for a Specific Session Using session_chat_history in Coco App
The session_chat_history command retrieves historical messages for a chat session by executing an HTTP GET request to /chat/{session_id}/_history and returning the parsed message array to the React frontend for state management.
The session_chat_history function serves as the core mechanism for loading previous conversations in the Coco AI application. When users open an existing chat session, this command fetches paginated message history from the Coco server and updates the local React state with the retrieved data. According to the infinilabs/coco-app source code, the implementation spans both Rust backend handlers and TypeScript frontend hooks to provide a seamless cross-platform experience.
Architecture of session_chat_history
The session_chat_history command operates through a platform adapter pattern that abstracts the difference between web and desktop environments. This design ensures consistent API usage across all deployment targets while handling the distinct networking requirements of each platform.
Web Mode Implementation
In web deployments, the platform adapter routes the command directly to a standard HTTP client. The adapter constructs a GET request to the endpoint /chat/{sessionId}/_history on the configured Coco server, passing pagination parameters from and size as query strings.
Tauri Desktop Mode Implementation
For Tauri desktop builds, the command travels through the Rust backend layer defined in src-tauri/src/assistant/mod.rs. The Rust handler builds the identical HTTP GET request, forwards it to the server using HttpClient::get, and returns the raw JSON response body as a string to the JavaScript frontend.
Retrieving Session Data in the Rust Backend
The Rust implementation of session_chat_history in src-tauri/src/assistant/mod.rs handles the actual HTTP communication with the Coco server. This command accepts four parameters: server_id, session_id, from, and size.
// src-tauri/src/assistant/mod.rs
#[tauri::command]
pub async fn session_chat_history(
_app_handle: AppHandle,
server_id: String,
session_id: String,
from: u32,
size: u32,
) -> Result<String, HttpRequestError> {
// Build query parameters for pagination
let mut query_params = Vec::new();
query_params.push(format!("from={}", from));
query_params.push(format!("size={}", size));
// Construct the endpoint path for session history
let path = format!("/chat/{}/_history", session_id);
// Execute GET request against the selected Coco server
let response = HttpClient::get(&server_id, path.as_str(), Some(query_params)).await?;
// Return raw JSON string to the frontend
common::http::get_response_body_text(response).await
}
The function constructs the query parameters for pagination, assembles the path using the provided session_id, and returns the complete response body text without parsing, leaving JSON deserialization to the TypeScript consumer.
Managing Chat History in the Frontend
Once the Rust backend returns the raw JSON string, the frontend hooks in src/hooks/useChatPanel.ts and src/hooks/useChatActions.ts handle parsing and state management. These hooks extract the message array from response.hits.hits and perform additional logic to restore the session context.
Processing the Response in useChatPanel
The useChatPanel.ts hook demonstrates the complete retrieval flow, including assistant identification and state updates:
// src/hooks/useChatPanel.ts
const chatHistory = useCallback(
async (chat: Chat) => {
try {
// Invoke the command through the platform adapter
let response: any = await platformAdapter.commands(
"session_chat_history",
{
serverId: currentService?.id,
sessionId: chat?._id || "",
from: 0,
size: 500,
}
);
// Parse the JSON string returned from Rust/backend
response = response ? JSON.parse(response) : null;
const hits = response?.hits?.hits || [];
// Identify the assistant from the last message
const lastAssistantId = hits[hits.length - 1]?._source?.assistant_id;
const matchedAssistant = assistantList?.find(
(assistant) => assistant._id === lastAssistantId
);
if (matchedAssistant) {
setCurrentAssistant(matchedAssistant);
}
// Update the active chat with retrieved messages
const updatedChat: Chat = { ...chat, messages: hits };
setActiveChat(updatedChat);
} catch (error) {
console.error("session_chat_history:", error);
}
},
[assistantList, currentService?.id, setCurrentAssistant]
);
Platform Adapter Abstraction
The platformAdapter in src/utils/platformAdapter.ts provides the unified interface that determines whether to invoke Tauri commands or standard web requests:
// src/utils/platformAdapter.ts
import { createTauriAdapter } from "./tauriAdapter";
let platformAdapter = createTauriAdapter();
export default platformAdapter;
When running in a web environment, this adapter swaps to createWebAdapter, maintaining identical function signatures while routing requests through standard HTTP clients rather than Tauri invoke handlers.
Summary
session_chat_historyserves as the unified command for retrieving historical messages across web and desktop platforms in the Coco app.- The Rust backend in
src-tauri/src/assistant/mod.rsconstructs HTTP GET requests to/chat/{session_id}/_historywith pagination support viafromandsizeparameters. - Frontend hooks
useChatPanelanduseChatActionsparse the JSON response to extracthits.hits, identify the last assistant viaassistant_id, and update the React store. - The platform adapter pattern ensures consistent API usage whether running as a Tauri desktop application or a standard web build.
Frequently Asked Questions
What parameters does session_chat_history require?
The session_chat_history command requires four parameters: server_id (identifying the Coco server instance), session_id (the unique chat session identifier), from (pagination offset), and size (number of messages to retrieve). These parameters are passed as an object to the platform adapter and forwarded to either the Rust backend or web HTTP client.
How does the web adapter differ from the Tauri adapter?
While both adapters expose identical commands interfaces, the Tauri adapter routes calls through Tauri's invoke system to Rust functions in src-tauri/src/assistant/mod.rs, whereas the web adapter executes standard HTTP requests directly from the browser. The web implementation calls "/chat/{sessionId}/_history" via fetch or axios, while the Tauri version forwards the request through the Rust HttpClient module.
Where is the retrieved chat history stored?
After parsing the JSON response, the message array (extracted from hits.hits) is stored in the chat store managed by useChatPanel or useChatActions as the activeChat object. The messages populate the messages property of the Chat interface, and the currentAssistant state updates based on the assistant_id found in the last message's _source field.
How does the system handle pagination for large chat histories?
The from and size parameters enable standard offset-based pagination. The Rust backend in src-tauri/src/assistant/mod.rs converts these parameters into query strings appended to the GET request (?from=0&size=500). The frontend typically requests larger batches (such as 500 messages) to minimize round trips, parsing only the hits.hits array from the Elasticsearch-style response format returned by the Coco server.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →