Refactoring a Conversation History Export Tool with a Terminal UI

    Learn how to refactor an offline conversation history export script into an online tool with a terminal-based interactive UI. This article covers token authentication, lazy-loading pagination, flexible export modes, local deduplication, and Markdown formatting—plus cross-platform build and distribution practices.

    Refactoring a Conversation History Export Tool with a Terminal UI

    1. Background and Problem Analysis

    Many AI chat platforms accumulate large volumes of valuable Q&A records, which are often important raw material for personal knowledge bases and technical retrospectives. However, these platforms typically only offer a one-shot, full-archive export capability, which comes with several pain points:

    1. Coarse export granularity: Only full export is supported. Users cannot selectively export specific conversations, resulting in huge files mixed with a lot of irrelevant content.
    2. Difficult incremental backup: Every export contains duplicate historical data. Without a deduplication mechanism, organizing the results afterward is extremely costly.
    3. Unfriendly formats: Raw exports are usually JSON with deeply nested fields, making them unusable directly in note-taking software.
    4. Lack of interactive experience: Pure command-line batch processing is unfriendly to non-technical users and lacks a visual selection process.

    The core goal of this refactoring is to upgrade the original offline mode—“parse the platform’s export file”—to an online mode that “talks to the platform API directly,” while introducing a full-screen terminal user interface (TUI) to achieve an integrated workflow of on-demand loading, precise selection, and smart deduplication.

    2. Overall Architecture

    The refactored tool is organized into four layers:

    1. ┌─────────────────────────────────────┐
    2. │ TUI Layer (keyboard-driven UI) │
    3. ├─────────────────────────────────────┤
    4. │ Session Management (pagination/ │
    5. │ selection/state machine) │
    6. ├─────────────────────────────────────┤
    7. │ Data Fetching (token auth + paged │
    8. │ API calls) │
    9. ├─────────────────────────────────────┤
    10. │ Export Engine (dedup/format/write) │
    11. └─────────────────────────────────────┘
    • TUI layer: Built on a terminal UI framework, it provides a full-screen interface supporting arrow-key navigation, space to select, Enter to confirm, and Q to quit. It requires no graphical environment, so it works equally well on servers and over SSH sessions.
    • Session management layer: Maintains the loading, selection, and export states of the conversation list—a classic state machine model.
    • Data fetching layer: Calls the platform’s history session API with a user-provided web token, pulling data page by page.
    • Export engine layer: Converts JSON conversation content into well-formatted Markdown and implements deduplication via existence checks on the local filesystem.

    3. Key Implementation Details

    3.1 Token Acquisition and Authentication

    Unlike the old version, which relied on the platform’s full export files, the new version mimics browser requests. The user first logs in on the web, opens the browser’s developer tools, finds a request header carrying user credentials in the Network panel, and copies the token value. The tool places it in the authentication header when calling the API:

    1. GET /api/v0/chat_session/fetch_page
    2. Authorization: Bearer <userToken>

    The advantage of this approach is that the data is always up to date, eliminating the manual “export—unzip—drag” loop. Note that a token is a sensitive credential: the tool should store it only in local configuration and never upload or transmit it elsewhere.

    3.2 Lazy-Loading Pagination Strategy

    A user may have hundreds or thousands of historical conversations; fetching them all at once is slow and wasteful. The tool adopts a lazy-loading strategy: initially only the first page of conversation summaries (title, update time, ID) is loaded, and the next page request is triggered automatically as the user scrolls near the bottom of the list. The logic looks like this:

    1. func (m *Model) maybeLoadMore() {
    2. if m.cursor >= len(m.items)-preloadThreshold && m.hasMore {
    3. go m.fetchNextPage()
    4. }
    5. }

    This design amortizes network overhead across the user’s browsing, keeping the UI responsive while avoiding pulling the entire dataset for users who only want to export the most recent few conversations.

    3.3 Flexible Export Modes

    The tool offers three export modes to cover different scenarios:

    Mode Use Case
    Export recent Daily incremental backups of the latest N conversations
    Export all First-time full archiving
    Manual selection Precisely exporting conversations on specific topics

    In manual selection mode, the user marks target items with the spacebar and presses Enter to batch-export the selected records. The interaction path is clear, and the cost of mistakes is low.

    3.4 Local Deduplication

    Deduplication is the key to incremental backup. The tool uses each conversation’s unique ID (or a stable filename generated from “date + title”) as the dedup key, checking the target directory before exporting:

    1. func alreadyExported(id string) bool {
    2. _, err := os.Stat(filepath.Join(exportDir, id+".md"))
    3. return err == nil
    4. }

    Conversations that already exist are skipped and marked in the UI. This not only saves disk space but also reduces API calls, lowering the risk of hitting platform rate limits. Going further, the tool can maintain a local index file recording content hashes of exported conversations to handle cases where the user manually renames files.

    3.5 Markdown-Formatted Output

    The raw conversation data is structured JSON containing user questions, assistant answers, and intermediate “deep reasoning” content. The export engine must restore it into highly readable Markdown:

    • Use “date + conversation title” as the filename for easy sorting and searching;
    • Group files by month under the export directory to avoid too many files in a single folder;
    • Separate user questions and assistant answers with blockquotes or headings;
    • Display reasoning processes and regular answers in distinct sections, preserving original syntax highlighting markers in code blocks.

    The converted files can be indexed directly by various note-taking tools and, combined with a tagging system, enable secondary organization of knowledge.

    4. Cross-Platform Build and Distribution

    The tool is implemented in a statically compiled language. Through cross-compilation, binaries for mainstream desktop platforms (amd64/arm64 architectures) are produced in one pass, so users need no runtime installation. Meanwhile, community-driven implementations in scripting languages provide an alternative for users who cannot install a compilation toolchain—a typical healthy path for an open-source tool ecosystem.

    5. Summary and Further Thoughts

    The essence of this refactoring is upgrading a “file format conversion script” into a complete toolchain of “data fetching + interactive selection + incremental export.” Its methodology is broadly applicable: lazy loading reduces resource consumption, local state enables idempotent export, and a terminal UI balances user experience with portability. Similar ideas can be extended to email archiving, cloud document synchronization, log collection, and more. In enterprise settings, this kind of personal knowledge asset can further integrate with general-purpose cloud capabilities such as object storage and log services for centralized backup and retrieval, building a more complete knowledge management loop.