Skip to content

Architecture

DuckTapeKiller edited this page Sep 13, 2026 · 1 revision

This page is a map of how Dive is built. It is written for developers, and for AI agents that need to find their way around the code before they change it. File names link to the repository, and the docs folder goes deeper into each area.

The three parts

Electron main process        electron/main.js
  starts the server, then opens a window at http://127.0.0.1:<port>
          |
          v
Node HTTP server             server.js, routes/, skills/, library/
  serves the interface, stores conversations and settings,
  talks to the model backends and runs tools
          |  HTTP requests, NDJSON streams, Server-Sent Events
          v
Renderer                     index.html and assets/js/00-modes.js to 08-browser.js
  classic scripts sharing one global scope, no bundler

Because the server is an ordinary local web server, the same interface also works in a web browser pointed at its address. Everything Dive keeps lives in one data folder, ~/dive by default, defined once in data-dir.js and overridden with the DIVE_DATA_DIR environment variable.

Starting up

electron/main.js takes a single-instance lock, so opening Dive twice focuses the existing window. Then bootLocalServer() runs:

  1. readConfiguredServerPort() reads serverPort from ~/dive/pi-settings.json, and falls back to 8080 when the value is missing or outside 1024 to 65535.
  2. syncRuntimeFiles() copies the server code from the app bundle into runtime/ inside Electron's user data folder (~/Library/Application Support/dive-desktop/runtime on macOS), overwriting the previous copy on every launch.
  3. On macOS, installOrRefreshLaunchAgent() writes ~/Library/LaunchAgents/com.dive.server.plist and restarts it with launchctl. The agent runs runtime/server.js with the node binary from PI_CHAT_NODE_PATH or the PATH, with RunAtLoad and KeepAlive, so the server outlives the window. If no node is found, no agent is written. On Windows and Linux, startLocalServerProcess() runs runtime/server.js with the app's own executable and ELECTRON_RUN_AS_NODE=1. The window's window-all-closed and before-quit handlers stop that process.
  4. waitForServer() polls GET /api/models for up to 6 seconds on macOS and 15 seconds elsewhere. If nothing answers, the main process requires server.js and runs the server in its own process.
  5. createMainWindow() loads http://127.0.0.1:<port>.

Two consequences are worth remembering. An installed app runs the copy in runtime/, so editing the repository changes nothing until you build and install again. And on macOS the LaunchAgent keeps serving after the window closes.

The server

server.js creates a Node http server and listens on 127.0.0.1 only (PORT from the environment, default 8080). Before it routes a request it:

  • refuses it with 403 unless the Host header is 127.0.0.1:<port> or localhost:<port>, and any Origin header matches too (isRequestAllowed());
  • sets X-Content-Type-Options: nosniff, X-Frame-Options: DENY and a Content-Security-Policy with a fresh nonce, which it writes into the <script> tags of index.html as it serves it.

There is no login. Binding to loopback is the protection, so the port must never be exposed to a network.

Route modules

Most endpoints live in domain modules under routes/. Each exports a factory that server.js calls with the dependencies the module needs, which keeps the modules testable without a running server.

Module Handles
routes/chat.js Chat for Ollama (/api/chat/stream, /api/chat), llama.cpp and LM Studio (/api/llamacpp/stream, /api/lmstudio/stream) and Cloud (/api/cloud/chat/stream), including the tool loop
routes/pi.js The pi integration: /api/pi/stream, /api/pi/events and the session, command and settings endpoints
routes/skills.js Tool and skill settings: /api/ollama/skills/settings, /api/custom-skills, /api/plugins, /api/agent-skills, /api/mcp/config, /api/book-search/config
routes/conversations.js The conversation history endpoints; the storage itself stays in server.js
routes/settings.js Interface, Cloud, Ollama and local-model settings
routes/library.js The library index job and /api/library/*
routes/llamacpp.js The managed llama-server: downloads from Hugging Face, loading, unloading
routes/browser.js What the agent browser panel shows
routes/notes.js, routes/prompts.js Notes and saved prompts

server.js itself handles uploads (/api/upload), the app-wide event channel (/api/events/global), /api/version, /api/health/logs and /api/security-event, and it owns conversation storage.

Streams and events

Chat replies stream as NDJSON: one JSON object per line. The event types include delta, thinking_start, thinking_delta, thinking_end, tool_start, tool_end, library_results, library_error, web_sources, attachment_notice, error and done.

Two long-lived channels use Server-Sent Events instead:

  • /api/events/global tells every open window about changes, through broadcastAppEvent(). Events include conversation_saved, conversation_deleted, llamacpp_models_changed and llamacpp_selection_changed. This is how a conversation saved in one window refreshes in another.
  • /api/pi/events lets the interface reattach to a pi run it wasn't watching, after a reload or a mode switch.

Modes

assets/js/00-modes.js is the single list of modes. The browser loads it as a script and the server requires it, so both sides agree. Each entry carries:

Field Meaning
enabledByDefault Shown in the switcher on first launch: true for llama.cpp, Pi and Cloud
diveSkills Dive supplies the tool loop, tools, skills, MCP, system prompts and lessons. False only for Pi
localEndpoint An OpenAI-compatible local server served by /api/<mode>/stream and handleLocalModeStream(): llama.cpp and LM Studio

It exports MODES in canonical order, which storage depends on, and MODE_DEFS in display order, plus MODE_IDS, DIVE_SKILL_MODE_IDS and LOCAL_MODE_IDS. On the server, requireNonPiMode() in mode-state.js keeps the tool, skill and MCP routes away from Pi.

How a message travels

  1. sendMessage() in assets/js/07-chat.js reads the message box and the active mode.
  2. The renderer posts to the mode's endpoint: /api/chat/stream for Ollama, /api/<mode>/stream for llama.cpp and LM Studio, /api/cloud/chat/stream for Cloud, or /api/pi/stream for Pi. The request carries the history and a saveConv conversation id.
  3. For the four Dive modes, createSkillContext() in routes/chat.js takes a snapshot of the mode's tool switches, custom tools, enabled external tools and their commands, enabled Agent Skills, and a lease on the mode's MCP session. The lease is released when the response finishes or closes.
  4. The server assembles the messages: the system prompt, the mode's lessons, library passages when Database Context is on, and the instructions for tools and skills.
  5. The server streams from the backend. When the model calls a tool, executeToolCallWithConfirmation() runs it (see Tools and skills), the stream carries tool_start and tool_end, the result goes back to the model, and the loop continues. It stops when the model answers or the tool budget runs out: 6 rounds for llama.cpp, LM Studio and Cloud, 10 for Ollama, or with Agent Mode on, 25 by default and anything from 1 to 50.
  6. The finished conversation is saved under ~/dive/conversations/, and /api/events/global announces conversation_saved.

Pi mode

Pi is a separate agent, so Dive is only a client. routes/pi.js starts one pi --mode rpc process per conversation and speaks JSONL with it over stdin and stdout. It also passes --extension routes/pi-rpc-ui-compat.js, an adapter that lets pi's permission screen work over RPC, so Dive can show those prompts as dialogs. RPC records over 4 MB are rejected. Each conversation's event channel keeps a replay buffer of up to 256 events or 4 MB.

Dive looks for the pi command at /opt/homebrew/bin/pi, then /usr/local/bin/pi, then on the PATH (pi.cmd, pi.exe or pi on Windows), unless a command path is set in Pi's settings.

Tools and skills in the code

File Role
skills.js ALL_SKILLS, the 29 native tool definitions; executeSkill(), the dispatcher; GATED_BUILTIN_SKILLS, the tools that need confirmation; the custom tool runner
skills/ Native tool implementations
plugins.js Loads and validates external tools from ~/dive/plugins, and runs them with a timeout: 60 seconds by default, between 1 second and 60 minutes
agent-skills.js Scans skill folders, builds the skill list for the prompt, runs activate_skill and expands /skill:name
mcp.js MCP clients per mode, session leases, and the allowlist of launch commands
slash_commands.js The slash command table and buildForcedSkillToolCall()
mode-state.js Reads and writes skills_config-<mode>.json and custom_skills-<mode>.json
routes/chat.js createSkillContext(), getLocalNativeTools(), getCloudSkillsPolicyPrompt(), executeToolCallWithConfirmation()

Many of these names still say "skill" where they mean a tool. Tools and skills explains why they stay.

The library

library/store.js keeps the index in ~/dive/library.sqlite. It works through a bundled sqlite3 command-line tool and the bundled sqlite-vec extension for vector search, with SQLITE3_PATH as an override and a Homebrew install as a fallback. The indexer reads EPUB, TXT and Markdown sources and never changes them. routes/library.js runs index jobs, and the server resumes an interrupted job when it starts.

The agent browser

skills/browser.js drives Chromium through Playwright for the browse_read and browse_act tools. routes/browser.js and assets/js/08-browser.js show the page live in a panel, so you can watch what the model does and take over.

The renderer

index.html loads nine classic scripts from assets/js/ in numeric order. They share one global scope: there is no bundler and no import, so a top-level function in one file is visible to all the others.

File Holds
00-modes.js The mode registry, shared with the server
01-core.js Shared state and helpers, the native tool descriptions shown in Settings (ALL_BUILTIN_SKILLS_INFO) and the default system prompt text
02-notes.js The notes panel, the app's dialogs (appAlert, appConfirm), apiUrl and the enabled-modes settings
03-theme.js Palettes and theme, Ollama options, database settings, setMode() and renderMode(), and the stream readers for each mode
04-local-models.js llama.cpp and LM Studio settings and the llama.cpp model manager
05-history.js The history and side panels, message rendering, attachments, export to Markdown, and the tool and skill lists in Settings
06-pi.js pi commands, the pi model picker, the pi event channel client and the book search settings
07-chat.js sendMessage(), the queue and Stop, the settings tabs (organizeSettingsTabs()), MCP settings and panel resizing
08-browser.js The agent browser panel

ESLint checks one file at a time, so it can't see calls between these files. scripts/lint-frontend.js concatenates them in load order and lints the result as one program.

Tests and checks

Command What it runs
npm test node --test test/*.test.js: 503 tests in 44 files at 5.0.8
npm run lint ESLint, then the whole-program frontend lint
npm run format:check Prettier

test/dom.test.js loads index.html and the scripts in jsdom, and treats any console error as a failure. Tests that start a server set DIVE_DATA_DIR so they never touch real data.

A husky pre-commit hook runs lint-staged (Prettier and eslint --fix on staged files) and then the frontend lint. GitHub Actions runs lint, the format check and the tests on Ubuntu with Node 20 for every push to main and every pull request. Pushing a version tag builds the desktop releases.

Where to start for common changes

To change Start in
A native tool skills.js for the definition, skills/ for the code, ALL_BUILTIN_SKILLS_INFO in assets/js/01-core.js for the Settings description
How tools are offered or run routes/chat.js
Slash commands slash_commands.js
Agent Skills agent-skills.js
A mode assets/js/00-modes.js, then routes/chat.js or routes/pi.js
A settings section Its group in index.html, organizeSettingsTabs() in 07-chat.js for the tab, modeVisibilityRules() in 03-theme.js for which modes show it
Startup electron/main.js
A new top-level server file Add it to build.files and build.asarUnpack in package.json and to syncRuntimeFiles() in electron/main.js. test/packaging.test.js fails otherwise

Read next

Clone this wiki locally