Refactoring an AI Chat History Export Tool with Go and Terminal TUI

    This article details the refactoring of an AI conversation history export tool, shifting from a file-based offline parsing workflow to a direct API-connected interactive terminal application built with Go and a TUI framework. It covers the architecture, key implementation details such as token authentication, lazy-loading pagination, three export modes (recent, full, and manual selection), local deduplication, and standardized Markdown output, along with cross-platform build considerations. The goal is to provide a practical blueprint for developers building local-first, data-export tools for web services.

    Refactoring an AI Chat History Export Tool with Go and Terminal TUI

    1. Background: From File Parsing to Direct API Access

    Early approaches to exporting AI chat history typically relied on the platform’s official “data export” feature. The user would request an export from the web interface, download a compressed archive, extract the JSON files, and run a script to parse and convert them into Markdown. While workable, this pipeline had notable drawbacks:

    • Disconnected workflow: The export action happened on the web, while parsing happened locally, requiring manual file transfer between steps.
    • Poor timeliness: Platform exports were usually generated in full, so even a user wanting only the latest few conversations had to wait for complete packaging.
    • Inconsistent formats: The field structure of export files changed with platform versions, making parser maintenance costly.

    The core idea of this refactor was to drop the dependency on official export files and instead extract an access token from the browser’s logged-in session. The tool would then call the conversation history API directly. This consolidates data fetching, filtering, conversion, and storage into a single terminal program, reducing the pipeline length and offering finer control. After the refactor, the tool supports on-demand pagination, manual selection, local deduplication, and Markdown formatting. It can be used for long-term archiving with note-taking knowledge management tools, and also allows syncing to general cloud object storage services.

    2. Overall Architecture Design

    The refactored program uses a layered structure:

    1. ┌─────────────────────────────┐
    2. │ TUI Interaction Layer│ Keyboard interaction, list rendering, status display
    3. ├─────────────────────────────┤
    4. │ Business Logic Layer │ Pagination scheduling, selection management, deduplication
    5. ├─────────────────────────────┤
    6. │ Data Access Layer │ Token authentication, API requests, error retry
    7. ├─────────────────────────────┤
    8. │ Persistence Layer │ Markdown generation, monthly directory storage
    9. └─────────────────────────────┘
    • TUI Interaction Layer implements a full-screen interface using a mature Go terminal UI framework (e.g., Bubble Tea). All operations are keyboard-driven.
    • Business Logic Layer coordinates pagination, maintains a set of selected conversation IDs, and handles local file deduplication.
    • Data Access Layer wraps HTTP requests, uniformly handling authentication headers, timeouts, and retry logic.
    • Persistence Layer renders conversation content as well-formed Markdown and organizes files by time-based directory structure.

    This separation makes every layer independently replaceable. For instance, switching to a desktop GUI or a web interface later would only require replacing the interaction layer.

    3. Key Implementation Details

    3.1 Token Acquisition and API Authentication

    The refactored authentication flow is:

    1. The user logs into the AI conversation platform in a browser.
    2. Open developer tools (F12) and switch to the Network panel.
    3. Find the user token field in the request headers or cookies of any API request and copy its value.
    4. Configure the token locally via environment variables or a config file.

    All requests from the tool carry the authentication header:

    1. req, _ := http.NewRequest("GET", apiURL, nil)
    2. req.Header.Set("Authorization", "Bearer "+token)

    Two engineering details need attention: first, the token has an expiry time, so the program should catch authentication failure responses and prompt the user to re-obtain the token. Second, the token is sensitive information, so the config file should be added to version control ignore lists to avoid leaking.

    3.2 Smart Pagination and On-Demand Loading

    Conversation histories can reach hundreds or even thousands of items. Fetching all at once is slow and wasteful. The refactor adopts a “lazy loading” strategy: initially only the first page is loaded, and the next page is requested when the user scrolls to the bottom of the list. Pseudocode:

    1. func (m *Model) loadNextPage() {
    2. if m.loading || !m.hasMore {
    3. return
    4. }
    5. m.loading = true
    6. page := fetchConversations(m.token, m.cursor)
    7. m.items = append(m.items, page.Items...)
    8. m.cursor = page.NextCursor
    9. m.hasMore = page.NextCursor != ""
    10. m.loading = false
    11. }

    This approach gives near-instant startup and a smooth browsing experience. Request intervals should include throttling to avoid triggering server rate limits.

    3.3 Three Flexible Export Modes

    To meet different backup needs, the tool offers three export strategies:

    • Recent export: Takes the most recent N conversations in reverse chronological order, ideal for daily incremental backups.
    • Full export: Iterates through all pages until exhausted, suitable for a first complete archive.
    • Manual selection export: In the list view, the user marks desired conversations with the spacebar and confirms with Enter, ideal for preserving only high-value conversations.

    The selection state is maintained in a map keyed by conversation ID, avoiding duplicate selections. During export, only the selected IDs are fetched.

    3.4 Local Deduplication Mechanism

    Before exporting, the program scans the target directory for existing files and builds an index mapping “conversation ID → file path.” Conversations already exported are skipped, and only the incremental portion is processed. This saves API requests and avoids file overwriting conflicts. Example logic:

    1. if _, exists := exportedIndex[conv.ID]; exists {
    2. skipped++
    3. continue
    4. }

    Deduplication should be based on the unique conversation ID rather than the title, as titles may be modified by the user, while the ID is a stable unique identifier.

    3.5 Markdown Formatting and Directory Organization

    Exported files follow a consistent naming and organization scheme:

    • File names use “date + conversation title” format for easy time-based sorting and quick lookup.
    • Directories are grouped by month, e.g., conversations_export/2026-05/, preventing too many files in a single directory.
    • For content, “deep thinking” sections and regular responses are styled differently: reasoning processes can be placed in collapsible blockquotes, while formal answers retain normal body hierarchy. Code fragments retain syntax highlighting markers.

    Standardized Markdown output can be directly indexed by various note-taking tools, forming a searchable personal knowledge base. For team collaboration or disaster recovery, the export directory can be synchronized to general cloud object storage services (e.g., Baidu AI Cloud’s object storage), providing low-cost and reliable long-term archiving.

    4. Cross-Platform Build and Usage Experience

    With Go’s cross-compilation capability, a single codebase can produce executable files for multiple platforms:

    1. GOOS=windows GOARCH=amd64 go build -o exporter-windows.exe
    2. GOOS=darwin GOARCH=arm64 go build -o exporter-macos
    3. GOOS=linux GOARCH=amd64 go build -o exporter-linux

    Users download the binary for their platform and run it without needing a runtime. A typical workflow is: configure a token → start the program to enter the TUI → browse and load history list → select export mode → wait for export completion → press “Q” to quit.

    5. Conclusion

    The essence of this refactor was upgrading an “offline parser relying on official export files” into an “interactive data management tool that directly connects to the API.” Through five design points—token-based direct API access, lazy-loaded pagination, multiple export modes, local deduplication, and standardized Markdown output—the tool achieved significant improvements in usability, efficiency, and maintainability. This approach also applies to other scenarios where web data needs to be localized and persisted: first solve authentication and data retrieval, then interaction and filtering, and finally format and storage. A clear, single-responsibility layering is key to the long-term evolution of such terminal tools.