The Interface Codex
The Controls That Inspect and Query: Exhaustive Reference for All 33 System Interfaces
Every control, interface boundary, and utility in this codex answers three architectural questions: What it does (user actions, triggers, and UI changes), How it works (internal execution trace across DOM elements, state transitions, and asynchronous promises), and Why it works (software invariants, security rationale, and failure resilience).
📂 File Loading & Ingestion (4 Controls)
Foundational controls for ingesting individual Markdown documents or whole folder hierarchies into workspace memory.
| Control / Action | Synopsis / Target | Summary |
|---|---|---|
| ADD FILES | #fileInputLabel / #mdFileInput |
Opens native file selection dialog to ingest one or more .md documents. |
| Scan Folder | #scanFolderBtn |
Recursively scans a chosen directory tree for Markdown files via the File System Access API. |
| FILES Readout | #fileCountDisplay |
Displays real-time count of total Markdown documents currently loaded in memory. |
| File Ingestion Filter | addFilesAndDisplay() |
Filters incoming files, rejects non-markdown files, skips duplicate file contents. |
ADD FILES : Native File Picker
INTERACTION: Click #fileInputLabel -> Trigger change event on #mdFileInput -> Process FileList
Opens the operating system's native multi-file selection picker filtered to .md documents, reads selected files asynchronously, and populates the workspace buffer.
- Clicking
#fileInputLabeltriggers the hidden<input type="file" multiple accept=".md">element. - On
change, files are mapped to an array of Promises reading text viafile.text(). addFilesAndDisplay()receives{name, content}objects, rejects duplicates already existing instate.loadedFiles, and selects an initial document to render.- Clears the input's value so selecting the same file again triggers a fresh change event.
Standard HTML5 file inputs provide universal cross-browser compatibility across all desktop and mobile platforms without requiring experimental browser permissions.
Scan Folder : Recursive Directory Scanner
INTERACTION: Click #scanFolderBtn -> window.showDirectoryPicker() -> Recursive scan() traversal
Prompts the user to select an entire directory tree, traverses all nested subdirectories, and loads every .md document found.
- Feature-detects
window.showDirectoryPicker; if unsupported, alerts the user to use the file picker or switch to Chromium. - Calls
window.showDirectoryPicker(), obtaining a rootFileSystemDirectoryHandle. - An asynchronous recursive generator
scan(dirHandle)traverses directory entries usingfor await (const entry of dirHandle.values()). - For each file ending in
.md, reads content viaawait entry.getFile().text()and streams the file intoaddFilesAndDisplay().
Allows instant exploration of large Obsidian vaults, documentation repositories, and note collections with a single click, skipping non-markdown assets automatically.
FILES Readout : Workspace Document Counter
INTERACTION: Triggered automatically by updateUI() -> Reflects state.loadedFiles.length
Renders the total count of loaded Markdown documents in the retro status footer (e.g. FILES: 42).
Whenever files are added, restored, or restarted, updateUI() executes elements.fileCountDisplay.textContent = `FILES: ${state.loadedFiles.length}`.
Provides immediate peripheral feedback to the user on the scale of their active workspace corpus.
File Ingestion Filter : Duplicate & Type Guard
INTERACTION: Invoked by addFilesAndDisplay(newFiles) -> Content deduplication & verification
Prevents duplicate documents from cluttering the workspace and ensures only valid markdown files enter the buffer.
- Filters incoming file objects by comparing filename and text content against existing entries in
state.loadedFiles. - If a file matches both name and content, it is skipped.
- Updates the status log with counts of added files and skipped duplicates (e.g. "Loaded 5 files (2 duplicates skipped).").
Prevents memory waste and duplicate search results when users scan overlapping folders or re-select files.
🧠 Document Intelligence & Single-File AI (6 Controls)
Intelligence operations performed strictly against the currently active Markdown document.
| Control / Action | Synopsis / Target | Summary |
|---|---|---|
| Summarize | #summarizeBtn |
Requests a concise, structured executive summary of the current document. |
| Suggest | #suggestQuestionsBtn |
Generates 3 to 5 insightful follow-up questions rendered as clickable buttons. |
| Ask Form | #askForm |
Form container managing keyboard submission and event handling for inquiries. |
| Ask Input Field | #askInput |
Text input field where users enter free-form follow-up questions about the active file. |
| Ask Submit Button | #askBtn |
Submits the question entered in the Ask Input field to the local model. |
| Question Buttons | .suggested-question-btn |
Clickable buttons representing suggested questions that trigger instant queries. |
Summarize : Executive Synthesis
INTERACTION: Click #summarizeBtn -> callModel() -> Append sanitized summary to #markdownDisplay
Prompts the local model to distill the current document into a high-level summary highlighting key themes and arguments.
- Locks UI controls and activates the header loader spinner.
- Dispatches the file text paired with the prompt: "Provide a concise summary of the following document. Highlight key points and main ideas."
- Captures the model response, verifies view invariance (
isStale()), parses Markdown via DOMPurify, and appends the result to the display viewport.
Allows rapid comprehension of long technical articles, transcripts, or notes without leaving the document context.
Suggest : Interactive Inquiry Generation
INTERACTION: Click #suggestQuestionsBtn -> callModel() -> Render .suggested-question-btn items
Generates 3 to 5 probing questions regarding the document's content and formats each question as an interactive button.
Asks the model to suggest questions a curious reader might ask. Parses lines beginning with numbers (e.g. 1. Why...) into interactive <button class="suggested-question-btn"> elements with bound click listeners.
Promotes deeper engagement with texts by highlighting nuances or unexplored ramifications of the author's arguments.
Ask Form : Inquiry Submission Controller
INTERACTION: Submit event -> e.preventDefault() -> askAboutCurrentFile(askInput.value)
Captures Enter keypresses or button clicks to trigger follow-up questions without reloading the page.
Binds a submit listener that prevents default navigation, checks if an answer is already in flight (state.isAsking), extracts trimmed text, and initiates the query.
Semantic form markup provides native keyboard submission handling (Enter to submit) while preserving single-page execution.
Ask Input Field : Free-Text Query Field
INTERACTION: User types question -> Managed enabled/disabled state via updateUI()
Receives arbitrary user questions concerning the currently displayed file.
Disabled when no files are loaded or while an inference request is in progress. Clears value on submit and automatically re-focuses when the model response completes.
Enables natural language follow-up conversations directly within the console without requiring modal dialogs.
Ask Submit Button : Query Dispatch Button
INTERACTION: Click #askBtn -> Triggers #askForm submission
Visual button to submit the question typed into the Ask Input field.
Configured with type="submit" inside #askForm. Synchronously disabled whenever #askInput is disabled.
Provides an explicit touch- and mouse-accessible target alongside keyboard Enter submission.
Question Buttons : Clickable Suggestion Triggers
INTERACTION: Click button -> askAboutCurrentFile(button.textContent)
Clicking any generated suggestion immediately dispatches that exact question to the model.
Constructed dynamically by suggestQuestionsBtn. Each button has a click listener invoking askAboutCurrentFile(questionText), adding the query to the conversation stack.
Eliminates the friction of manually copying and pasting suggested questions into the input bar.
📚 Corpus Synthesis & Multi-Document Analysis (2 Controls)
Intelligence operations performed across all documents currently loaded in the workspace.
| Control / Action | Synopsis / Target | Summary |
|---|---|---|
| Ask All Files | #askAllFilesBtn |
Queries every loaded Markdown document to synthesize cross-file answers. |
| Corpus Input Modal | #inputModal |
Asynchronous modal dialog prompting the user for their cross-document inquiry. |
Ask All Files : Global Corpus Synthesis
INTERACTION: Click #askAllFilesBtn -> showInputModal() -> Concatenate files -> callModel()
Synthesizes an answer to a single question across all loaded documents simultaneously, citing sources across files.
- Calls
showInputModal()to capture the query text. - Concatenates all documents in
state.loadedFileswith clear delimiters (File: <name>). - Dispatches the prompt to the local model, captures the response, verifies that the view hasn't been reset (
isStale()), and displays the answer under an "Ask All Files" heading.
Acts as an ambient knowledge synthesis engine across disparate personal notes without requiring an external vector database.
Corpus Input Modal : Asynchronous Query Dialog
INTERACTION: showInputModal({title, prompt}) -> Resolves with string or null
Displays an overlay dialog requesting string input from the user with full keyboard navigation (Enter/Escape).
Returns a Promise that unhides #inputModal, sets labels, focuses the input field, and resolves with the entered string on Confirm/Enter or null on Cancel/Escape.
Replaces blocking browser prompt() dialogs with a styled, non-blocking asynchronous interaction that matches the console aesthetic.
⚙️ Model Configuration & Local AI Engine (7 Controls)
Controls governing model server endpoints, discovery, and parameters.
| Control / Action | Synopsis / Target | Summary |
|---|---|---|
| Model Settings Button | #modelSettingsBtn |
Opens the Local Model Configuration dialog modal. |
| Server Type Selector | #modelApiStyle |
Selects between Ollama native REST and OpenAI-compatible API endpoints. |
| Server URL Input | #modelBaseUrl |
Input for configuring the local server loopback address. |
| Model Dropdown Selector | #modelName |
Populated dropdown of available chat models fetched from the server. |
| Refresh List Button | #fetchModelsBtn |
Actively queries the local server to refresh the model dropdown list. |
| Save Model Settings | #saveModelSettingsBtn |
Validates loopback constraints and saves settings to state and storage. |
| Cancel Model Settings | #cancelModelSettingsBtn |
Dismisses the model settings dialog without applying changes. |
Model Settings Button : Server Configuration Opener
INTERACTION: Click #modelSettingsBtn -> showModelSettings() -> Unhide #modelSettingsModal
Opens the Model Settings modal dialog, pre-populating existing settings and querying available models.
Initializes form fields from state.modelSettings (or defaults), clears error messages, unhides #modelSettingsModal, and invokes fetchAndFillModels().
Gives users immediate visual access to local server configuration without editing text configuration files.
Server Type Selector : Protocol Adapter Dropdown
INTERACTION: Change selection -> Adjust default URL placeholder & endpoint routing
Switches between Ollama's native protocol and the OpenAI-compatible completions format.
Changing selection updates the URL placeholder to the protocol's default (http://localhost:11434 for Ollama, http://localhost:8080/v1 for OpenAI) and refreshes model capability queries.
Provides transparent protocol switching across popular local inference runtimes without manual header configuration.
Server URL Input : Loopback Address Target
INTERACTION: Input URL -> Validated against isLocalUrl() on change / save
Specifies the network address of the local model daemon.
Accepts loopback URLs. Validated by isLocalUrl() to ensure requests never leave the machine.
Allows users to bind custom ports (e.g. LM Studio on 1234, vLLM on 8000) while strictly maintaining the Zero-Key localhost perimeter.
Model Dropdown Selector : Capability-Filtered Picker
INTERACTION: User selects model -> Captured into state.modelSettings.model
Lists available models with disabled states for non-chat embedding models (Roadmap P2-04).
Populated by fillModelSelect(). Capable models are listed first; embedding-only models are disabled and appended at the bottom with visual notices.
Prevents model selection errors and avoids failures caused by calling embedding models for text generation.
Refresh List Button : Live Endpoint Prober
INTERACTION: Click #fetchModelsBtn -> Query /api/tags or /models -> Re-populate #modelName
Actively queries the configured server URL to fetch newly pulled or loaded models.
Validates the URL with isLocalUrl(), fetches model listings, executes capability probing, and updates the select options.
Users can pull new models in another terminal (e.g. ollama pull phi4) and refresh the list without reloading the web page.
Save Model Settings : Configuration Committer
INTERACTION: Click #saveModelSettingsBtn -> Validate -> state.modelSettings -> saveSession()
Validates inputs, commits configuration to application state, persists settings to localStorage, and closes the modal.
- Enforces non-empty URL and selected model.
- Verifies
isLocalUrl(baseUrl); displays an inline error if external. - Assigns
state.modelSettings = {apiStyle, baseUrl, model}, callssaveSession(), and hides the modal.
Atomic validation ensures that invalid or unsafe configurations can never be committed to runtime state.
Cancel Model Settings : Dialog Dismissal
INTERACTION: Click #cancelModelSettingsBtn -> Hide #modelSettingsModal without mutation
Closes the Model Settings modal without modifying existing configuration.
Adds the hidden class to #modelSettingsModal, discarding uncommitted form adjustments.
Provides a safe escape route from configuration dialogs without side effects.
💾 Session Persistence & Storage Management (5 Controls)
Controls managing persistent state snapshots, hydration, and quota limits.
| Control / Action | Synopsis / Target | Summary |
|---|---|---|
| Save Session | #saveSessionBtn |
Persists the current workspace state to browser localStorage. |
| Restart Session | #restartSessionBtn |
Wipes active session state and purges stored session data. |
| Restore Confirm | #confirmRestoreBtn |
Confirms rehydration of a saved session discovered on page boot. |
| Restore Deny | #denyRestoreBtn |
Declines session restoration to start with a fresh workspace. |
| Quota Circuit Breaker | saveSession() try/catch |
Traps quota errors when session size exceeds browser limits (P2-02). |
Save Session : Snapshot Serializer
INTERACTION: Click #saveSessionBtn -> saveSession() -> localStorage.setItem('chidiMdSession', json)
Serializes all loaded files, navigation history, active conversations, and model configurations into localStorage.
Packages {loadedFiles, history, historyIndex, chatHistory, modelSettings} into a JSON string and writes to chidiMdSession. Updates the status log with "Session saved."
Users can close their browser or shut down their workstation and return directly to their exact reading and conversation state.
Restart Session : Complete State Wipe
INTERACTION: Click #restartSessionBtn -> restartSession() -> Reset state & localStorage
Wipes all in-memory files, conversations, and history, removes the saved session from localStorage, and resets the console.
Removes chidiMdSession from localStorage, resets state.loadedFiles = [], state.history = [], state.chatHistory = [], increments state.viewId to invalidate pending requests, and resets the UI.
Provides a clean slate for starting a new document reading session without lingering state from previous vaults.
Restore Confirm : Session Hydration
INTERACTION: Click #confirmRestoreBtn -> restoreSession() -> Hide #restoreSessionModal
Restores previously saved workspace files and conversation threads on application startup.
Parses the stored JSON payload, re-populates state arrays, restores the last viewed file, purges any legacy secrets, and updates the status log.
Gives the user explicit control over whether to resume prior work or begin fresh.
Restore Deny : Discard Saved Workspace
INTERACTION: Click #denyRestoreBtn -> localStorage.removeItem('chidiMdSession') -> Hide modal
Rejects restoring the saved session, clears the stored record, and presents a clean start.
Removes chidiMdSession from localStorage, hides the modal, and leaves the console in its default ready state.
Allows users to cleanly discard stale sessions without manually navigating browser developer tools.
Quota Circuit Breaker : Storage Exhaustion Protector
INTERACTION: Catch QuotaExceededError in saveSession() -> Alert user with session MB calculation
Traps browser storage quota exceptions when saving sessions that exceed ~5 MB and alerts the user while leaving prior saves intact.
Wraps localStorage.setItem in a try/catch block. On exception, calculates payload megabytes and logs: "Error: Session is ~X MB; browser storage is full. Your previous save is still kept."
Prevents unhandled crashes and data loss when loading large corpora, preserving previous saves safely.
🛡️ Security Boundaries & Sanitization (4 Controls)
Architectural filters enforcing input validation, sanitization, and network isolation.
| Control / Action | Synopsis / Target | Summary |
|---|---|---|
| DOMPurify Sanitizer | convertMarkdownToHtml() |
Strips XSS vectors and script tags from all rendered Markdown output. |
| Localhost URL Enforcer | isLocalUrl() |
Restricts network communication strictly to local loopback hosts. |
| Stale Response Quarantine | isStale() / state.viewId |
Quarantines late AI responses to prevent cross-document contamination. |
| Legacy Credential Scrubber | restoreSession() cleanup |
Automatically scrubs legacy API keys from older saved sessions. |
DOMPurify Sanitizer : Render Security Boundary
INTERACTION: DOMPurify.sanitize(marked.parse(content)) -> Verified safe HTML string
Sanitizes all HTML generated from Markdown files and model responses before it touches the DOM.
Filters AST HTML output via pinned DOMPurify 3.4.16, stripping inline event handlers (onerror), script elements, and javascript: URI schemes.
Guarantees that untrusted or hostile Markdown documents cannot execute arbitrary code in the user's browser.
Localhost URL Enforcer : Network Perimeter Guard
INTERACTION: isLocalUrl(url) -> Strict loopback verification before fetch()
Ensures that outbound model requests are only sent to the user's local machine.
Parses the hostname via the standard URL constructor and validates that it matches localhost, 127.0.0.1, [::1], or ends with .localhost.
Prevents data exfiltration and accidental requests to third-party cloud APIs.
Stale Response Quarantine : View Invariance Guard
INTERACTION: Capture state.viewId at request start -> Check isStale() at resolution
Drops responses that arrive after the user has navigated to another document or restarted the session.
Increments state.viewId on document change. When a response resolves, verifies that the active view ID matches the captured view ID. If mismatched, drops output and logs a notice.
Protects conversation integrity from race conditions caused by slow model generation.
Legacy Credential Scrubber : Storage Sanitizer
INTERACTION: restoreSession() -> delete parsedData.apiKey -> saveSession()
Detects and scrubs legacy cloud API keys from sessions created by older versions of the app.
During session restoration, checks for apiKey or geminiChatHistory properties, removes them from state, and re-saves the clean session.
Ensures user secrets are completely evicted from persistent storage in compliance with the Zero-Key Mandate.
🖥️ Operational Feedback & Console Telemetry (3 Controls)
UI indicators providing operational status and activity telemetry.
| Control / Action | Synopsis / Target | Summary |
|---|---|---|
| SYSTEM LOG Readout | #messageBox |
Status bar rendering system events, operational state, and error alerts. |
| Activity Loader | #loader |
Animated console spinner indicating background model inference. |
| Console Title Header | #mainTitle |
Top console header displaying product title and active document filename. |
SYSTEM LOG Readout : Console Message Bar
INTERACTION: Updated via elements.messageBox.textContent = `SYSTEM LOG: ${msg}`
Renders real-time feedback on user actions, model generation progress, and system alerts.
Displays standardized status messages (e.g. "SYSTEM LOG: Standby.", "SYSTEM LOG: Answering question...", "SYSTEM LOG: Error: ...").
Provides a consistent, non-intrusive status readout that avoids distracting popup notifications.
Activity Loader : Inference Activity Spinner
INTERACTION: Toggled via #loader.classList.remove('hidden') / add('hidden')
Displays an animated spinner in the console header during active model inference or file loading.
Controlled by setLoading(true/false). Unhides the CSS animation when an operation begins and hides it upon completion.
Informs users that the system is processing their request, especially during longer model generations.
Console Title Header : Header & Breadcrumb Display
INTERACTION: Reflects active file name: 'chidi.md // '
Displays the application title and active document filename in retro terminal styling.
Updates on document navigation to display chidi.md // <filename>, resetting to default when no file is active.
Gives users clear, persistent context on which document they are currently viewing.
🛠️ Developer & Verification Tooling (4 Controls)
Command-line utilities and test harnesses ensuring code quality and safety.
| Control / Action | Synopsis / Target | Summary |
|---|---|---|
| serve.py | python3 tools/serve.py |
Local development server with no-cache headers and browser auto-launch. |
| check_docs.py | python3 tools/check_docs.py |
Automated documentation auditor verifying links, roadmap items, and decisions. |
| check_structure.py | python3 tests/check_structure.py |
Fast linting script verifying DOM ID wiring and sanitization rules. |
| Playwright Smoke Suite | cd tests/e2e && npm test |
34-test dual-browser end-to-end verification suite in Chromium and Firefox. |
serve.py : Development Server & Cache Buster
SYNOPSIS: python3 tools/serve.py [--port 8000] [--no-browser]
Serves the application locally with strict Cache-Control: no-cache headers and opens the page in Google Chrome.
Extends Python's http.server.SimpleHTTPRequestHandler to send no-cache headers on all responses, preventing stale browser caching during local development.
Ensures developers always test the latest code modifications without aggressive browser caching issues.
check_docs.py : Documentation Truth Auditor
SYNOPSIS: python3 tools/check_docs.py [--template]
Scans documentation for broken links, duplicate decisions, invalid roadmap checkboxes, and unfulfilled placeholders.
Uses regular expressions to validate relative paths, decision references (D-NNN), roadmap IDs (P#-##), and handoff session logs across all documentation files.
Maintains absolute consistency between codebase changes and documentation records across development sessions.
check_structure.py : Wiring & Lint Auditor
SYNOPSIS: python3 tests/check_structure.py
Audits index.html and main.js to confirm that all DOM element references match and sanitization rules are respected.
Extracts all IDs from index.html and verifies that every document.getElementById() call targets a valid, uniquely defined ID. Rejects un-sanitized innerHTML assignments and unpinned CDN scripts.
Catches missing elements, typos, and security regressions before code reaches staging or production.
Playwright Smoke Suite : Dual-Browser E2E Harness
SYNOPSIS: cd tests/e2e && npm test
Runs 34 automated smoke tests in headless Chromium and Firefox, validating all key user flows offline.
Uses Playwright to boot the app with local SRI-pinned libraries, mock model servers, test XSS sanitization, verify storage quota handling, and exercise concurrent request guards.
Provides conclusive, observed proof of feature correctness and security enforcement across multiple browser engines.