Refactoring a Terminal Conversation Export Tool: From Offline Files to an On-Demand Data Pipeline
This article walks through the architectural refactor of a tool that exports AI chat history from a web session into structured local Markdown files. It explains why file-driven full exports are slow, coarse-grained, and repetitive, then details the new four-layer design (credentials, transport, domain, and TUI/output), on-demand cursor-based loading, terminal state management, deduplication using session IDs plus content hashes, structured archiving conventions, credential security, cross-platform concerns, and a three-tier testing strategy. Readers can reuse the patterns for interface-based data-source isolation, state-machine-driven terminal interaction, incremental export, and atomic writes.
1. Background: Why Historical Conversations Are Hard to Reuse
Conversational AI has become a daily entry point for developers doing research, writing, and knowledge management. A common pain point is that valuable conversation content stays locked inside web sessions with no structured export capability, which makes long-term archiving difficult and prevents the content from entering a local note-taking workflow for further processing. Early solutions typically relied on the platform’s “export all data” feature: users had to download an archive, unpack it, and locate the structured data file inside. The flow was long and depended heavily on the platform finishing its export job.
This approach has three limitations:
- Long chain: export, download, unpack, place, parse — any failed step means starting over.
- Coarse granularity: only full exports are possible; you cannot grab just the latest few turns or a specific topic.
- High repetition cost: each run pulls the full dataset again, generating many wasted requests and duplicate files.
The core goal of the refactor was to replace “offline file-driven” operation with “session-credential-driven on-demand fetching,” and to upgrade the interaction layer from command-line arguments to a full-screen terminal interface.
2. Overall Architecture After the Refactor
The new design is split into four logical layers, decoupled through explicit data contracts:
- Credential layer: obtains and validates the session access credential, and surfaces expiry notices.
- Transport layer: paginates through the session list and message details, handling timeouts and retries.
- Domain layer: normalizes session models, sorts by time, and parses content blocks.
- Interaction and output layer: renders the terminal UI, manages selection state, deduplicates locally, and writes documents.
A schematic module breakdown (pseudocode, expressing responsibility boundaries only):
type Session struct {ID stringTitle stringUpdatedAt time.TimeTurns []Turn}type Fetcher interface {List(cursor string, size int) ([]Session, string, error)Detail(id string) (*Session, error)}type Exporter interface {Exists(s Session) (bool, error)Write(s Session) error}
Abstracting fetching and writing behind interfaces means deduplication logic and rendering logic can be tested independently, and switching to another data source later only requires swapping the implementation.
3. Key Design One: On-Demand Loading and Terminal Interaction
A full session list can reach hundreds or even thousands of entries, and loading everything at once causes noticeable waiting. On-demand loading maintains a cursor and a page size, triggers the next request when the user scrolls near the bottom of the list, and caches loaded data in memory to avoid duplicate requests.
The terminal interaction is essentially a finite state machine problem, and it helps to model the UI states explicitly:
- Browse state: move up/down, page through, search and filter.
- Selection state: toggle with space, confirm with enter, select all or clear with a key.
- Export state: progress display, skip count, retry on failure.
- Exit state: confirmation prompt to avoid losing selections by accident.
Pseudocode for the state transitions:
switch key {case "up", "down":state.move(delta)case " ":state.toggle()case "enter":state.confirmAndExport()case "q":state.quit()}
On the engineering side, terminal rendering performance also matters: redraw only the visible region to avoid the flicker of a full-screen refresh, and truncate long titles with ellipses so the list stays aligned.
4. Key Design Two: Local Deduplication and Incremental Export
Deduplication is the key to saving requests and keeping the output directory clean. The reliable approach is not comparing titles but combining the session’s unique identifier with a content digest: first scan existing files in the target directory, parse the session identifier out of the filename or file-header metadata, and build a local index set; before exporting, query that set and skip on a hit.
local index = { session ID -> file path }if session ID ∈ local index AND content digest matches → skipotherwise → write or overwrite
Introducing a content digest (for example, a hash of the normalized body) handles the case where the same session has been updated and needs re-exporting, giving true incremental semantics. Writes should use a temporary file plus an atomic rename so a mid-way failure does not leave a truncated file behind.
5. Key Design Three: Structured Formatting and Archiving
The value of an export depends on readability. The recommended conventions are:
- File naming: date plus title, with illegal characters replaced to prevent cross-platform path errors.
- Directory layout: grouped by year and month, so note-taking apps can index by folder.
- Content structure: a level-one heading with the session title, a metadata block with time and turn count, then user prompts and model replies output turn by turn.
- Separating reasoning from the final answer: carry the reasoning process in a quote block or collapsible section, keeping the main body clean for later search and citation.
Example output skeleton:
# Session Title- Updated: 2026-05-01 12:30- Turns: 6## Turn 1**Prompt**...**Answer**...> Reasoning (collapsible)...
6. Credential Handling, Security, and Compliance
The new design no longer relies on offline files and instead needs a browser-side session credential. The security boundary must be emphasized here: the credential is equivalent to temporary access rights to the account, so it should be kept only in local memory or a user-private config, never written to logs, never hard-coded, and never distributed along with exported files. When an expiry notice appears, guide the user to obtain a fresh credential rather than trying to bypass validation. Export behavior should also stay within the scope of the user’s own data and comply with the target platform’s terms of service and data usage policies.
7. Cross-Platform Support and Portability
Cross-platform concerns concentrate in three places: path separators and illegal filename characters; terminal capability detection (different terminals support color and cursor control differently, so rendering must degrade gracefully); and the runtime dependency introduced by single-file static distribution. For users without a build environment, a community-maintained equivalent script implementation can be offered, but the documentation should note its feature differences and maintenance status.
8. Version Evolution and Verification Strategy
Refactoring changes are the most prone to regressions, so a three-tier verification approach is recommended:
- Unit tests: model parsing, filename sanitization, deduplication decisions.
- Contract tests: use fixed sample data to simulate paginated and detail responses, verifying cursor advancement and termination conditions.
- End-to-end rehearsal: verify the browse, select, export, and repeated-run paths on a small dataset.
9. Summary
The essence of this refactor is upgrading a “file conversion script” into a “local data pipeline with interaction, incremental, and archiving capabilities.” Reusable lessons for readers include isolating the data source behind interfaces, managing terminal interaction with a state machine, achieving incremental export with an identifier plus a digest, and guaranteeing file integrity with atomic writes. To connect export results to the cloud, you can further combine object storage for long-term archiving, use a logging service to record export audits, and use monitoring and alerting to track failure rates, smoothly evolving a personal tool into a data archiving solution a team can use.
