Skip to content

Architecture

nodemode-ai edited this page Dec 6, 2026 · 7 revisions

Architecture

frontend/  vanilla TypeScript and Vite: engine/ (model, ops, document client, session, reactions-api, names-api, nmr-api, spectra-api,
           three-api, stale, database-api), chem/ (valence, rings, formula, stoich, spectrum-ops, elements3d, geom3d, conformer-mol), canvas/ (view, hit
           testing, tools, spectrum-links, render/ with one module per object kind, spectrum and its data cache and model3d included),
           app/ (menus, shell, canvas, object and reaction commands, documents, window tools, agent-window, agent-calls, agent-activity,
           name, nmr, spectrum, 3D, database, live structure, HELM and xtb commands), canvas/a11y/ (keyboard focus, spoken atoms
           and bonds, palettes), ui/ (shell, menus, Home, Preferences, tool rail, Analysis and Stoichiometry panels, Structure
           Library, file changed bar, announcer, Structure Summary, HELM and xtb dialogs,
           template library, Agent activity panel, agent chip, name dialog, Spectrum editor, 3D View panel with its viewer, lazy 3Dmol.js
           loader and dialogs, database/ (the database workspace, table, gallery, form and dialogs), database-find/ (search, query
           builder, hit lists, saved queries, import, export, plot), notebook/ (the notebook view and entry editor)), io/ (glb), dock/,
           extensions/, styles/
backend/   FastAPI engine: core/ (config, guard, window key, seal, agent token), routers/ (system, live, library, commands, documents, chem, reactions,
           templates, terminal, chat, extensions, mcp, agent_activity, names, nmr, spectra, three_d, databases, db_search, notebook,
           structures, describe, helm, xtb), services/ (model, ops, store, history, package, importers, templates, agent_out, agent_draw,
           agent_edits, agent_convert, agent_log, agent_db, agent_notebook, agent_library, agent_helm, agent_xtb, live_structures,
           file_watch, describe, helm/ (HELM reader, writer, monomers), xtb/ (finding and running xtb and CREST), chem/ on RDKit and Indigo, names/ (the name engines), nmr/ (the increment predictor),
           spectra/ (the JCAMP-DX reader and spectrum service), three_d/ (3D building, conformers, force fields, scans, PDB and mmCIF
           readers, ligands, the stale-conformer rule), database/ (the .fcdb store, registration, fields, import, export, search, hit
           lists, the command line), notebook/ (entries, the content hash, schemes, export), demos (the demo catalogue and previews)),
           data/templates/, data/names/, data/helm_monomers.json, data/demos/ (all of data/ ships in the frozen engine at app/data)
src-tauri/ the desktop shell; the frozen engine runs from a folder inside the app on macOS and as a sidecar elsewhere; the deep link
           plugin registers formai://; linux/ (desktop entry, MIME package), windows/ (installer hook), icons/documents/
demos/     offline browser demos (drawing, reactions, 3d) built from the window's code with an offline stand-in for the engine

The engine owns the document

The engine holds every open document in its store (backend/app/services/store.py): the document itself, its revision, its file path, whether it has unsaved changes, and its undo and redo stacks. The document model follows docs/FORMAT.md, implemented twice and kept in step: frontend/src/engine/model.ts and backend/app/services/model.py. The window keeps a mirror of each open document and never owns the chemistry.

The document flow

  1. A gesture becomes a transaction. While the person drags, the tool shows a local preview: ops applied to the window's mirror only, drawn by the renderer, never sent. When the gesture ends (or a command or hover key runs), the window commits one transaction {id, label, origin, ops, inverse} of set, ins, del and move ops on JSON paths. One gesture, one command or one agent call is one transaction and one undo step.
  2. The window applies it at once. EngineDocumentClient.commit validates and applies the ops to the mirror, marks the transaction pending and sends it on the live socket (or over HTTP when the socket is down). The person sees the change in the same frame.
  3. The engine applies it for good. The store normalises the ops, applies them, validates the result (rolling the whole transaction back on any failure), raises the revision, records the inverse for undo, merges a stream of small edits that share a coalescing key, and schedules autosave and version snapshots (history.py).
  4. Everyone hears about it. The engine broadcasts the transaction with the new revision to every window and agent. The sending window drops it from its pending list; other windows apply it to their mirror. After a dropped connection a window resyncs from a snapshot and resends what was still pending.
  5. The derived cache follows. After each transaction the engine derives the chemistry of the changed fragments in a worker thread with RDKit (services/chem/derive.py, cached per fragment): canonical SMILES and CXSMILES, InChI and InChIKey, formula, masses, elemental analysis, implicit hydrogens, valence errors and warnings, plus the balance check of every reaction step. It broadcasts the result keyed by fragment id and revision. It is never saved: it is rebuilt whenever a drawing opens.
  6. The renderer patches. The canvas (canvas/render/) draws in SVG keyed by object, atom and bond id; every object kind (arrows, symbols, brackets, shapes, lines, tables, TLC plates, orbitals, images, captions, groups) goes through one registry, and a change of stacking order moves only the nodes out of place. Ops share structure, so the renderer compares records by reference, re-lays out only the changed atoms and their neighbours, and patches the attributes of the nodes whose drawing changed; it never rebuilds the canvas. Until the derived cache for the current revision arrives, it draws implicit hydrogens and double-bond sides from the window's own tables (frontend/src/chem/); then it adopts the engine's values. Hit testing works on the model geometry, not on DOM nodes.

Undo and redo are engine operations: the engine applies the recorded inverse as a new transaction with origin history and broadcasts it like any other.

The live channel

Windows and agents talk to the engine over a WebSocket hub. It carries the connection and the engine's state, document transactions and derived caches, the window's command catalogue, the tool calls an agent makes through the engine (run_command, the extension tools), consent questions and answers, and handoff notes. Agents reach drawings through the MCP server: get_context reads the store's open documents, and run_command runs the window's commands, whose changes travel the same flow as the person's.

Agents draw through the engine

From 0.8.0 the drawing and edit tools build ops in the engine (services/agent_draw.py lays SMILES, molfiles and reaction SMILES out and finds free space; services/agent_edits.py holds each edit tool as a pure function from the document and the arguments to ops) and apply them with STORE.apply as one transaction with origin agent and the agent's name. From there the change travels the document flow above: broadcast to every window, which patches its mirror and its SVG, then derived. So an agent's call is one undo step in the window, and it works with no window open.

Every write answers with agent_out.write_result: the touched structures read back from the derived cache after the transaction, and a picture. Pictures go through the bridge. The engine sends the document and its derived cache to the window as the window tool render (bridge.window_call over the live channel); the window cuts out the objects asked for and draws them with the same off-screen renderer as File > Export (app/agent-window.ts, app/picture.ts), in the person's display preferences, and rasterises the PNG itself without waiting on animation frames, so a background window still answers. With no window, a window error or no answer in 25 seconds, the engine draws the structures in the journal style with RDKit (services/chem/depict.py) and says so. The window tools selection (the person's selection) and show (open and activate a drawing the engine made for an agent) travel the same way. render and selection are read-only window tools, so a window without the drawing does not hold the call.

The agent call log

Every tool call passes through call_tool in routers/mcp.py, which logs it in services/agent_log.py before and after it runs. A context variable set for the call flows through STORE.apply into the store's after-change hooks (store.AFTER_CHANGE), so each transaction is credited to the call that made it; a window command's transaction, which the window posts itself, is credited to the one writing window-tool call that is running or ended less than 1.5 seconds ago. After every change, undo and redo the hook checks which call owns the top of that drawing's undo stack and tells the windows (agentUndoable), so Agent Activity offers Undo on exactly that call. The log is mirrored live to every window (agentCall), kept in memory and appended to files in the data folder, and served under /api/agents (Agent Activity). A stopped agent is refused in call_tool before any tool runs.

Names, predictions and spectra

From 0.9.0 three engine services sit beside the chemistry core, each behind a registry so a later engine can take its place without touching the routes, the window or the agent tools.

  • Names (services/names/, routes under /api/names): a registry of name engines that all meet one protocol. The only one at 0.9.0 is FormChem's offline engine: a dictionary of 629 common names, then a systematic parser and builder, and a namer whose names are shown only when they parse back to the same InChIKey. OPSIN or an online lookup would be registered in front of it (docs/NAMES.md).
  • NMR prediction (services/nmr/, routes under /api/nmr): a chain of predictors where the first answer for each atom wins, at 0.9.0 FormChem's own increments for 1H and 13C. A predicted spectrum is a document object that stores its settings and its links to atoms, never its points.
  • Spectra (services/spectra/, routes under /api/documents/{doc}/spectra): the JCAMP-DX reader, decimation, peaks, integrals and export. A measured spectrum's file lives in the drawing as media; a predicted one is answered by the predictor registered for its method (spectra.source.PREDICTORS), so the data, peaks, integrals and export routes serve both the same way.

The window never holds spectrum points in the document: its spectrum kind asks the data route for about as many points as the plot has pixels at the current zoom, keeps them in a cache keyed by range and zoom bucket, and patches only the trace path when finer data arrives. Peak picking and integration run in the engine and come back as transactions; links, the view range and the y mode are ordinary window transactions. Atom and peak highlights live in their own overlay layer, so they never reach an export.

3D

From 0.10.0 the engine's services/three_d/ (routes under /api/documents/{id}/3d and /api/3d/parse) builds and keeps 3D structures, with RDKit's ETKDGv3, MMFF94, MMFF94s, UFF and Gasteiger code. (docs/3D.md)

  • Conformers live in the fragment. A structure's conformers hold 3D coordinates for every atom (hydrogens under h, the extra atoms of an abbreviation under expanded), each with its energy and method; conformer names the shown one. A build, a conformer search, a minimisation or a stored scan computes in a worker thread on a snapshot of the drawing, checks that the structure has not changed meanwhile, and applies one transaction, which travels the document flow like any other.
  • Stale conformers drop in the same transaction. Inside Store.apply_now, three_d/stale.py compares each touched fragment's graph before and after; when the atoms or bonds changed (not just positions or display), it appends unsets of conformers and conformer to the transaction, so undo brings them back with the old graph. The window's client runs the same rule (engine/stale.ts) on its own transactions before sending them, and on the engine's echo it applies a trailing conformer drop it did not send, so both sides agree at once.
  • Structure files stay as files. A PDB or mmCIF file read by FormChem's own readers becomes a model3d object over the bytes kept as media, so saving, exporting and pasting carry the original file. 3D SD and MOL records become structures whose file coordinates are their conformer.
  • The window shows, the engine computes. The 3D View panel loads 3Dmol.js on first use (its own chunk, so startup is unaffected), reads a structure as a molfile with an atom map from the engine (or writes one locally from the stored conformer), and measures in the window with the engine's formulas. A model3d on the page is drawn as a PNG snapshot of the view; the panel writes a new snapshot, the camera and the style in one coalesced transaction after the person changes the view, and the renderer keeps the old picture until the new one has loaded, so the page never flashes. Exports and print use the snapshot and need no 3D renderer.

Databases and the notebook

From 0.11.0 the engine's services/database/ and services/notebook/ (routes under /api/databases) keep structure databases and lab notebook entries. They live beside the document store, not in it: a database is not a drawing, has no undo stack and is not sent as transactions. (docs/DATABASE.md, docs/DATABASES.md)

  • One file, one connection, one lock. Each open .fcdb is a handle (g and eight characters) with one SQLite connection and a lock; every write is one BEGIN IMMEDIATE ... COMMIT and one audit row, and reads take the same lock. A lock file beside the database makes a second FormChem or the command line open it read-only.
  • Chemistry enters through one function. database/chem.py register_values computes the keys, formula, masses and both fingerprints of every stored structure and of every exact query, so they always agree.
  • Search screens in memory. database/search.py keeps each database's fingerprints as numpy arrays, refreshed only when the record count, the newest id or the newest audit row moves; substructure hits are screened there and confirmed by an RDKit SubstructLibrary, similarity is computed for every row at once, and every query term is a mask. Every search is stored as a hit list.
  • Long work runs as jobs. Imports and large exports run on worker threads in batches of 250 records, each its own transaction, with a report of failed records the window polls.
  • Everyone hears about it, after the commit. Each write broadcasts {t: "database", db, change, uids?} on the live channel once committed. The window's workspace refetches only the rows or lists the message names; rows are paged in blocks of 100, pooled and keyed by uid, so a 10,000 record table never rebuilds.
  • The notebook reuses the chemistry. An entry's scheme is a one-page FormChem document; its stoichiometry is computed on every read by the reaction services, and its content hash covers the scheme, text, products, tags and file hashes, so signing can tell when it changed.
  • Pictures have their own key. Database reads need the window key; thumbnails and attachments, loaded by image and link tags, take a second view key that opens only those two routes.

Family integration

From 0.12.0 FormChem shares structures with the other Form apps and runs outside programs, without changing the document flow. (docs/LIVE_STRUCTURES.md, docs/HELM.md, docs/3D.md)

  • The library is plain files. services/live_structures.py writes Library/library.json and an SVG, PNG and molfile per item, each through a temporary file and a rename, the index last, so sibling apps read it without FormChem running.
  • A live drawing is an ordinary drawing with a link. Opening an item makes a normal session from the drawing inside its SVG and keeps {id, rev, from} beside it in memory; Save rewrites the item and raises its revision instead of writing a .fchem, and the engine broadcasts live-structure. Nothing is written into the drawing, so Save As copies are ordinary.
  • Three ways in. The window's commands, ./formchem edit-live (which posts with the agent token, the one thing that token may write outside /mcp) and the formai://formchem/edit deep link, which the desktop shell receives through tauri-plugin-deep-link and the main window alone handles.
  • The file watch polls. Once a second the engine compares the size and time of each open drawing's file and broadcasts file-changed when another program moved it; FormChem's own saves are recognised by the modified time inside the file.
  • Accessibility sits in front of the canvas. The keyboard route in canvas/a11y/ is installed before the canvas's own key handler, moves the view's keyboard cursor, and speaks through one shared live region; POST /api/describe gives the summary with the method of each part.
  • HELM becomes atoms. services/helm/ reads HELM against FormChem's own monomer data and joins monomers into one RDKit molecule, which enters the drawing as an ordinary fragment through the template placement path, one transaction.
  • xtb and CREST run outside. services/xtb/ finds the programs the person installed, runs one job at a time as a separate process in its own folder, and writes the result back as one 3D transaction with the stale-conformer check, as the 0.10.0 3D routes do.

Desktop and demos

From 0.13.0 the desktop shell hands files from the system to the window, and the engine ships its demo drawings. (Desktop)

  • Files from the system take the Open path. src-tauri/src/main.rs turns launch arguments, macOS open events and second launches into absolute paths and passes them to the window as ?open= parameters or window.__formchemOpen; frontend/src/app/system-open.ts opens them one at a time through the same function as Open Recent, so an .fcdb reaches the database workspace and every other file becomes a drawing in the engine's store.
  • Engine data is read relative to the services folder. Each service finds its data from its own file's location (Path(__file__).resolve().parents[...] / "data"), and the frozen engine carries backend/app/data at app/data, so the same lookup works from source and in the app.
  • Demos are copies. services/demos.py lists data/demos/demos.json, validates each drawing, draws a small SVG preview itself (the engine has no renderer of its own for documents) and opens a demo as a new document with a fresh id and no path, so the shipped file is never written. Home's Demos section (ui/home-demos.ts) fills reserved cards from GET /api/demos.
  • Browser demos stand alone. demos/ builds the window's canvas, tools and panels with Vite shims: io/api.ts becomes an offline stand-in and documents live in memory with the window's own op code, so each page opens from file:// with no engine.

Guarding the engine

The engine binds to 127.0.0.1. A local guard refuses requests whose Host or Origin is not local, and a window key made at each start lets only the FormChem window change settings, use the terminal dock or answer an agent's question. Saved agent choices are sealed with a key in the system keychain. From 0.8.0 the MCP endpoint also needs the agent token (core/agent_token.py, the file agent-token in the data folder), which the stdio relay and the agent configs send.

The window

Vanilla TypeScript, no UI framework. Every colour, space and z-index comes from frontend/src/styles/tokens.css; icons are inline currentColor SVG in frontend/src/ui/icons.ts. The theme is set before first paint, panels are built once and patched, and anything floating renders into #overlay-root.

Chemistry core

RDKit (structure model, canonical SMILES, InChI, stereo, coordinates) and Indigo (chemical drawing formats) are pinned in backend/requirements.txt. The engine's chemistry service (backend/app/services/chem/, routes under /api/chem) is the authority for sanitising, valence, aromaticity, identifiers, formula and masses, 2D clean-up and layout, and reading SMILES, molfile, SDF, RXN, CML and CDXML. The window only computes what it must draw at once without the engine.

From 0.5.0 the same service reads reactions: perception of roles around the arrows, atom mapping with Indigo, balance, stoichiometry, and reaction SMILES and RXN exchange, under /api/documents/{id}/reactions (docs/REACTIONS.md). Each changing reaction route applies one transaction through the store and broadcasts it like any other. The window computes stoichiometry itself for the panel and the drawn grid with the same rules (frontend/src/chem/stoich.ts). The template library (/api/templates) is data in backend/app/data/templates built once and cached, and pictures enter a drawing through /api/documents/{id}/media.

Clone this wiki locally