Refactoring a Terminal Session Export Tool: TUI Architecture and Incremental Export Design

    This article walks through the refactoring of a Go-based tool for exporting chat history from LLM conversation platforms. It covers the shift from manual file-based exports to direct API access, a Bubble Tea-style TUI built on the Elm architecture, lazy loading with smart pagination, three export strategies, deterministic filename-based deduplication, and Markdown formatting that separates reasoning traces from final answers. Practical guidance on credential security, rate limiting, and idempotent design is also included.

    1. Background and Motivation

    Users of LLM chat products often accumulate a large volume of valuable content: technical research notes, code design discussions, and idea logs. However, this content usually lives only in the platform’s cloud. When users want to consolidate it into a personal knowledge base (for example, a Markdown-based note-taking app), they run into several typical pain points:

    1. Heavy export dependencies: Early solutions typically required users to manually request a full data export on the web, wait for the platform to generate an archive, download and extract it, and then feed a specific JSON file into a local script — a long and tedious pipeline.
    2. No selectivity: Full exports offer no way to pick specific conversations. Even if you only want to back up a few recent chats, you still have to process everything.
    3. No deduplication: Repeated exports produce large numbers of duplicate files, and manual cleanup is costly.
    4. Poor format fidelity: Reasoning traces (“thinking” content) and final answers are interleaved, so the converted Markdown ends up with a messy hierarchy that is hard to file into a knowledge base.

    Based on these issues, the core goal of the refactor was set: eliminate the dependency on official export files, pull history directly through the API, and provide a smooth terminal interface for selection, deduplication, and formatted export.

    2. Overall Architecture

    The refactored tool is implemented in Go and organized into four layers:

    1. ┌─────────────────────────────┐
    2. │ TUI layer (Bubble Tea style) │ ← Full-screen terminal UI, keyboard-driven
    3. ├─────────────────────────────┤
    4. │ Orchestration layer │ ← Selection strategy / dedup / grouped export
    5. ├─────────────────────────────┤
    6. │ Data access layer │ ← Token management + paginated API calls
    7. ├─────────────────────────────┤
    8. │ Formatting/output layer │ ← Markdown rendering and disk writes
    9. └─────────────────────────────┘

    2.1 Why a TUI

    Compared with a web interface or a GUI, a TUI offers three clear advantages:

    • Zero-dependency deployment: A single binary runs cross-platform (Windows / macOS / Linux, covering both amd64 and arm64) with no runtime to install.
    • Keyboard-first: For developers, pure keyboard interaction (arrow keys to browse, space to select, Enter to confirm, Q to quit) is far more efficient than mouse clicks.
    • Natural fit with terminal workflows: It can be seamlessly embedded into scripts and automation pipelines.

    The interaction framework follows the well-known Elm architecture (Model–Update–View), which decouples state, events, and rendering. This makes complex UI state — such as paginated loading and checkbox selections — much easier to maintain.

    3. Key Implementation Details

    3.1 Token Acquisition and Direct Data Access

    The biggest change in the refactor is that the tool no longer depends on manually exported platform files. The workflow is:

    1. The user logs in to the chat platform in a browser;
    2. Opens the developer tools’ Network tab and locates the authentication token in the request headers;
    3. Pastes the token into the tool, which then calls the session list API with that credential.

    The data access layer wraps a unified session list client, abstracted behind a core interface:

    1. type SessionFetcher interface {
    2. // Fetch session metadata (title, time, ID) by page
    3. ListSessions(ctx context.Context, page, pageSize int) ([]SessionMeta, error)
    4. // Fetch the full message list of a single session by ID
    5. FetchMessages(ctx context.Context, sessionID string) ([]Message, error)
    6. }

    This abstraction brings two benefits: first, when the upstream API changes, only the implementation layer needs to be updated; second, it is easy to write mocks for unit tests.

    3.2 Lazy Loading and Smart Pagination

    Chat history can contain hundreds or thousands of conversations. Pulling everything at once is both slow and likely to trigger API rate limits. The tool adopts a load-on-demand strategy:

    • On startup, only the first page of metadata (title + summary) is fetched to render the list;
    • The next page is requested only when the user pages forward;
    • Full message bodies are fetched only for conversations the user has selected.

    This compresses network traffic from “all sessions × all messages” down to “selected sessions × message bodies”. With several hundred conversations, this can reduce waiting time by an order of magnitude.

    3.3 Three Export Strategies

    Mode Use case Behavior
    Recent export Routine incremental backup Automatically selects the most recent N conversations
    Full export First-time migration Fetches and converts all records
    Manual selection Fine-grained curation Space to select in the paginated list, Enter to confirm

    3.4 Local Smart Deduplication

    Deduplication runs before export to avoid wasting API calls:

    1. func isExported(targetDir, filename string) bool {
    2. _, err := os.Stat(filepath.Join(targetDir, filename))
    3. return err == nil // If the file exists, treat it as already exported
    4. }

    Files are named with a deterministic “date + conversation title” rule, which guarantees that the same conversation hits the same filename no matter when it is exported — achieving “skip if it exists”. The output layer also groups files into monthly subdirectories (e.g., conversations_export/2026-05/), making it easy to browse and archive along a timeline.

    3.5 Automatic Markdown Formatting

    The formatting layer needs to handle two types of content differently:

    • Reasoning traces: Rendered as blockquotes or collapsible sections, visually separated from the final answer;
    • Final answers: Native Markdown structures such as code blocks, lists, and headings are preserved.

    Key processing steps during conversion include: escaping special characters that would break Markdown syntax, normalizing code block language annotations, and converting message timestamps into a readable metadata header. The exported files can be indexed directly by common Markdown note-taking apps, and combined with backlinks and tags to complete the knowledge base workflow.

    4. Version Evolution

    • Version 1: Relied on the platform’s manually exported JSON file as input, ran via drag-and-drop on the command line. Functional, but the pipeline was cumbersome.
    • Refactored version: Direct API access + TUI interaction + lazy loading + deduplicated export, forming a complete closed loop.

    This evolution reflects the typical iteration pattern of tooling projects: first validate the core conversion capability with a minimal solution, then build out interaction, performance, and robustness around the user experience. In addition, an equivalent Python implementation has appeared in the community, lowering the barrier for users without a Go environment — which also demonstrates that an architecture with core logic decoupled from the implementation language is highly portable.

    5. Practical Recommendations

    If you plan to build a similar tool for local management of conversation data, consider the following:

    1. Credential security: Keep sensitive data such as user tokens in memory or in an encrypted local config; never write them to logs;
    2. Rate limiting and retries: Add backoff retries and frequency control to API calls to avoid triggering risk controls;
    3. Idempotent design: Deterministic filenames + existence checks make export operations safe to repeat;
    4. Structure first: Separate data access, orchestration, and rendering layers so you can adapt to upstream API changes;
    5. Preserve metadata: Keep timestamps, titles, and other metadata in the Markdown to lay the groundwork for future knowledge base search.

    6. Conclusion

    This refactor upgraded the original “manual export file + script conversion” approach into a complete toolchain of “direct API access + TUI interaction + incremental deduplication + automatic formatting”, effectively solving the problem of backing up and reusing conversation history. Its design ideas — lazy loading to reduce request volume, deterministic naming for deduplication, and layered architecture for maintainability — are valuable references for any scenario involving the localization of large volumes of structured records.