Refactoring a Terminal Conversation Export Tool: From Manual File Downloads to Direct API Access
This article walks through the refactoring of a terminal-based conversation export tool, moving from a manual export-and-convert workflow to a four-layer architecture that fetches data on demand. It covers the auth, collection, interaction, and output layers; full-screen terminal rendering driven by a state machine; cursor-based pagination and batch sizing; export modes and local deduplication; formatting rules that keep reasoning and answers readable; and practical guidance on credential safety, rate limiting, idempotent writes, and rollout order.
1. Background: From Moving Files to a Direct Data Path
Early conversation export solutions typically relied on a platform’s “export all data” feature: the user started an export request in the browser, waited for the platform to build an archive, downloaded and unpacked it, and then dragged the structured data files into a local script or CLI program for format conversion. The problem with this path is that it has too many stages and too many factors outside your control: export jobs have cooldown periods, data freshness depends on the user triggering the job manually, and any change to the file structure forces a matching change to the parsing logic.
The core goal of the refactor was to turn “the user hunts for data” into “the program fetches data on demand.” After the user completes authentication, the program uses the supplied credentials to call the history endpoints directly, pages through the conversation list and message details, and then feeds everything into a local processing pipeline. This approach has three benefits: first, the user controls when data is fetched instead of waiting in an export queue; second, only incremental data needs processing, avoiding a full conversion every time; third, it leaves room for interactive filtering later.
One point deserves emphasis: tools of this kind fall under personal data archiving. The prerequisite is that the data subject has authorized the access and supplied the credentials personally, and that the target platform’s terms of service and rate limits are respected. On the engineering side, avoid high-frequency polling; use reasonable request intervals and a failure backoff strategy.
2. Overall Architecture: Four Decoupled Layers
The refactored system splits into four layers that communicate through explicit data structures, which keeps UI logic and network logic from contaminating each other.
- Auth layer: accepts the session credentials provided by the user, validates them, and surfaces expiry messages. It never writes plaintext to disk and holds credentials in memory only briefly.
- Collection layer: handles list pagination, detail fetching, and field normalization, and outputs a unified conversation model (conversation ID, title, creation time, message array).
- Interaction layer: a full-screen terminal interface responsible for browsing, paging, selection, and status feedback.
- Output layer: template rendering, file naming, directory grouping, local deduplication, and writing.
The data flow looks roughly like this:
credential input -> paginate conversation list -> select conversations -> fetch message details-> normalize into a unified model -> render template -> dedup check -> write to disk
The immediate benefit of this split: the collection layer can implement throttling and retries on its own, the output layer can swap templates independently, and the interaction layer can degrade to “process cached data only” when there is no network.
3. Terminal UI: Full-Screen Rendering and a State Machine
Terminal interaction is usually built on an event-driven full-screen rendering framework, and its runtime model can be abstracted as a state machine: the model holds the current state (list offset, loaded cursor, set of selected items, hint message), and on each keyboard event it returns a new state plus optional side-effect commands (issue a request, write a file).
Key design points:
- Viewport and scrolling: terminal height is limited, so you need to track the start and end indices of the visible window and handle window boundaries and truncation of long titles.
- Layered loading states: distinguish “initial load,” “load next batch on scroll to bottom,” and “fetching details,” so users do not assume the program has frozen.
- Selection set: store selected IDs in a set, support select-all-on-current-page, invert, and clear, and preserve selections when switching pages.
- Visible errors: compress the failure reason into a single-line hint and keep a retry entry point instead of exiting the process outright.
A simplified state update skeleton:
type Model struct {offset intcursor stringloading boolselected map[string]struct{}hint string}func (m Model) Update(msg Msg) (Model, Cmd) {switch msg := msg.(type) {case KeyMsg:switch msg.String() {case "down":m.offset++case "space":m.selected[msg.ID] = struct{}{}case "enter":return m, fetchDetailCmd(msg.ID)}case BatchLoadedMsg:m.loading = falsem.cursor = msg.NextCursor}return m, nil}
4. On-Demand Loading: Cursor Pagination and Batch Sizing
On-demand loading is essentially about splitting one long wait into several short ones. Prefer a server-side cursor over page-number offsets, because the conversation list keeps growing and offset pagination tends to produce duplicates and gaps. Batch size is a trade-off between the number of requests and the latency of each response; in practice, one to two screens’ worth of entries works well, enough to fill the viewport without making the first load wait too long.
Three edge cases also need handling: end-of-list detection (an empty list or an empty cursor), duplicate fetches (the same batch arriving again after a network retry), and mid-stream expiry (expired credentials require aborting and prompting for re-entry). Attaching a batch identifier to each batch makes duplicates and gaps easier to trace.
5. Export Strategies and Local Deduplication
Export modes come down to three: the most recent N conversations, everything, or a manual selection. The only difference is how the target set is produced; the downstream pipeline is identical, which keeps behavior predictable.
Deduplication is the key to saving both requests and writes. Build an index in the output directory: derive a stable key from the conversation ID and update time, and check the index before writing. If the entry exists and the update time is unchanged, skip it; if the update time changed, overwrite it and mark it. The index can be an in-memory map plus a local manifest file, loaded once at startup.
key = hash(conversation ID + update time)if index[key] exists -> skipelse -> render and write, then update the index
6. Formatted Output: Making the Reasoning Readable
The value of a conversation record lies in reuse, so the output format matters more than merely being able to store something. A few general rules: use the date plus title as the filename and sanitize illegal characters; group files into monthly directories to keep the file count per directory manageable; write the body in standard markup with complete heading levels, lists, and closed code blocks; and visually separate reasoning passages in model output from the formal answer, for example by marking reasoning with a blockquote or a divider so it is not confused with the main text.
Code blocks need special handling: preserve the original language identifier, normalize line endings, and prevent triple backticks inside the content from breaking the fence structure. Keep tables and formulas as-is rather than “beautifying” or reflowing them, to avoid losing meaning.
7. Reliability, Security, and Maintainability
- Credential safety: never write credentials to logs, never pass them as command-line arguments, and clear them on exit; prompt the user to rotate them when necessary.
- Request restraint: fetch serially or with low concurrency, combined with exponential backoff; pause when rate-limit messages appear instead of retrying continuously.
- Idempotent writes: write to a temporary file first and then replace it atomically, so an interruption cannot leave a half-written file.
- Observability: report the number of records processed, skipped, and failed, so completeness can be verified.
- Cross-platform: abstract away path separators, filename length limits, and differences in terminal capabilities so behavior stays consistent across mainstream desktop and server environments.
8. Suggested Rollout Steps
- First get “fetch one page and print it” working end to end, to validate authentication and field structure.
- Then define the unified conversation model to isolate changes in API fields.
- Add the full-screen interaction and the selection set, keeping state updates purely functional.
- Fill in the rendering templates and directory rules, and proofread the layout repeatedly against a few samples.
- Finally add index-based deduplication and summary output, producing a repeatable archiving workflow.
Following this path, the tool evolves from a one-off script into maintainable personal knowledge archiving infrastructure. Whether the next step is bidirectional links into a note-taking app or support for additional data sources, both can be layered onto the existing structure smoothly.
