diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ddbc4f2..2ea6a7a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,8 +2,9 @@ name: ci on: push: - branches: [main] + branches: [main, "compile_v*"] pull_request: + workflow_dispatch: permissions: contents: read diff --git a/.gitignore b/.gitignore index 18e3fe2..35200f2 100644 --- a/.gitignore +++ b/.gitignore @@ -10,5 +10,6 @@ .DS_Store /src-tauri/target/ /src-tauri/gen/ +/src-tauri/permissions/autogenerated/ /src-tauri/binaries/* !/src-tauri/binaries/.gitkeep diff --git a/BRANCHING.md b/BRANCHING.md index 1c75f71..a6fe7af 100644 --- a/BRANCHING.md +++ b/BRANCHING.md @@ -45,8 +45,11 @@ This repository has no release workflow and builds no release artifacts: packagi 1. On a `chore/release-vX.Y.Z` branch, bump the version everywhere it is written: - `VERSION := vX.Y.Z` in `Makefile` - `"version"` in `web/package.json` and `web/package-lock.json` - - `"version"` in `src-tauri/tauri.conf.json` - - the "latest release" row of the supported-versions table in `SECURITY.md` + - `"version"` in `src-tauri/tauri.conf.json`, `version` in `src-tauri/Cargo.toml` and the `formledger-desktop` entry of `src-tauri/Cargo.lock` + - `Version` in `internal/app/version.go` + - the version badge in `README.md` + + The supported-versions table in `SECURITY.md` says "Latest release" and needs no change. 2. Commit it as `chore(release): vX.Y.Z (x.y.z)` and merge it into `main` through a pull request. 3. A maintainer hands the new `main` to FormCompiler, which builds and publishes the release. diff --git a/CHANGELOG.md b/CHANGELOG.md index 12d5c51..0101796 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,43 @@ # Changelog +## 0.15.0 + +FormLedger gets the family's menu bar, a Home start screen, Preferences and the agent dock, and takes on the family look. + +### New +- **A menu bar in the window on Windows and Linux:** FormLedger, File, Edit, View, Go, Window and Help, made from the same list as the commands in the command palette. Alt or F10 opens it; the arrow keys, Home, End and the first letter of an item move through it. A menu opens under the bar and is never taller than three quarters of the window; a long one scrolls and shows a small hint at its foot while more rows lie below. +- **macOS: the system menu,** made from the same list, with Preferences under FormLedger. View > Menus in Window puts the bar in the window instead, from the next start. +- **Home** is a start screen: the FormLedger mark and name, a greeting, six cards for the first things to do (new sales invoice, new quote, new purchase invoice, record a payment, open the general ledger, start from a template), and under them the figures and last invoices that Home showed before. +- **Preferences** (Cmd or Ctrl plus comma, Edit > Preferences on Windows and Linux, FormLedger > Preferences on macOS, or the Preferences button on Home): theme Dark, Light or Match the system, six accent colours, the agent dock switch and the app lock. Theme and accent are in place from the first frame, so the window does not flash. +- **Agent dock** (View > Agent Dock, or Cmd or Ctrl plus J): a terminal panel beside the books with a shell tab and tabs for Claude Code, Codex and Cursor. A program that is not installed shows its install line. Only the owner of the books can open it, and only from this computer. +- **Three demo companies** in `demos/`: Larkspur Lane Cafe, Halftone Field Design Studio and Ironbark Hardware and Supply. Each is a data folder with three months of posted selling, buying, stock and payments. Copy one, start FormLedger with `FORMLEDGER_DATA` set to the copy, and sign in with the email in its `about.json` and the password `formledger-demo`. Every company, person and address in them is invented. +- **48 document templates** in `templates/` for the Templates screen: 20 sales invoices by trade, 8 quotes, 5 sales orders, 6 purchase orders and 9 supplier bills. Each file is posted to `/api/templates` as it is; Use opens a new draft from it. + +### Improved +- The window follows the family's colour, spacing and type names, with a light theme built on them, glass on the menus and the command palette, and one stacking order for menus, palette, dock, dialogs and notices. Debit, credit and chart colours are as they were. +- The Agent Dock menu row shows its key (Cmd or Ctrl plus J) and the command palette shows keys for the dock and for Preferences. + +### Fixed +- **With the agent dock open,** the links in the sidebar could sit under Reports, Setup and Templates and the user chip, and the list could not scroll. The list now scrolls above them. +- **A line with no item** showed only the first word or two of its description in the line grid. It now shows its text, and the full text is its hover title. +- **A sales or purchase document in a narrow window** cut the year off its date fields and wrapped the buttons along its foot onto a second row. The dates now show whole and the buttons stay on one row down to a window 1000 pixels wide, with their names as hover titles where only an icon fits. The line under the title now ends before the buttons, and the Description column of the lines no longer shrinks to a single letter. + +### Changed +- Windows and Linux: the menu bar is drawn by the window. Before, the system drew the native menu as a bar of its own above it. +- The Settings menu item is called Preferences. + +### Known issues +- macOS: the system menu and Menus in Window were not run on a Mac. +- Windows: the dock's tabs cannot open a terminal yet; the dock says so. +- Home has no Open or recent ledgers, because FormLedger keeps one company in its data folder and has no import. +- Preferences does not show the company settings (the instance name, negative stock, the goods received account and the purchases account); the server has no route for them yet. +- Still open from 0.14.0: a desktop ledger with no chart of accounts does not point you to Setup from Home; an empty ledger shows 0.00 with no currency code; the account shown on a line with no item is 5100 or 4100 even if the setting names another; reading the snapshot from FormCel's window was not checked. + +### Under the hood +- Build: `build_app` takes `--config`, as FormCompiler passes it; the Tauri command line is a pinned dev dependency of `web` (2.12.5); CI also runs on `compile_v*` branches. New dependencies are `@xterm/xterm` 6.0.0, `@xterm/addon-fit` 0.11.0, `@tauri-apps/api` 2.12.5 and `github.com/creack/pty` 1.1.24, each with a row in `NOTICE.md`. +- Checked: gofmt, `go build`, `go vet`, `tsc --noEmit` and `npm run build` pass, and the server answers `/api/health`. There are no Go or window tests in the repository. The Linux desktop build was run on the release tree, before the last window fixes (the sidebar, the free line and the key hints, which change window styles and a few lines of window code, not the Rust, the build scripts or the server): it made `FormLedger_0.15.0_amd64.deb` (10.17 MiB, package version 0.15.0) and `FormLedger_0.15.0_amd64.AppImage` (84.50 MiB). Under a virtual display the AppImage started, and its server answered `/api/health` with v0.15.0. A demo (Larkspur Lane Cafe) was served by the built binary and opened in headless Chrome with the content security policy enforced, with no violations. The window itself was not photographed, so it is not verified. In headless Chrome with the CPU slowed four times, the menus stayed under the bar and under three quarters of the window at four window sizes, Home and Preferences drew with the final theme and accent on the first frame with no layout shift, and the dock opened and closed in one step. The dock's terminal was run against the server's own content security policy with no violations. The sales and purchase forms were looked at under the same slowdown at 1000, 1200, 1440 and 1871 pixels, dark and light, and the sidebar with the dock open was looked at at 1280 by 720, 1000 by 480 and 1440 by 900, with the dock at the bottom and at the right. All 48 templates were loaded with an app token and each made a draft, and the three demo companies were opened on this branch's server and their Home shows their invoices. +- Not run: a Mac (the system menu, Menus in Window, the `.dmg`), Windows (the build, the installer, the in-window bar, the dock), the `.rpm`, a live terminal under the content security policy, the build after the last window fixes, and a look at the installed Linux window. The macOS Cmd+J accelerator was not run. + ## 0.14.0 Lists and reports get their column widths back, the first screen of the desktop app is filled in, and a line with no item posts to a named account. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index e2e5af0..ddc0889 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -26,7 +26,7 @@ for the project elsewhere. Report anything that breaks this code by opening an [issue](https://github.com/nodemode-dev/formledger/issues), or by reaching the maintainers on GitHub: the [nodemode-dev](https://github.com/nodemode-dev) -organization, [@nodemode-ai](https://github.com/nodemode-ai) and +organisation, [@nodemode-ai](https://github.com/nodemode-ai) and [@gbarnai](https://github.com/gbarnai). ## What happens next diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3cead65..74ccd8d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,8 +1,8 @@ # Contributing to FormLedger -Thank you for helping. FormLedger is a local-first business app. It is a scaffold for -now: a Go server and a web client that start, and a desktop shell around them. It grows -through real use and real contributions. +Thank you for helping. FormLedger aims to be a free, local-first set of books for a +small company, with sales, purchases, payments and stock in one ledger that stays on your +own computer, and it gets there through real use and real contributions. ## Where to start @@ -13,20 +13,22 @@ through real use and real contributions. ## Setting up -Clone the repository and run `./formledger_oc_install`, then `./formledger` (or -`formledger_oc_install.bat` and `formledger.bat` on Windows). The first downloads the -Go modules and installs the web client's packages; the second starts the server on -`127.0.0.1:8340` and the web client's dev server on port 5340. `./formledger --help` -lists the other commands. You need Go and Node 22. +Clone the repository and run `./formledger install`, then `./formledger boot` (or +`formledger_oc_install.bat` and `formledger.bat` on Windows). The first downloads the Go +modules and installs the web client's packages; the second starts the server on +`127.0.0.1:8340` and the web client's dev server on port 5340. `./formledger help` lists +every command, and the README's "Run it from source" section has the details and the +requirements. The code lives in: | Folder | What is there | | --- | --- | -| `cmd/formledger` | the server binary | -| `internal` | the server's packages (Go) | -| `web` | the client (TypeScript and Vite), embedded into the server when built | +| `cmd/formledger` | the server binary and the `cli` commands | +| `internal` | the engine (Go): ledger, selling, buying, stock, reports, printing, roles, audit | +| `web` | the window (TypeScript and Vite), embedded into the server when built | | `src-tauri` | the desktop shell (Rust, Tauri), which starts the server as a sidecar | +| `docs` | what each part does, and the behaviours the app commits to | | `.github` | the CI workflow and the code owners | ## Before you open a pull request @@ -39,13 +41,18 @@ go build ./... go vet ./... ``` -CI also starts the server and waits for `http://127.0.0.1:8340/api/health` to answer. -There are no automated tests yet. +`./formledger check` runs gofmt, go vet and the window's type check in one go. CI also +starts the server and waits for `http://127.0.0.1:8340/api/health` to answer. There are +no automated tests yet. - Keep each pull request to one change. -- Write commit subjects the way the history does: `feat(web): ...`, - `fix(server): ...`, `docs(...)`, with the scopes listed in [BRANCHING.md](BRANCHING.md). +- Write commit subjects the way the history does, in Conventional Commits: + `feat(web): ...`, `fix(server): ...`, `docs(...)` (see [BRANCHING.md](BRANCHING.md)). Leave the version alone; a maintainer bumps it when releasing. +- Keep emoji out of every file and em dashes out of Markdown. +- Every new dependency, binary or data file gets a row in `NOTICE.md` before it is used. +- Other vendors' product names appear only to name a file format or compatibility. + Never copy vendor help text, icons, templates or themes. ## Maintainers @@ -59,27 +66,32 @@ Reach them through issues and pull requests. ## How changes land -Work reaches `main` only through a pull request from a working branch; nobody pushes to `main` directly. Contributors without write access fork the repository and work on a branch there. A pull request merges when the `web` and `server` checks pass on an up-to-date branch and a maintainer has approved it after its last push. Pull requests are merged with a merge commit, never squashed and never rebased. +Nobody pushes to `main` directly. Everyone forks the repository, or branches from `main` with write access, and opens a pull request into `main`. A pull request merges when the `web` and `server` checks pass on an up-to-date branch and a maintainer has approved it after its last push. Pull requests are merged with a merge commit, never squashed and never rebased. ## Releases -Packaging and releases are done by FormCompiler (`nodemode-dev/formcompiler`), not in -this repository, and only a maintainer starts one. No push from a contributor starts a -release. See [BRANCHING.md](BRANCHING.md). +A release is a version, and only a maintainer makes one: after the version is bumped on +`main`, a maintainer hands it to formcompiler (`nodemode-dev/formcompiler`), which builds +every platform and publishes them together. Packaging is not done in this repository. No +push from a contributor starts a release. See [BRANCHING.md](BRANCHING.md). ## Licensing -FormLedger is licensed under the Apache License 2.0 ([LICENSE](LICENSE), SPDX -`Apache-2.0`). By contributing, you agree that your contribution is licensed under the -same terms. Only add code you have the right to contribute, and name any third-party -code and its license in the pull request. +FormLedger is licensed under the Apache License, Version 2.0 ([LICENSE](LICENSE), SPDX +`Apache-2.0`). By contributing, you agree that your contribution is licensed under +the same terms. Only add code you have the right to contribute, and name any +third-party code and its licence in the pull request. + +## Patents and other people's IP + +Some features are deliberately not built, or are taken out, because they come too close to someone else's patent, trademark, copyright or design. The maintainers hold that line with counsel; contributors do not decide it, and nobody here redesigns a feature on their own reading of a patent. This is engineering diligence, not legal advice. ### Rules for every contribution - Patents: do not add a feature, or a dependency that provides one, that reproduces a method you know to be patented. If you are unsure, open an issue that describes what the feature does, not which patent it resembles. Patent numbers stay out of code, commits, comments, logs and changelogs. -- Trademarks: other vendors' product and feature names appear only to name a file format or compatibility ("opens files", "for use with"). No command, menu, panel or tool takes another product's feature name, and no text says "like X" or "the way X does it". Describe what the feature does. -- Copyright: never copy another product's help, tooltip, dialog or documentation text (link to it instead); never trace or import vendor icons; never bundle vendor templates, themes, sample files, stock media or fonts. -- Licenses: every new dependency, binary or data file gets a row in `NOTICE.md` before it is used. GPL stays outside the distributed bundle, AGPL nowhere, LGPL dynamically linked and replaceable, MPL files unedited. CC BY credited, CC BY-SA only unmodified, CC NC and ND never. +- Trademarks: other vendors' product and feature names appear only to name a file format or compatibility ("opens files", "for use with"). No command, menu, panel, tool, template, theme or agent tool takes another product's feature name, and no text says "like X" or "the way X does it". Describe what the feature does. +- Copyright: never copy another product's help, tooltip, dialog or documentation text (link to it instead); never trace or import vendor icons; never bundle vendor templates, themes, presets, sample files, stock media or fonts. Compatibility layers carry names and signatures only. +- Licences: every new dependency, binary, font or data file gets a row in `NOTICE.md` before it is used. GPL stays outside the distributed bundle, AGPL nowhere, LGPL dynamically linked and replaceable, MPL files unedited. CC BY credited, CC BY-SA only unmodified, CC NC and ND never. ## Conduct diff --git a/Makefile b/Makefile index c18605c..978a750 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -VERSION := v0.14.0 +VERSION := v0.15.0 GO_BUILD := CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" .PHONY: build web server check clean diff --git a/NOTICE.md b/NOTICE.md index 415b1ef..420beba 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -9,6 +9,7 @@ A file brought over from another Form repository gets a row here with its source | Source | License | What came over | | --- | --- | --- | | form.md v0.61.1 (`nodemode-dev/form.md`) | Apache-2.0 | `cmd/formledger/main.go`, `embed.go` and `internal/` (`app`, `config`, `httpx`, `i18n`, `ids`, `netguard`, `nowindow`, `secrets`, `settings`, `store` with its migration runner and the instance and settings tables, `server`, `static`, `startup`), reduced to a skeleton and renamed, with the encryption hooks cut for now. Since 0.3.0 also `internal/auth` (password hashing nearly verbatim; the desktop entry, sessions, tokens and invitations cut down to one company and one role per person), `internal/policy` (the roles and actions are FormLedger's own), `internal/audit` and `internal/auditapi` (the workspace, page and agent parts, the purge and the export removed), `internal/crypt` and `internal/cryptvfs` (nearly verbatim, not switched on yet), and the users, sessions, tokens and invitations tables cut from form.md's accounts migration. `web/`: the engine store and commands, `ui/dom`, `ui/icons`, `ui/toast`, the theme tokens and shell styles, the Vite and TypeScript configuration, `oc_install` and `boot_frontend`. `src-tauri/`: the whole shell, renamed, with the menus reduced. The root launcher, installer, `build_app` and `Makefile`. `CODE_OF_CONDUCT.md`, `CONTRIBUTING.md`, `SECURITY.md`, `BRANCHING.md`, `.github/` and `.claude/settings.json`, rewritten for this repository. Since 0.10.0 also, from form.md at its `main` of 2026-11-27: the system-theme start in `web/index.html`; the sidebar head, user chip and menu, the top bar's back, forward and crumb, the sign-in card and the Home head (`web/src/styles/shell.css`, `auth.css`, `home.css`, `panels.css`, `pages.css`, `controls.css`, `web/src/ui/auth.ts`, `web/src/ui/icons.ts`, the tokens); the field, select and checkbox styles (`forms.css`, `settings.css`); the page head (`home.css`); the PDF page setup and page counter (`internal/transfer/pdf.go`); and the splash page's layout, which FormLedger shows with its own icon. Since 0.11.0 also, from the same `main`: the native menubar and its wiring (`src-tauri/src/menu.rs`, `main.rs`); the command palette (`web/src/ui/command-palette.ts`, the `.cpal`, scrim and dialog rules); the buttons (`forms.css`); the bar chart and the chart and dashboard card rules (`web/src/ui/bar-chart.ts`, `charts.css`); and encryption at rest, now switched on when a key is given (`internal/crypt/key.go`, `internal/cryptvfs/vfs.go`, `internal/store/store.go`, `internal/ops/encrypt.go`, the key options in `internal/config/config.go` and the `keygen` and `encrypt` commands) | +| FormVis 2.9.0 (`nodemode-dev/formvis`), the shared dock module 2.2.1 | Apache-2.0 | Since 0.15.0: `web/src/dock/` (written out by hand, byte for byte the module's TypeScript and `dock.css`), with FormLedger's own `web/src/dock-adapter.ts`, `web/src/styles/dock-tokens.css` and `web/src/styles/terminal.css`; `internal/dock/` is a Go rewrite of the terminal, agent program and status routes of FormVis's `backend/app/routers/terminal.py`, `services/terminal.py` and `services/agent_programs.py` | ## Third-party software @@ -25,5 +26,9 @@ Each component gets a row here with its license and its use before it is added. | vite 8.4.0 and what it pulls in (rolldown, postcss and others: MIT; lightningcss: MPL-2.0; picocolors: ISC; source-map-js: BSD-3-Clause), and @types/node | MIT | building the web client; not shipped | | Tauri 2 with the shell, dialog, opener and single-instance plugins | MIT OR Apache-2.0, per form.md's notices | desktop shell, which has not been compiled yet | | windows-sys, objc2, objc2-app-kit | the same crates form.md's shell uses; their licenses have not been read for this repository yet | desktop shell | +| @tauri-apps/api 2.12.5 | Apache-2.0 OR MIT, read from the package's `license` field | web client, loaded only inside the desktop app: the macOS menu bar, the zoom steps and the window buttons of the menus | +| @tauri-apps/cli 2.12.5 and its per-platform binary packages | Apache-2.0 OR MIT, read from the package's `license` field | building the desktop app (`build_app` runs it); not shipped | +| @xterm/xterm 6.0.0 and @xterm/addon-fit 0.11.0, the versions FormVis 2.9.0 ships | MIT, read from the packages' LICENSE: Copyright (c) 2017-2019 The xterm.js authors, (c) 2014-2016 SourceLair Private Company, (c) 2012-2013 Christopher Jeffrey | web client, the agent dock's terminal emulator, loaded when the first terminal tab opens | +| github.com/creack/pty v1.1.24 | MIT, read from the module's LICENSE: Copyright (c) 2011 Keith Rarick | server, the pseudo-terminals behind the agent dock (macOS and Linux; Windows answers that it has none yet) | -The web client has no runtime dependency. +The web client's runtime dependencies are the ones listed above as "web client". diff --git a/README.md b/README.md index a24a397..fdb006b 100644 --- a/README.md +++ b/README.md @@ -7,11 +7,12 @@

Books for a small company; sales, purchases, payments and stock in one ledger.
Every sale, purchase, payment and stock movement is a numbered document
- that posts to shared ledgers for money and stock. Local-first, on your own machine. + that posts to shared ledgers for money and stock. Local-first, on your own machine,
+ and scriptable from the command line.

- version v0.14.0 + version v0.15.0 Go 1.26+ TypeScript and Vite License: Apache-2.0 @@ -19,15 +20,33 @@

- Download · + Download FormLedger · Run it from source

+
+ +

+ + + FormLedger with a posted sales invoice for a customer open: four lines with quantities, unit prices and sales tax, a subtotal of 6,672.00, tax of 533.76 and a total of 7,205.76 USD, the date and due date shown whole, one row of buttons along the foot, the menu bar along the top and the sidebar of selling, buying, ledger and setup screens at the left + +
+ A posted sales invoice: the lines, the tax and the total the server worked out, with the menu bar in the window. The page follows your GitHub theme; the app has dark and light themselves. +

+

- Features · In the box · Agents · Under the hood · - Download · Run from source + Features · + In the box · + Agents · + Network · + Under the hood · + Download · + Run from source

+
+ @@ -37,11 +56,18 @@

One ledger

Documents post to a general ledger and a stock ledger, and a trial balance and the stock check say whether the books agree.
+
+ ## Features + + + +
+ + + The Trial balance report as of a day, with a Balanced badge, nine accounts listed with their debit or credit and equal debit and credit totals of 185,405.84 + +
A trial balance of a sample company: nine accounts, and debits equal credits.

The ledger core

A chart of accounts, fiscal years and period locks, and journal entries that post and cancel by reversal. A trial balance, general ledger, profit and loss and balance sheet read from it. See docs/ledger/.
@@ -56,13 +82,31 @@

People and audit

Every user has one role, the owner invites the others, and an audit trail records who did what. See docs/ROLES.md.
+ + + The Home start screen with six cards for the first things to do, three figures for what customers owe, what is owed to suppliers and cash and bank, and the last sales and purchase invoices + +
Home, from 0.15.0: where to start, then the figures and the last invoices. +

A start screen

Home opens with cards for a new sales invoice, quote or purchase invoice, a payment, the general ledger and a template, above what customers owe you, what you owe and your cash. +
+ + + The Preferences screen with theme choices Dark, Light and Match the system, six accent colours, a Show the agent dock checkbox and a Security heading + +
Preferences, from 0.15.0: theme, accent, the agent dock and the app lock. +

Preferences

Dark, light or the system's theme, six accents that leave debit, credit and chart colours alone, the agent dock and the app lock. +
## Everything in the box - + @@ -80,21 +124,49 @@ The command line is a client of the running server; it never opens the database. [`docs/ledger/cli.md`](docs/ledger/cli.md) walks from an empty company to a trial balance. What the app commits to do is listed in [`docs/BEHAVIOURS.md`](docs/BEHAVIOURS.md), and [`AGENTS.md`](AGENTS.md) is the guide for coding agents working on the repo. +From 0.15.0 the window also has an agent dock, opened from View, Agent Dock or with Cmd or Ctrl plus J: a terminal panel beside the books with a shell tab and tabs for Claude Code, Codex and Cursor when they are installed on your computer. Only the owner of the books can open it, and only from this computer. On Windows its terminals do not open yet. FormLedger has no MCP server yet; an agent drives the books through the command line above. + +## Network + +FormLedger keeps the books on your own computer. + +- **The server** listens on `127.0.0.1:8340` and answers this computer only. `FORMLEDGER_ADDR` changes the address; an address other machines can reach is your choice to make. `FORMLEDGER_TLS_CERT` with `FORMLEDGER_TLS_KEY`, or `FORMLEDGER_ACME_DOMAINS`, serve it over HTTPS. +- **The desktop app** starts its own copy of the server on a loopback address, which stays on this computer. +- **Nothing calls out.** The window loads no font, script or image from another host, and the server makes no outbound request of its own, apart from the certificate authority when you set `FORMLEDGER_ACME_DOMAINS`. +- **The command line** talks only to the server at `FORMLEDGER_URL`, with an app token. +- **The agent dock** (from 0.15.0) runs a shell and agent programs on this computer. What those programs send over the network is up to them and to you. + +Security reports go through [`SECURITY.md`](SECURITY.md). + ## Under the hood - **Go server:** one process is the only writer to the database; amounts are whole numbers of a currency's minor unit, never floats. - **Encryption at rest:** the database is encrypted when you give the server a key (`formledger keygen`, then `FORMLEDGER_KEY_FILE`); `formledger encrypt` converts an existing ledger. Without a key the ledger is stored plain, and the server says so when it starts. See [`docs/ENCRYPTION.md`](docs/ENCRYPTION.md). - **Web client:** vanilla TypeScript and Vite, with no UI framework, embedded into the server binary by `./build_app --server-only`. -- **Desktop shell:** a Tauri shell in `src-tauri/` around the server binary, with a native menubar (File, Edit, View, Go, Window, Help). It has not been compiled yet, so the menubar has not been run. +- **Desktop shell:** a Tauri 2 shell in `src-tauri/` around the server binary. From 0.15.0 the menu bar (File, Edit, View, Go, Window, Help) is drawn in the window on Windows and Linux, and macOS gets the system menu from the same list. - **Checks:** `./formledger check` runs gofmt, go vet and the web client's type check. ## Download -Not released yet. The desktop app has not been compiled and there is no release to download. To use FormLedger now, run it from source below. +Pick the file for your computer from the [Releases page](https://github.com/nodemode-dev/formledger/releases) of this repository. Each file is named `formledger--` with the kind of file at the end. + +| Your computer | File to download | What it is | +|---|---|---| +| Mac with Apple silicon (M1 or newer) | `formledger--macos-arm64.dmg` | Disk image. Open it and drag FormLedger to Applications. | +| Mac with an Intel processor | `formledger--macos-x64.dmg` | The same for Intel Macs. | +| Windows PC (64-bit Intel or AMD) | `formledger--windows-x64-setup.exe` | Installer. The one most people on Windows want. | +| Windows PC (64-bit Intel or AMD) | `formledger--windows-x64.msi` | The same app as an MSI installer, for IT teams that install on many PCs. | +| Linux PC (64-bit Intel or AMD) | `formledger--linux-x64.AppImage` | One file that runs on most Linux systems with no install. | +| Linux PC (64-bit Intel or AMD) | `formledger--linux-x64.deb` | Package for Debian, Ubuntu, Linux Mint and Pop!_OS. | +| Linux PC (64-bit Intel or AMD) | `formledger--linux-x64.rpm` | Package for Fedora, Red Hat, Rocky Linux and openSUSE. | + +Needs macOS 12 or newer on a Mac, and a Linux system with glibc 2.35 or newer (Ubuntu 22.04 has it). `SHA256SUMS.txt` on the same page lists a checksum for every file, to confirm that a download arrived whole. + +All FormLedger builds are compiled and released from [FormCompiler](https://github.com/nodemode-dev/formcompiler); this repo holds the source. ## Run it from source -**Requires:** Go 1.26 and Node 22, the versions the checks use. +**Requires:** Go 1.26 and Node 22, the versions the checks use. The desktop shell also needs Rust and the Tauri 2 system packages. ```sh git clone https://github.com/nodemode-dev/formledger.git @@ -105,6 +177,8 @@ cd formledger ./formledger help # every launcher command ``` +`./formledger desktop dev` opens the desktop window instead, with the server just compiled. + On Windows use `formledger_oc_install.bat` and `formledger.bat`. | Port | What listens | Change it with | @@ -123,9 +197,18 @@ On Windows use `formledger_oc_install.bat` and `formledger.bat`. | `FORMLEDGER_KEY_HOME` | Folder where the server makes and keeps its own key (`formledger.key`) when no key file is given. The desktop app sets it to its app data folder. Losing that key loses the books: back it up (`docs/ENCRYPTION.md`) | > [!IMPORTANT] -> **Status:** early. The ledger, selling, buying and stock work from the command line and over the server's routes. The window's screens for them are new and only partly checked in a browser, and the desktop app in `src-tauri/` has not been compiled. +> **Status:** early. The ledger, selling, buying and stock work from the command line and over the server's routes. The window's screens for them are new and only partly checked in a browser; see [`CHANGELOG.md`](CHANGELOG.md). -**Contributing:** see [`CONTRIBUTING.md`](CONTRIBUTING.md), [`BRANCHING.md`](BRANCHING.md) and [`AGENTS.md`](AGENTS.md). Security reports: [`SECURITY.md`](SECURITY.md). +**Contributing:** branch from `main`, keep changes to source here, and leave packaging and releases to FormCompiler. See [`CONTRIBUTING.md`](CONTRIBUTING.md), [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md), [`BRANCHING.md`](BRANCHING.md) and [`AGENTS.md`](AGENTS.md). Report security issues privately as [`SECURITY.md`](SECURITY.md) describes. + +## Demos and templates + +| What | Where | How it opens | +| --- | --- | --- | +| 3 demos: Larkspur Lane Cafe, Halftone Field Design Studio, Ironbark Hardware and Supply | [`demos/`](demos/README.md) | each is a data folder with three months of posted selling, buying, stock and payments; copy it and start `FORMLEDGER_DATA= ./formledger`, then sign in with the `about.json` email and the password `formledger-demo` | +| 48 document templates: 20 sales invoices by trade, 8 quotes, 5 sales orders, 6 purchase orders, 9 supplier bills | [`templates/`](templates/README.md) | each file is posted to `/api/templates` as it is, then shows on the Templates screen, where Use opens a new draft | + +Every company, person and address in them is invented. They are Apache-2.0, as FormLedger. ## Repository @@ -135,7 +218,10 @@ On Windows use `formledger_oc_install.bat` and `formledger.bat`. | `internal/` | The Go server: ledger, selling, buying, stock, reports, printing, roles, audit | | `web/` | The TypeScript and Vite client | | `src-tauri/` | The desktop shell around the server binary | -| `docs/` | What each part does and the behaviors the app commits to | +| `docs/` | What each part does and the behaviours the app commits to | +| `formledger` · `build_app` | The launcher (`./formledger help`) and the build script behind it | + +Docs: [`docs/`](docs/) · Agents: [`CLAUDE.md`](CLAUDE.md), [`AGENTS.md`](AGENTS.md) · Contributing: [`BRANCHING.md`](BRANCHING.md)
diff --git a/SECURITY.md b/SECURITY.md index cc69f92..16781ac 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -7,7 +7,7 @@ check whether the problem is still there. | Version | Supported | | --- | --- | -| 0.1.x (latest release) | Yes | +| Latest release | Yes | | Anything older | No | ## Reporting a vulnerability @@ -22,37 +22,36 @@ is fixed and credit you in the release notes, unless you would rather not be nam ## What counts -FormLedger is a local-first app: a Go server that listens on `127.0.0.1:8340` by -default and serves the web client, and a Tauri shell that starts that server on the -same computer. At this stage it has no accounts, sharing or network features, so the -things that matter most are: - -- **Reaching the server from outside the computer**: the server answering on an - address other than the one it was told to bind, or a web page in a browser reaching - its local API from another origin. -- **The data directory**: reading or writing files outside the directory named by - `FORMLEDGER_DATA`. +FormLedger runs on your own machine, so the things that matter most are the ways +something outside it could get in: + +- **The server** listens on loopback (`127.0.0.1:8340` by default, set with + `FORMLEDGER_ADDR`; the desktop app starts its own copy on a loopback address). Anything + that makes it reachable from another machine without the person turning that on, or + lets a web page on another origin drive it. +- **Accounts, roles and app tokens**: getting past a role, reading or changing the books + as another user, an app token doing more than its read or write scope or its owner's + role allows, an app token making another one, or any edit or delete of a row in the + audit trail. See [`docs/ROLES.md`](docs/ROLES.md). +- **The data directory and the key**: reading or writing files outside the directory + named by `FORMLEDGER_DATA`. With a key (`FORMLEDGER_KEY_FILE`, or a systemd credential + named `formledger.key`) the ledger database, its WAL and its journal are encrypted + with XTS-AES-256, and without one the server says at start that the ledger is plain. + The desktop app makes its own key in its app data folder, never in the data directory. + A missing or wrong key stops the server before any database is opened. Reading the + encrypted database without the key, or anything that leaves ledger data in the clear + inside an encrypted data directory, counts. `formledger report snapshot` writes a plain + copy by design and must be treated as sensitive. See + [`docs/ENCRYPTION.md`](docs/ENCRYPTION.md). - **The desktop shell**: the Tauri shell running the bundled server with more permissions than its capability files grant, or loading content that did not come from the app. +- **The agent dock** (from 0.15.0): anything other than FormLedger's own window on this + computer reaching a shell or an agent program through it. +- **Files**: exporting, printing or taking a snapshot in a way that writes outside where + it should. - **The build**: a script, workflow or dependency in this repository that runs something it should not. -Bugs that need someone to already control the computer, or to run a modified build of -FormLedger, are ordinary bugs: please open an issue for those. - -## Data at rest - -With a key (`FORMLEDGER_KEY_FILE`, or a systemd credential named `formledger.key`), -the ledger database, its WAL and its journal are encrypted with XTS-AES-256 through the -`formledger-crypt` SQLite VFS, ported from form.md. Without a key the ledger is plain, -and the server says so at start. With `FORMLEDGER_KEY_HOME` set and no key given, the -server makes its own key once in that folder (owner-only) and uses it from then on; the -desktop app is written to set it to its app data folder, which is not the data directory. -A missing or wrong key stops the server before any -database is opened. The key is never stored in the data directory; if it is lost, the -ledger cannot be recovered by anyone. `formledger report snapshot` writes a plain copy -by design and must be treated as sensitive. See [`docs/ENCRYPTION.md`](docs/ENCRYPTION.md). - -Reading the encrypted database without the key, or anything that leaves ledger data -in the clear inside an encrypted data directory, counts as a vulnerability. +Bugs that need someone to already control your machine, or to run a modified build +of FormLedger, are ordinary bugs: please open an issue for those. diff --git a/assets/screens/home-light.webp b/assets/screens/home-light.webp new file mode 100644 index 0000000..141d145 Binary files /dev/null and b/assets/screens/home-light.webp differ diff --git a/assets/screens/home.webp b/assets/screens/home.webp new file mode 100644 index 0000000..0bf1437 Binary files /dev/null and b/assets/screens/home.webp differ diff --git a/assets/screens/invoice-light.webp b/assets/screens/invoice-light.webp new file mode 100644 index 0000000..bbc77f0 Binary files /dev/null and b/assets/screens/invoice-light.webp differ diff --git a/assets/screens/invoice.webp b/assets/screens/invoice.webp new file mode 100644 index 0000000..f6a2ae4 Binary files /dev/null and b/assets/screens/invoice.webp differ diff --git a/assets/screens/preferences-light.webp b/assets/screens/preferences-light.webp new file mode 100644 index 0000000..5896cc3 Binary files /dev/null and b/assets/screens/preferences-light.webp differ diff --git a/assets/screens/preferences.webp b/assets/screens/preferences.webp new file mode 100644 index 0000000..8ef4fe2 Binary files /dev/null and b/assets/screens/preferences.webp differ diff --git a/assets/screens/report-light.webp b/assets/screens/report-light.webp new file mode 100644 index 0000000..856ff31 Binary files /dev/null and b/assets/screens/report-light.webp differ diff --git a/assets/screens/report.webp b/assets/screens/report.webp new file mode 100644 index 0000000..d7bd31a Binary files /dev/null and b/assets/screens/report.webp differ diff --git a/build_app b/build_app index 4cb837c..fa92f9f 100755 --- a/build_app +++ b/build_app @@ -4,7 +4,7 @@ cd "$(dirname "$0")" usage() { cat << 'EOF' -usage: ./build_app [--server-only] [--skip-web] [--debug] [--bundles LIST] +usage: ./build_app [--server-only] [--skip-web] [--debug] [--bundles LIST] [--config FILE] Builds FormLedger: the desktop app for this computer, with the server inside it. 1. checks Go and Node 22+ @@ -20,6 +20,7 @@ Options: --skip-web reuse the web client already in web/dist --debug a debug build of the desktop app --bundles LIST which desktop packages, for example app or deb,appimage + --config FILE a Tauri config file (or JSON) merged over src-tauri/tauri.conf.json On Windows run build_app.bat. Run the server alone with ./bin/formledger. EOF @@ -37,6 +38,10 @@ while [ $# -gt 0 ]; do [ $# -ge 2 ] || { printf '[build_app] --bundles needs a list\n' >&2; exit 2; } desktop_args+=("$1" "$2"); shift ;; --bundles=*) desktop_args+=("--bundles" "${1#--bundles=}") ;; + --config) + [ $# -ge 2 ] || { printf '[build_app] --config needs a file\n' >&2; exit 2; } + desktop_args+=("--config" "$2"); shift ;; + --config=*) desktop_args+=("--config" "${1#--config=}") ;; -h|--help) usage; exit 0 ;; *) printf '[build_app] unknown option: %s\n\n' "$1" >&2; usage >&2; exit 2 ;; esac @@ -79,7 +84,7 @@ say "done: bin/formledger$ext ($(du -h "bin/formledger$ext" | cut -f1))" [ -x "$HOME/.cargo/bin/rustc" ] && export PATH="$HOME/.cargo/bin:$PATH" command -v rustc >/dev/null 2>&1 || die "Rust is needed for the desktop app: install it from https://rustup.rs and run ./build_app again, or use --server-only" -[ -x web/node_modules/.bin/tauri ] || die "the Tauri CLI is not in web/node_modules: run ./formledger_oc_install, or use --server-only" +[ -x web/node_modules/.bin/tauri ] || die "the Tauri CLI is not in web/node_modules: run npm ci in web, or use --server-only" triple="$(rustc -vV | awk '/^host:/ {print $2}')" mkdir -p src-tauri/binaries rm -f src-tauri/binaries/formledger-server-* diff --git a/build_app.bat b/build_app.bat index aa00339..2441758 100644 --- a/build_app.bat +++ b/build_app.bat @@ -46,6 +46,8 @@ del /q src-tauri\binaries\formledger-server-* 2>nul copy /y bin\formledger.exe "src-tauri\binaries\formledger-server-%TRIPLE%.exe" >nul || exit /b 1 echo [build_app] server inside the app: src-tauri\binaries\formledger-server-%TRIPLE%.exe +if not exist web\node_modules\.bin\tauri.cmd (echo [build_app] the Tauri CLI is not in web\node_modules: run npm ci in web & exit /b 1) + findstr /c:"\"version\": \"%APPV%\"" src-tauri\tauri.conf.json >nul || (echo [build_app] src-tauri\tauri.conf.json does not carry version %APPV% & exit /b 1) echo [build_app] bundling %BUNDLES% pushd src-tauri diff --git a/cmd/HASHOUT_LOG.md b/cmd/HASHOUT_LOG.md index 391feee..a3a86a0 100644 --- a/cmd/HASHOUT_LOG.md +++ b/cmd/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for the entry point, `embed.go`, `internal/server`, `internal/static` and `internal/startup`. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. Read it first, then edit code surgically. -Current build version: v0.14.0 +Current build version: v0.15.0 Last updated: 2026-11-26 (US Eastern) · skeleton port from form.md --- diff --git a/demos/README.md b/demos/README.md new file mode 100644 index 0000000..019c58d --- /dev/null +++ b/demos/README.md @@ -0,0 +1,22 @@ +# Demos + +Three complete, invented small companies, each a FormLedger data folder with three months of posted work (September to November 2026): sales and purchase documents, goods in and out of stock, payments both ways, and the reports that follow from them. Every company, person and address is fictional; email addresses use the reserved `.example` domain. + +| Folder | Company | What it shows | +| --- | --- | --- | +| `larkspur-cafe` | Larkspur Lane Cafe | catering and wholesale beans with sales tax, stock bought and delivered, rent and utilities | +| `halftone-studio` | Halftone Field Design Studio | project work billed as deposit and balance, day rates, prints sold from stock | +| `ironbark-hardware` | Ironbark Hardware and Supply | three wholesalers into stock, trade accounts and counter sales, freight | + +## Open one + +Opening a data folder writes to it, so open a copy: + +``` +cp -R demos/larkspur-cafe/data /tmp/larkspur-cafe +FORMLEDGER_DATA=/tmp/larkspur-cafe ./formledger +``` + +Then sign in at http://127.0.0.1:8340 with the email in the demo's `about.json` and the password `formledger-demo`. Home shows the balances and the last invoices; Reports holds the trial balance, profit and loss and balance sheet for the period. + +Each folder's `about.json` names the demo, describes it and gives its licence (Apache-2.0, as FormLedger) and credit. diff --git a/demos/halftone-studio/README.md b/demos/halftone-studio/README.md new file mode 100644 index 0000000..90127ac --- /dev/null +++ b/demos/halftone-studio/README.md @@ -0,0 +1,3 @@ +# Halftone Field Design Studio + +Open a copy: `cp -R data /tmp/halftone-studio && FORMLEDGER_DATA=/tmp/halftone-studio ./formledger`, then sign in as `owner@halftone-studio.example` with the password `formledger-demo`. diff --git a/demos/halftone-studio/about.json b/demos/halftone-studio/about.json new file mode 100644 index 0000000..357d576 --- /dev/null +++ b/demos/halftone-studio/about.json @@ -0,0 +1,9 @@ +{ + "id": "halftone-studio", + "name": "Halftone Field Design Studio", + "description": "A two-person design studio from September to November 2026: a brand project billed as deposit and balance, illustration and web design days, art prints and zines sold to a gallery shop from stock, desk rent and software bills, and a confirmed quote for the next project.", + "licence": "Apache-2.0", + "credit": "Invented sample data made with FormLedger by nodemode.ai; every company, person and address in it is fictional.", + "open": "FORMLEDGER_DATA= ./formledger", + "signIn": {"email": "owner@halftone-studio.example", "password": "formledger-demo"} +} diff --git a/demos/halftone-studio/data/formledger.db b/demos/halftone-studio/data/formledger.db new file mode 100644 index 0000000..44b1181 Binary files /dev/null and b/demos/halftone-studio/data/formledger.db differ diff --git a/demos/ironbark-hardware/README.md b/demos/ironbark-hardware/README.md new file mode 100644 index 0000000..3d7036c --- /dev/null +++ b/demos/ironbark-hardware/README.md @@ -0,0 +1,3 @@ +# Ironbark Hardware and Supply + +Open a copy: `cp -R data /tmp/ironbark-hardware && FORMLEDGER_DATA=/tmp/ironbark-hardware ./formledger`, then sign in as `owner@ironbark-hardware.example` with the password `formledger-demo`. diff --git a/demos/ironbark-hardware/about.json b/demos/ironbark-hardware/about.json new file mode 100644 index 0000000..1e45c37 --- /dev/null +++ b/demos/ironbark-hardware/about.json @@ -0,0 +1,9 @@ +{ + "id": "ironbark-hardware", + "name": "Ironbark Hardware and Supply", + "description": "A hardware shop with a trade counter from September to November 2026: tools, fixings and paint bought from three wholesalers into stock, trade accounts and counter sales with 7.25 percent sales tax, deliveries out of the yard, rent and freight bills, a part payment and open invoices on both sides.", + "licence": "Apache-2.0", + "credit": "Invented sample data made with FormLedger by nodemode.ai; every company, person and address in it is fictional.", + "open": "FORMLEDGER_DATA= ./formledger", + "signIn": {"email": "owner@ironbark-hardware.example", "password": "formledger-demo"} +} diff --git a/demos/ironbark-hardware/data/formledger.db b/demos/ironbark-hardware/data/formledger.db new file mode 100644 index 0000000..32c6fe0 Binary files /dev/null and b/demos/ironbark-hardware/data/formledger.db differ diff --git a/demos/larkspur-cafe/README.md b/demos/larkspur-cafe/README.md new file mode 100644 index 0000000..638c1cf --- /dev/null +++ b/demos/larkspur-cafe/README.md @@ -0,0 +1,3 @@ +# Larkspur Lane Cafe + +Open a copy: `cp -R data /tmp/larkspur-cafe && FORMLEDGER_DATA=/tmp/larkspur-cafe ./formledger`, then sign in as `owner@larkspur-cafe.example` with the password `formledger-demo`. diff --git a/demos/larkspur-cafe/about.json b/demos/larkspur-cafe/about.json new file mode 100644 index 0000000..555d8b4 --- /dev/null +++ b/demos/larkspur-cafe/about.json @@ -0,0 +1,9 @@ +{ + "id": "larkspur-cafe", + "name": "Larkspur Lane Cafe", + "description": "A small cafe from September to November 2026: catering and wholesale bean invoices with 8 percent sales tax, beans and mugs bought in and delivered from stock, rent and utility bills, payments in and out, one part-paid and two open invoices, and two quotes.", + "licence": "Apache-2.0", + "credit": "Invented sample data made with FormLedger by nodemode.ai; every company, person and address in it is fictional.", + "open": "FORMLEDGER_DATA= ./formledger", + "signIn": {"email": "owner@larkspur-cafe.example", "password": "formledger-demo"} +} diff --git a/demos/larkspur-cafe/data/formledger.db b/demos/larkspur-cafe/data/formledger.db new file mode 100644 index 0000000..2ed5b9c Binary files /dev/null and b/demos/larkspur-cafe/data/formledger.db differ diff --git a/go.mod b/go.mod index 9937d52..bb4bb1d 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/nodemode-ai/formledger go 1.26.9 require ( + github.com/creack/pty v1.1.24 github.com/go-pdf/fpdf v0.9.0 golang.org/x/crypto v0.58.0 modernc.org/libc v1.77.1 diff --git a/go.sum b/go.sum index 8fda208..e052281 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= +github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/go-pdf/fpdf v0.9.0 h1:PPvSaUuo1iMi9KkaAn90NuKi+P4gwMedWPHhj8YlJQw= diff --git a/internal/HASHOUT_LOG.md b/internal/HASHOUT_LOG.md index cd3d9dd..36df965 100644 --- a/internal/HASHOUT_LOG.md +++ b/internal/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of comment content, rationale and removed code for the core skeleton packages under `internal/`. Source files stay comment-free; what they would have said lives here, indexed. Read it first, then edit code surgically. Covers the packages ported in the core slice only; `internal/server`, `internal/static` and `internal/startup` are logged by their own slice. -Current build version: v0.14.0 +Current build version: v0.15.0 Last updated: 2026-11-27 (US Eastern) · profit and loss and the balance sheet --- @@ -1910,3 +1910,44 @@ The earlier proof printed drafts, so no heading had a number and the statement h - logged: v0.14.0 · 2026-11-27 A line with no item and no account was refused (`no_expense_account`, `no_income_account`), and the form had no way to name one. The chart marks no default account, so the rule is the smallest honest one already used for item lines on buying: the setting `purchase.expense_account`, else 5100; selling gets the same shape, `sales.income_account`, else 4100. When that account is missing, inactive or a group, the refusal keeps its code and says in words to add the account to the chart or pick an item. Against a seeded copy, a free line "Courier fee" at 42.50 posted PI-2026-000001 as 5100 debit, 2110 credit, and SI-2026-000001 as 1200 debit, 4100 credit. + +--- + +## internal/dock · the agent dock's terminals and agent programs (v0.15.0) + +Map: `internal/dock/` · `guard.go` who may call, `session.go` the PTY sessions and their registry, `programs.go` finding Claude Code, Codex and Cursor and their status, `ws.go` the WebSocket, `module.go` the routes. Registered by one line in `internal/server/server.go` (`dock.Module(accounts)`, beside `delivery`). `go.mod` gains `github.com/creack/pty v1.1.24` (MIT, in `NOTICE.md`). + +### internal/dock/guard.go · only the owner, only this computer, never an agent credential +- refers-to: internal/dock/guard.go :: local, loopbackName, guard +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +Every route goes through `auth.Service.Session`, so a request with no session is 401 and an API token is 403 `session_only` (clause 1 of the dock contract: the dock is the person's, an agent's credential is never accepted). Then `local`: the peer address is loopback, no proxy header is present (a reverse proxy on the same machine would otherwise make every visitor look local), the `Host` names loopback (a page that rebinds its own domain to 127.0.0.1 is refused), an `Origin`, when sent, is the request's own scheme and host (another local site on another port shares the cookie's site but not this origin), and `Sec-Fetch-Site` is not cross-site. Then the role is `owner`; other roles get 403 `dock_owner_only`. `internal/netguard` is the guard for addresses FormLedger fetches, not for callers, so the peer test is written here with `netip` and does not reuse it. The stream additionally requires an `Origin`, which every browser sends on a WebSocket. + +### internal/dock/session.go · PTY sessions, as FormVis's services/terminal.py keeps them +- refers-to: internal/dock/session.go :: session, registry, pump, cut, attach, restart, close +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +A session holds its launch (argv, environment, folder), 256 KiB of scrollback, a generation counter and its subscribers. `pump` reads the PTY and holds back a trailing partial UTF-8 sequence until the next read, then sends valid UTF-8 (a WebSocket text frame must be), with invalid bytes as U+FFFD. A subscriber's queue holds 1024 frames; when it is full output is dropped, and an exit that cannot be queued ends that stream (clause 9: never block the program). `restart` raises the generation so the old pump's last output and its exit are ignored, clears the scrollback, starts the same launch again and sends `ESC c` to attached windows. `close` is safe to repeat. Tabs belong to the user who opened them and lists, streams and changes are refused (404) for anyone else's. At most 16 sessions and 24 streams at once. The child is killed and its PTY closed on close, restart and engine shutdown (`Stop`). On Windows `creack/pty` has no PTY, so opening answers 501 `pty_unsupported`. + +### internal/dock/programs.go · Claude Code, Codex and Cursor +- refers-to: internal/dock/programs.go :: programs, locate, childEnv, signedIn, statusCache +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +A program is looked for on `PATH` and then where installers put it when an app started from the Finder has a short `PATH` (`~/.local/bin`, `~/.claude/local`, `~/.npm-global/bin`, `~/.bun/bin`, `~/.volta/bin`, `~/.cursor/bin`, `/opt/homebrew/bin`, `/usr/local/bin`, `%APPDATA%\npm`). Found and `--version` answering means installed; the version is cached per path, modification time and size. Signed in: Claude Code is yes with `ANTHROPIC_API_KEY` or `CLAUDE_CODE_OAUTH_TOKEN`, else `claude auth status` (`loggedIn`), as FormVis does; Codex reads `codex login status`; Cursor reads `cursor-agent status`; anything unclear is null, which the module words as "cannot tell". Each check has five seconds and the whole answer is kept 30 seconds (`?fresh=1` asks again). The child's environment drops every `FORMLEDGER_` variable (the key file, key home and desktop key live there), puts the program's own folder and the folders above on `PATH`, and sets `TERM`, `COLORTERM`, `FORMLEDGER_TERMINAL=1` and `FORMLEDGER_ENGINE_URL`. FormLedger has no MCP server, so no tab gets a token or an MCP entry (clause 11 does not arise) and there are no consent questions. A Claude Code prompt is an argument after `--`; a resume id must match `[A-Za-z0-9_-]{1,200}`. A live Claude Code tab is reused unless a resume is asked for, and a prompt is typed into it. + +### internal/dock/ws.go · a WebSocket without a dependency +- refers-to: internal/dock/ws.go :: upgradeCheck, upgrade, wsConn.read, wsConn.write +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +RFC 6455 server side only: the handshake through `http.ResponseController.Hijack` (it unwraps the access-log recorder), masked client frames up to 1 MiB with continuation, ping answered, close echoed, unmasked server frames with a ten second write deadline. Output goes as text frames and the exit as a binary frame `{"type":"exit"}`, so shell output is never read as a control message (FormVis's framing). Every attach first sends the scrollback, even when empty, so the window knows the engine answered (clause 7). The window sends `{"type":"input","data"}` and `{"type":"resize","cols","rows"}`; anything else is ignored. + +### internal/dock/module.go · the routes +- refers-to: internal/dock/module.go :: Mount +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +`GET /api/terminal` (`{terminals: [{id,title,cwd,alive,kind}]}`), `POST /api/terminal` (shell, `{cols,rows}`), `POST /api/terminal/claude` (`{cols,rows,prompt?,resume?}`), `POST /api/terminal/agent` (`{kind: codex|cursor, cols, rows}`), `POST /api/terminal/{id}/resize`, `POST /api/terminal/{id}/restart`, `DELETE /api/terminal/{id}`, `GET /api/terminal/{id}/stream` (WebSocket), `GET /api/agent/status` (`{claude,codex,cursor}` each `{installed,version,install,signedIn,said?,title}`, FormDeck's shape). A missing program answers 409 `program_missing`, which the adapter maps to `notInstalled`. Shells and programs start in the user's home folder (the data folder if there is none), never in the data folder's books. diff --git a/internal/app/version.go b/internal/app/version.go index e0de571..4c590fe 100644 --- a/internal/app/version.go +++ b/internal/app/version.go @@ -1,5 +1,5 @@ package app -var Version = "v0.14.0" +var Version = "v0.15.0" const Product = "FormLedger" diff --git a/internal/dock/guard.go b/internal/dock/guard.go new file mode 100644 index 0000000..75dec80 --- /dev/null +++ b/internal/dock/guard.go @@ -0,0 +1,71 @@ +package dock + +import ( + "net" + "net/http" + "net/netip" + "net/url" + "strings" + + "github.com/nodemode-ai/formledger/internal/auth" + "github.com/nodemode-ai/formledger/internal/httpx" + "github.com/nodemode-ai/formledger/internal/policy" +) + +var ( + errLocal = httpx.Fail(http.StatusForbidden, "dock_local_only", "the terminals answer only the FormLedger window on this computer") + errOwner = httpx.Fail(http.StatusForbidden, "dock_owner_only", "only the owner of these books may open terminals") +) + +var proxyHeaders = []string{"Forwarded", "X-Forwarded-For", "X-Forwarded-Host", "X-Real-Ip"} + +func loopbackName(hostport string) bool { + host := hostport + if h, _, err := net.SplitHostPort(hostport); err == nil { + host = h + } + host = strings.Trim(strings.ToLower(host), "[]") + if host == "localhost" { + return true + } + a, err := netip.ParseAddr(host) + return err == nil && a.Unmap().IsLoopback() +} + +func local(r *http.Request) bool { + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return false + } + peer, err := netip.ParseAddr(host) + if err != nil || !peer.Unmap().IsLoopback() { + return false + } + for _, h := range proxyHeaders { + if r.Header.Get(h) != "" { + return false + } + } + if !loopbackName(r.Host) { + return false + } + if o := r.Header.Get("Origin"); o != "" { + u, err := url.Parse(o) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || !strings.EqualFold(u.Host, r.Host) { + return false + } + } + return r.Header.Get("Sec-Fetch-Site") != "cross-site" +} + +func guard(a *auth.Service, h auth.PrincipalHandler) http.HandlerFunc { + return a.Session(func(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + if !local(r) { + return errLocal + } + if p.Role != policy.Owner { + return errOwner + } + return h(w, r, p) + }) +} diff --git a/internal/dock/module.go b/internal/dock/module.go new file mode 100644 index 0000000..6499571 --- /dev/null +++ b/internal/dock/module.go @@ -0,0 +1,291 @@ +package dock + +import ( + "encoding/json" + "net/http" + "os" + "regexp" + "runtime" + "strings" + + "github.com/nodemode-ai/formledger/internal/app" + "github.com/nodemode-ai/formledger/internal/auth" + "github.com/nodemode-ai/formledger/internal/httpx" + "github.com/nodemode-ai/formledger/internal/policy" +) + +var resumeID = regexp.MustCompile(`^[A-Za-z0-9_-]{1,200}$`) + +var errMissing = func(p program) error { + return httpx.Fail(http.StatusConflict, "program_missing", p.title+" is not installed on this computer: "+p.install) +} + +type module struct { + auth *auth.Service + reg registry + status statusCache + dataDir string +} + +func Module(a *auth.Service) app.Module { return &module{auth: a} } + +func (m *module) ID() string { return "dock" } + +func (m *module) Stop() { m.reg.closeAll() } + +func (m *module) Mount(r *httpx.Router, d *app.Deps) error { + m.dataDir = d.Config.DataDir + g := func(h auth.PrincipalHandler) http.HandlerFunc { return guard(m.auth, h) } + r.HandleFunc("GET /api/terminal", g(m.list)) + r.HandleFunc("POST /api/terminal", g(m.openShell)) + r.HandleFunc("POST /api/terminal/claude", g(m.openClaude)) + r.HandleFunc("POST /api/terminal/agent", g(m.openAgent)) + r.HandleFunc("POST /api/terminal/{id}/resize", g(m.resize)) + r.HandleFunc("POST /api/terminal/{id}/restart", g(m.restart)) + r.HandleFunc("DELETE /api/terminal/{id}", g(m.close)) + r.HandleFunc("GET /api/terminal/{id}/stream", g(m.stream)) + r.HandleFunc("GET /api/agent/status", g(m.agentStatus)) + return nil +} + +func (m *module) workdir() string { + if h := homeDir(); h != "" { + if st, err := os.Stat(h); err == nil && st.IsDir() { + return h + } + } + return m.dataDir +} + +func engineURL(r *http.Request) string { + if r.TLS != nil { + return "https://" + r.Host + } + return "http://" + r.Host +} + +func loginShell() []string { + if runtime.GOOS == "windows" { + if c := os.Getenv("COMSPEC"); c != "" { + return []string{c} + } + return []string{"cmd.exe"} + } + if sh := os.Getenv("SHELL"); sh != "" && runnable(sh) { + return []string{sh, "-l"} + } + for _, sh := range []string{"/bin/bash", "/bin/zsh", "/bin/sh"} { + if runnable(sh) { + return []string{sh, "-l"} + } + } + return []string{"/bin/sh"} +} + +type sizeBody struct { + Cols int `json:"cols"` + Rows int `json:"rows"` +} + +func decodeSize(r *http.Request) (sizeBody, error) { + b := sizeBody{Cols: 100, Rows: 30} + if r.ContentLength == 0 { + return b, nil + } + return b, httpx.Decode(r, &b) +} + +func (m *module) list(w http.ResponseWriter, _ *http.Request, p *policy.Principal) error { + httpx.JSON(w, http.StatusOK, map[string]any{"terminals": m.reg.mine(p.UserID)}) + return nil +} + +func (m *module) openShell(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + b, err := decodeSize(r) + if err != nil { + return err + } + s, err := m.reg.add(p.UserID, "shell", "", launch{argv: loginShell(), env: childEnv(engineURL(r), ""), dir: m.workdir()}, b.Cols, b.Rows) + if err != nil { + return err + } + httpx.JSON(w, http.StatusOK, s.describe()) + return nil +} + +func (m *module) openProgram(w http.ResponseWriter, r *http.Request, p *policy.Principal, prog program, args []string, cols, rows int) error { + st := m.status.one(prog) + if !st.Installed { + m.status.mu.Lock() + m.status.last = nil + m.status.mu.Unlock() + return errMissing(prog) + } + argv := append([]string{st.path}, args...) + s, err := m.reg.add(p.UserID, prog.kind, prog.title, launch{argv: argv, env: childEnv(engineURL(r), st.path), dir: m.workdir()}, cols, rows) + if err != nil { + return err + } + httpx.JSON(w, http.StatusOK, s.describe()) + return nil +} + +func (m *module) openClaude(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + b := struct { + Cols int `json:"cols"` + Rows int `json:"rows"` + Prompt string `json:"prompt"` + Resume string `json:"resume"` + }{Cols: 100, Rows: 30} + if r.ContentLength != 0 { + if err := httpx.Decode(r, &b); err != nil { + return err + } + } + if len(b.Prompt) > 100_000 { + return httpx.Fail(http.StatusRequestEntityTooLarge, "prompt_too_long", "the prompt is longer than 100000 characters") + } + if b.Resume != "" && !resumeID.MatchString(b.Resume) { + return httpx.Fail(http.StatusBadRequest, "bad_resume", "the session to resume is not a Claude Code session id") + } + if b.Resume == "" { + if live := m.reg.liveClaude(p.UserID); live != nil { + if b.Prompt != "" { + live.write(strings.ReplaceAll(strings.ReplaceAll(b.Prompt, "\r\n", "\n"), "\r", "\n") + "\r") + } + httpx.JSON(w, http.StatusOK, live.describe()) + return nil + } + } + var args []string + if b.Resume != "" { + args = append(args, "--resume", b.Resume) + } + if b.Prompt != "" { + args = append(args, "--", b.Prompt) + } + prog, _ := programFor("claude") + return m.openProgram(w, r, p, prog, args, b.Cols, b.Rows) +} + +func (m *module) openAgent(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + b := struct { + Kind string `json:"kind"` + Cols int `json:"cols"` + Rows int `json:"rows"` + }{Cols: 100, Rows: 30} + if err := httpx.Decode(r, &b); err != nil { + return err + } + prog, ok := programFor(b.Kind) + if !ok || prog.kind == "claude" { + return httpx.Fail(http.StatusBadRequest, "bad_kind", "the agent program must be codex or cursor") + } + return m.openProgram(w, r, p, prog, nil, b.Cols, b.Rows) +} + +func (m *module) resize(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + s, err := m.reg.get(r.PathValue("id"), p.UserID) + if err != nil { + return err + } + b, err := decodeSize(r) + if err != nil { + return err + } + s.resize(b.Cols, b.Rows) + httpx.JSON(w, http.StatusOK, map[string]bool{"ok": true}) + return nil +} + +func (m *module) restart(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + s, err := m.reg.get(r.PathValue("id"), p.UserID) + if err != nil { + return err + } + if err := s.restart(); err != nil { + return err + } + httpx.JSON(w, http.StatusOK, s.describe()) + return nil +} + +func (m *module) close(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + m.reg.remove(r.PathValue("id"), p.UserID) + httpx.JSON(w, http.StatusOK, map[string]bool{"ok": true}) + return nil +} + +func (m *module) agentStatus(w http.ResponseWriter, r *http.Request, _ *policy.Principal) error { + httpx.JSON(w, http.StatusOK, m.status.all(r.URL.Query().Get("fresh") == "1")) + return nil +} + +type inbound struct { + Type string `json:"type"` + Data string `json:"data"` + Cols int `json:"cols"` + Rows int `json:"rows"` +} + +func (m *module) stream(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + s, err := m.reg.get(r.PathValue("id"), p.UserID) + if err != nil { + return err + } + if r.Header.Get("Origin") == "" { + return errLocal + } + if err := upgradeCheck(r); err != nil { + return err + } + if !m.reg.takeSocket() { + return httpx.Fail(http.StatusTooManyRequests, "too_many_streams", "too many terminal streams are open") + } + defer m.reg.releaseSocket() + ws, err := upgrade(w, r) + if err != nil { + return nil + } + defer ws.close() + x, replay, alive := s.attach() + defer s.detach(x) + if ws.write(opText, []byte(replay)) != nil { + return nil + } + exit, _ := json.Marshal(map[string]string{"type": "exit"}) + if !alive && s.kind != "agent" { + _ = ws.write(opBinary, exit) + } + go func() { + for f := range x.ch { + if f.exit { + _ = ws.write(opBinary, exit) + continue + } + if ws.write(opText, []byte(f.text)) != nil { + return + } + } + ws.shut() + }() + for { + op, data, err := ws.read() + if err != nil { + return nil + } + if op != opText { + continue + } + var msg inbound + if json.Unmarshal(data, &msg) != nil { + continue + } + switch msg.Type { + case "input": + s.write(msg.Data) + case "resize": + s.resize(msg.Cols, msg.Rows) + } + } +} diff --git a/internal/dock/programs.go b/internal/dock/programs.go new file mode 100644 index 0000000..8eff580 --- /dev/null +++ b/internal/dock/programs.go @@ -0,0 +1,276 @@ +package dock + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "strings" + "sync" + "time" + + "github.com/nodemode-ai/formledger/internal/config" +) + +const ( + checkWait = 5 * time.Second + statusFresh = 30 * time.Second +) + +type program struct { + kind, bin, title, install string +} + +var programs = []program{ + {kind: "claude", bin: "claude", title: "Claude Code", install: "npm install -g @anthropic-ai/claude-code"}, + {kind: "codex", bin: "codex", title: "Codex", install: "npm install -g @openai/codex"}, + {kind: "cursor", bin: "cursor-agent", title: "Cursor", install: "curl https://cursor.com/install -fsS | bash"}, +} + +func programFor(kind string) (program, bool) { + for _, p := range programs { + if p.kind == kind { + return p, true + } + } + return program{}, false +} + +type programStatus struct { + Installed bool `json:"installed"` + Version *string `json:"version"` + Install string `json:"install"` + SignedIn *bool `json:"signedIn"` + Said string `json:"said,omitempty"` + Title string `json:"title"` + path string +} + +var versionPattern = regexp.MustCompile(`\d+\.\d+(?:\.\d+)?(?:[-+.][0-9A-Za-z.]+)?`) + +func homeDir() string { + if h, err := os.UserHomeDir(); err == nil { + return h + } + return "" +} + +func extraDirs() []string { + home := homeDir() + var dirs []string + if home != "" { + dirs = append(dirs, filepath.Join(home, ".local", "bin"), filepath.Join(home, ".claude", "local"), filepath.Join(home, ".npm-global", "bin"), + filepath.Join(home, ".bun", "bin"), filepath.Join(home, ".volta", "bin"), filepath.Join(home, ".cursor", "bin")) + } + if runtime.GOOS == "windows" { + if ad := os.Getenv("APPDATA"); ad != "" { + dirs = append(dirs, filepath.Join(ad, "npm")) + } + return dirs + } + return append(dirs, "/opt/homebrew/bin", "/usr/local/bin") +} + +func searchDirs() []string { + return append(filepath.SplitList(os.Getenv("PATH")), extraDirs()...) +} + +func runnable(path string) bool { + st, err := os.Stat(path) + if err != nil || !st.Mode().IsRegular() { + return false + } + return runtime.GOOS == "windows" || st.Mode().Perm()&0o111 != 0 +} + +func locate(bin string) string { + exts := []string{""} + if runtime.GOOS == "windows" { + exts = []string{".exe", ".cmd", ".bat", ""} + } + for _, dir := range searchDirs() { + if dir == "" { + continue + } + for _, ext := range exts { + if p := filepath.Join(dir, bin+ext); runnable(p) { + return p + } + } + } + return "" +} + +func childEnv(engineURL, programPath string) []string { + var out []string + for _, kv := range os.Environ() { + name, _, _ := strings.Cut(kv, "=") + switch { + case strings.HasPrefix(strings.ToUpper(name), config.EnvPrefix), strings.EqualFold(name, "PATH"), name == "TERM", name == "COLORTERM": + continue + } + out = append(out, kv) + } + dirs := searchDirs() + if programPath != "" { + dirs = append([]string{filepath.Dir(programPath)}, dirs...) + } + return append(out, "PATH="+strings.Join(dirs, string(os.PathListSeparator)), "TERM=xterm-256color", "COLORTERM=truecolor", + config.EnvPrefix+"TERMINAL=1", config.EnvPrefix+"ENGINE_URL="+engineURL) +} + +func run(path string, args ...string) (string, int, error) { + ctx, cancel := context.WithTimeout(context.Background(), checkWait) + defer cancel() + cmd := exec.CommandContext(ctx, path, args...) + cmd.Env = childEnv("", path) + cmd.WaitDelay = time.Second + var out bytes.Buffer + cmd.Stdout, cmd.Stderr = &out, &out + err := cmd.Run() + var exit *exec.ExitError + if errors.As(err, &exit) && ctx.Err() == nil { + return out.String(), exit.ExitCode(), nil + } + if err != nil { + return out.String(), -1, err + } + return out.String(), 0, nil +} + +func signedIn(kind, path string) *bool { + yes, no := true, false + switch kind { + case "claude": + if os.Getenv("ANTHROPIC_API_KEY") != "" || os.Getenv("CLAUDE_CODE_OAUTH_TOKEN") != "" { + return &yes + } + out, _, err := run(path, "auth", "status") + if err != nil { + return nil + } + var said struct { + LoggedIn *bool `json:"loggedIn"` + } + if json.Unmarshal([]byte(strings.TrimSpace(out)), &said) == nil && said.LoggedIn != nil { + return said.LoggedIn + } + case "codex": + out, code, err := run(path, "login", "status") + if err != nil { + return nil + } + if code == 0 && strings.Contains(strings.ToLower(out), "logged in") { + return &yes + } + if strings.Contains(strings.ToLower(out), "not logged in") { + return &no + } + case "cursor": + out, _, err := run(path, "status") + if err != nil { + return nil + } + low := strings.ToLower(out) + if strings.Contains(low, "not logged in") || strings.Contains(low, "not authenticated") { + return &no + } + if strings.Contains(low, "logged in") { + return &yes + } + } + return nil +} + +type versionKey struct { + path string + mod time.Time + size int64 +} + +type statusCache struct { + mu sync.Mutex + versions map[versionKey]*string + at time.Time + last map[string]programStatus +} + +func (c *statusCache) version(path string) (*string, bool) { + st, err := os.Stat(path) + if err != nil { + return nil, false + } + key := versionKey{path, st.ModTime(), st.Size()} + c.mu.Lock() + v, ok := c.versions[key] + c.mu.Unlock() + if ok { + return v, v != nil + } + out, code, err := run(path, "--version") + if err == nil && code == 0 { + if m := versionPattern.FindString(out); m != "" { + v = &m + } else { + s := strings.TrimSpace(strings.SplitN(out, "\n", 2)[0]) + v = &s + } + } + c.mu.Lock() + if c.versions == nil { + c.versions = map[versionKey]*string{} + } + c.versions[key] = v + c.mu.Unlock() + return v, v != nil +} + +func (c *statusCache) one(p program) programStatus { + st := programStatus{Install: p.install, Title: p.title} + path := locate(p.bin) + if path == "" { + return st + } + st.path = path + v, ok := c.version(path) + if !ok { + st.Said = p.title + " was found at " + path + " but does not start." + return st + } + st.Installed, st.Version, st.Install = true, v, "" + st.SignedIn = signedIn(p.kind, path) + return st +} + +func (c *statusCache) all(fresh bool) map[string]programStatus { + c.mu.Lock() + if !fresh && c.last != nil && time.Since(c.at) < statusFresh { + out := c.last + c.mu.Unlock() + return out + } + c.mu.Unlock() + out := make(map[string]programStatus, len(programs)) + var wg sync.WaitGroup + var mu sync.Mutex + for _, p := range programs { + wg.Add(1) + go func() { + defer wg.Done() + st := c.one(p) + mu.Lock() + out[p.kind] = st + mu.Unlock() + }() + } + wg.Wait() + c.mu.Lock() + c.last, c.at = out, time.Now() + c.mu.Unlock() + return out +} diff --git a/internal/dock/session.go b/internal/dock/session.go new file mode 100644 index 0000000..abc6b16 --- /dev/null +++ b/internal/dock/session.go @@ -0,0 +1,376 @@ +package dock + +import ( + "crypto/rand" + "encoding/hex" + "errors" + "net/http" + "os" + "os/exec" + "runtime" + "strconv" + "strings" + "sync" + "unicode/utf8" + + "github.com/creack/pty" + + "github.com/nodemode-ai/formledger/internal/httpx" +) + +const ( + scrollbackMax = 256 << 10 + maxSessions = 16 + maxSockets = 24 + subQueue = 1024 + minCols = 10 + minRows = 4 + maxCols = 500 + maxRows = 200 +) + +var ( + errNoSession = httpx.Fail(http.StatusNotFound, "no_terminal", "there is no such terminal") + errTooMany = httpx.Fail(http.StatusTooManyRequests, "too_many_terminals", "close a terminal tab before opening another") + errNoPTY = httpx.Fail(http.StatusNotImplemented, "pty_unsupported", "terminals need a pseudo-terminal, which FormLedger does not have on "+runtime.GOOS+" yet") +) + +type frame struct { + text string + exit bool +} + +type sub struct { + ch chan frame + once sync.Once +} + +func (s *sub) end() { s.once.Do(func() { close(s.ch) }) } + +type launch struct { + argv []string + env []string + dir string +} + +type session struct { + id, title, kind, owner string + spec launch + onClose []func() + + mu sync.Mutex + tty *os.File + cmd *exec.Cmd + gen int + alive bool + closed bool + cols, rows int + back []string + size int + subs map[*sub]struct{} +} + +type record struct { + ID string `json:"id"` + Title string `json:"title"` + Cwd string `json:"cwd"` + Alive bool `json:"alive"` + Kind string `json:"kind"` +} + +func clamp(v, lo, hi int) int { return max(lo, min(hi, v)) } + +func newID() string { + var b [6]byte + _, _ = rand.Read(b[:]) + return hex.EncodeToString(b[:]) +} + +func (s *session) describe() record { + s.mu.Lock() + defer s.mu.Unlock() + return record{ID: s.id, Title: s.title, Cwd: s.spec.dir, Alive: s.alive, Kind: s.kind} +} + +func (s *session) spawn() error { + cmd := exec.Command(s.spec.argv[0], s.spec.argv[1:]...) + cmd.Dir = s.spec.dir + cmd.Env = s.spec.env + tty, err := pty.StartWithSize(cmd, &pty.Winsize{Cols: uint16(s.cols), Rows: uint16(s.rows)}) + if errors.Is(err, pty.ErrUnsupported) { + return errNoPTY + } + if err != nil { + return err + } + s.tty, s.cmd, s.alive = tty, cmd, true + go s.pump(tty, cmd, s.gen) + return nil +} + +func cut(data []byte) int { + for i := len(data) - 1; i >= 0 && i >= len(data)-utf8.UTFMax; i-- { + if utf8.RuneStart(data[i]) { + if !utf8.FullRune(data[i:]) { + return i + } + break + } + } + return len(data) +} + +func (s *session) pump(tty *os.File, cmd *exec.Cmd, gen int) { + buf := make([]byte, 32<<10) + var carry []byte + for { + n, err := tty.Read(buf) + if n > 0 { + data := append(carry, buf[:n]...) + at := cut(data) + if at > 0 { + s.emit(gen, strings.ToValidUTF8(string(data[:at]), "�")) + } + carry = append([]byte(nil), data[at:]...) + } + if err != nil { + break + } + } + _ = cmd.Wait() + s.mu.Lock() + defer s.mu.Unlock() + if s.gen != gen || s.closed { + return + } + s.alive = false + s.broadcast(frame{exit: true}) +} + +func (s *session) keep(text string) { + s.back = append(s.back, text) + s.size += len(text) + for s.size > scrollbackMax && len(s.back) > 1 { + s.size -= len(s.back[0]) + s.back = s.back[1:] + } +} + +func (s *session) broadcast(f frame) { + for x := range s.subs { + select { + case x.ch <- f: + default: + if f.exit { + delete(s.subs, x) + x.end() + } + } + } +} + +func (s *session) emit(gen int, text string) { + s.mu.Lock() + defer s.mu.Unlock() + if s.gen != gen || s.closed { + return + } + s.keep(text) + s.broadcast(frame{text: text}) +} + +func (s *session) stop() { + if s.tty != nil { + _ = s.tty.Close() + } + if s.cmd != nil && s.cmd.Process != nil { + _ = s.cmd.Process.Kill() + } + s.tty, s.cmd, s.alive = nil, nil, false +} + +func (s *session) restart() error { + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return errNoSession + } + s.gen++ + s.stop() + s.back, s.size = nil, 0 + if err := s.spawn(); err != nil { + return err + } + s.broadcast(frame{text: "\x1bc"}) + return nil +} + +func (s *session) write(data string) { + s.mu.Lock() + defer s.mu.Unlock() + if s.alive && s.tty != nil { + _, _ = s.tty.WriteString(data) + } +} + +func (s *session) resize(cols, rows int) { + s.mu.Lock() + defer s.mu.Unlock() + s.cols, s.rows = clamp(cols, minCols, maxCols), clamp(rows, minRows, maxRows) + if s.alive && s.tty != nil { + _ = pty.Setsize(s.tty, &pty.Winsize{Cols: uint16(s.cols), Rows: uint16(s.rows)}) + } +} + +func (s *session) attach() (*sub, string, bool) { + s.mu.Lock() + defer s.mu.Unlock() + x := &sub{ch: make(chan frame, subQueue)} + if s.closed { + x.end() + return x, "", false + } + s.subs[x] = struct{}{} + return x, strings.Join(s.back, ""), s.alive +} + +func (s *session) detach(x *sub) { + s.mu.Lock() + delete(s.subs, x) + s.mu.Unlock() + x.end() +} + +func (s *session) close() { + s.mu.Lock() + if s.closed { + s.mu.Unlock() + return + } + s.closed = true + s.gen++ + s.stop() + for x := range s.subs { + select { + case x.ch <- frame{exit: true}: + default: + } + x.end() + } + s.subs = nil + done := s.onClose + s.onClose = nil + s.mu.Unlock() + for _, f := range done { + f() + } +} + +type registry struct { + mu sync.Mutex + list []*session + sockets int +} + +func (g *registry) add(owner, kind, title string, spec launch, cols, rows int) (*session, error) { + g.mu.Lock() + defer g.mu.Unlock() + if len(g.list) >= maxSessions { + return nil, errTooMany + } + if title == "" { + n := 1 + for _, x := range g.list { + if x.kind == "shell" && x.owner == owner { + n++ + } + } + title = "Terminal " + strconv.Itoa(n) + } + s := &session{id: newID(), title: title, kind: kind, owner: owner, spec: spec, cols: clamp(cols, minCols, maxCols), rows: clamp(rows, minRows, maxRows), subs: map[*sub]struct{}{}} + s.mu.Lock() + err := s.spawn() + s.mu.Unlock() + if err != nil { + return nil, err + } + g.list = append(g.list, s) + return s, nil +} + +func (g *registry) get(id, owner string) (*session, error) { + g.mu.Lock() + defer g.mu.Unlock() + for _, s := range g.list { + if s.id == id && s.owner == owner { + return s, nil + } + } + return nil, errNoSession +} + +func (g *registry) mine(owner string) []record { + g.mu.Lock() + list := append([]*session(nil), g.list...) + g.mu.Unlock() + out := []record{} + for _, s := range list { + if s.owner == owner { + out = append(out, s.describe()) + } + } + return out +} + +func (g *registry) liveClaude(owner string) *session { + g.mu.Lock() + defer g.mu.Unlock() + for _, s := range g.list { + if s.owner == owner && s.kind == "claude" && s.describe().Alive { + return s + } + } + return nil +} + +func (g *registry) remove(id, owner string) { + g.mu.Lock() + var found *session + for i, s := range g.list { + if s.id == id && s.owner == owner { + found = s + g.list = append(g.list[:i], g.list[i+1:]...) + break + } + } + g.mu.Unlock() + if found != nil { + found.close() + } +} + +func (g *registry) closeAll() { + g.mu.Lock() + list := g.list + g.list = nil + g.mu.Unlock() + for _, s := range list { + s.close() + } +} + +func (g *registry) takeSocket() bool { + g.mu.Lock() + defer g.mu.Unlock() + if g.sockets >= maxSockets { + return false + } + g.sockets++ + return true +} + +func (g *registry) releaseSocket() { + g.mu.Lock() + g.sockets = max(0, g.sockets-1) + g.mu.Unlock() +} diff --git a/internal/dock/ws.go b/internal/dock/ws.go new file mode 100644 index 0000000..6ced2b0 --- /dev/null +++ b/internal/dock/ws.go @@ -0,0 +1,182 @@ +package dock + +import ( + "bufio" + "crypto/sha1" + "encoding/base64" + "encoding/binary" + "errors" + "io" + "net" + "net/http" + "strings" + "sync" + "time" + + "github.com/nodemode-ai/formledger/internal/httpx" +) + +const ( + wsGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + wsMaxFrame = 1 << 20 + wsWriteWait = 10 * time.Second + opCont = 0x0 + opText = 0x1 + opBinary = 0x2 + opClose = 0x8 + opPing = 0x9 + opPong = 0xA +) + +var errWSClosed = errors.New("dock: websocket closed") + +type wsConn struct { + c net.Conn + br *bufio.Reader + mu sync.Mutex + once sync.Once +} + +func headerHas(h http.Header, name, token string) bool { + for _, v := range h.Values(name) { + for _, part := range strings.Split(v, ",") { + if strings.EqualFold(strings.TrimSpace(part), token) { + return true + } + } + } + return false +} + +func upgradeCheck(r *http.Request) error { + if !headerHas(r.Header, "Connection", "upgrade") || !strings.EqualFold(r.Header.Get("Upgrade"), "websocket") { + return httpx.Fail(http.StatusBadRequest, "not_websocket", "this address takes a WebSocket") + } + if r.Header.Get("Sec-WebSocket-Version") != "13" { + return httpx.Fail(http.StatusUpgradeRequired, "websocket_version", "WebSocket version 13 is required") + } + if k, err := base64.StdEncoding.DecodeString(r.Header.Get("Sec-WebSocket-Key")); err != nil || len(k) != 16 { + return httpx.Fail(http.StatusBadRequest, "websocket_key", "the WebSocket key is missing or malformed") + } + return nil +} + +func upgrade(w http.ResponseWriter, r *http.Request) (*wsConn, error) { + conn, brw, err := http.NewResponseController(w).Hijack() + if err != nil { + return nil, err + } + sum := sha1.Sum([]byte(r.Header.Get("Sec-WebSocket-Key") + wsGUID)) + _ = conn.SetDeadline(time.Time{}) + _ = conn.SetWriteDeadline(time.Now().Add(wsWriteWait)) + _, err = brw.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " + base64.StdEncoding.EncodeToString(sum[:]) + "\r\n\r\n") + if err == nil { + err = brw.Flush() + } + if err != nil { + conn.Close() + return nil, err + } + _ = conn.SetWriteDeadline(time.Time{}) + return &wsConn{c: conn, br: brw.Reader}, nil +} + +func (c *wsConn) write(op byte, payload []byte) error { + c.mu.Lock() + defer c.mu.Unlock() + head := make([]byte, 2, 10) + head[0] = 0x80 | op + switch n := len(payload); { + case n < 126: + head[1] = byte(n) + case n <= 0xFFFF: + head[1] = 126 + head = binary.BigEndian.AppendUint16(head, uint16(n)) + default: + head[1] = 127 + head = binary.BigEndian.AppendUint64(head, uint64(n)) + } + _ = c.c.SetWriteDeadline(time.Now().Add(wsWriteWait)) + if _, err := c.c.Write(append(head, payload...)); err != nil { + c.close() + return err + } + return nil +} + +func (c *wsConn) read() (byte, []byte, error) { + var msg []byte + var msgOp byte + for { + var h [2]byte + if _, err := io.ReadFull(c.br, h[:]); err != nil { + return 0, nil, err + } + fin, op, masked, n := h[0]&0x80 != 0, h[0]&0x0F, h[1]&0x80 != 0, uint64(h[1]&0x7F) + if !masked { + return 0, nil, errWSClosed + } + switch n { + case 126: + var b [2]byte + if _, err := io.ReadFull(c.br, b[:]); err != nil { + return 0, nil, err + } + n = uint64(binary.BigEndian.Uint16(b[:])) + case 127: + var b [8]byte + if _, err := io.ReadFull(c.br, b[:]); err != nil { + return 0, nil, err + } + n = binary.BigEndian.Uint64(b[:]) + } + if n > wsMaxFrame || uint64(len(msg))+n > wsMaxFrame { + return 0, nil, errWSClosed + } + var mask [4]byte + if _, err := io.ReadFull(c.br, mask[:]); err != nil { + return 0, nil, err + } + payload := make([]byte, n) + if _, err := io.ReadFull(c.br, payload); err != nil { + return 0, nil, err + } + for i := range payload { + payload[i] ^= mask[i%4] + } + switch op { + case opClose: + _ = c.write(opClose, payload[:min(2, len(payload))]) + return 0, nil, errWSClosed + case opPing: + if err := c.write(opPong, payload); err != nil { + return 0, nil, err + } + case opPong: + case opCont: + if msg == nil { + return 0, nil, errWSClosed + } + msg = append(msg, payload...) + if fin { + return msgOp, msg, nil + } + case opText, opBinary: + if fin { + return op, payload, nil + } + msgOp, msg = op, payload + default: + return 0, nil, errWSClosed + } + } +} + +func (c *wsConn) close() { + c.once.Do(func() { c.c.Close() }) +} + +func (c *wsConn) shut() { + _ = c.write(opClose, []byte{0x03, 0xE8}) + c.close() +} diff --git a/internal/server/server.go b/internal/server/server.go index 29724fd..56d0ebc 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -13,6 +13,7 @@ import ( "github.com/nodemode-ai/formledger/internal/config" "github.com/nodemode-ai/formledger/internal/customers" "github.com/nodemode-ai/formledger/internal/delivery" + "github.com/nodemode-ai/formledger/internal/dock" "github.com/nodemode-ai/formledger/internal/export" "github.com/nodemode-ai/formledger/internal/fiscal" "github.com/nodemode-ai/formledger/internal/invoicing" @@ -59,6 +60,7 @@ func Build(ctx context.Context, cfg config.Config, log *slog.Logger, st *store.S coa.Module(st, accounts), customers.Module(st, accounts), delivery.Module(st, accounts), + dock.Module(accounts), export.Module(), printout.Module(), fiscal.Module(accounts), diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 48a8323..ab4b8d9 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1106,7 +1106,7 @@ dependencies = [ [[package]] name = "formledger-desktop" -version = "0.14.0" +version = "0.15.0" dependencies = [ "objc2", "objc2-app-kit", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 9a166e0..67a63a9 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formledger-desktop" -version = "0.14.0" +version = "0.15.0" description = "FormLedger desktop app" authors = ["NodeAgentc, Inc."] license = "Apache-2.0" diff --git a/src-tauri/HASHOUT_LOG.md b/src-tauri/HASHOUT_LOG.md index 969efb4..0337d8c 100644 --- a/src-tauri/HASHOUT_LOG.md +++ b/src-tauri/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for the Tauri 2 desktop shell (`src-tauri`). Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of the shell: read it first, then edit code surgically. -Current build version: v0.14.0 +Current build version: v0.15.0 Last updated: 2026-11-26 (US Eastern) · the shell ported from form.md's src-tauri and renamed for FormLedger --- @@ -338,3 +338,18 @@ Ported from form.md `src-tauri/src/menu.rs` and its wiring in `src-tauri/src/mai - logged: v0.12.0 · 2026-11-27 Read against form.md's `menu.rs` and `main.rs` and the Tauri 2 menu builders it uses (`MenuItemBuilder::with_id`, `accelerator`, `build(app)`, `SubmenuBuilder` predefined items, `MenuBuilder::items`, `on_menu_event`, `MenuEvent::id`). Imports, types, builder calls and the handler are the same as form.md's apart from the `Submenu` import that `screens` needs and the `__formledgerRun` bridge name. Every `cmd:` id has a window command (the 26 `go.*` ids were each run through `__formledgerRun` on a built copy and each changed the route); `zoom:in`, `zoom:out`, `zoom:reset`, `app:reload` and `app:notices` are matched in `handle`, and the match has no arm without an item. Following form.md, Cmd or Ctrl+P is File > Search, which opens the palette (the window's Search button does the same); Print moved to Cmd or Ctrl+Alt+P, which form.md does not use; File's second "Find a Command..." without a key became that Search item, and Help keeps "Find a Command..." on Cmd or Ctrl+Shift+P. "Write Snapshot" lost its ellipsis because it now writes at once. `start` now passes `engine_start::key_home` to the sidecar with `.envs`. Not compiled: `cargo check --offline` in a private copy stopped at dependency resolution (no `tauri` crate in the local registry), before any source was read. + +### src/menu.rs, src/main.rs, build.rs, capabilities/main.json · the window's menu list on macOS, the bar in the window elsewhere +- refers-to: src/menu.rs :: build, apply_zoom, zoom, handle; src/main.rs :: main (invoke_handler, setup); build.rs :: AppManifest commands; capabilities/main.json :: permissions +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +From 0.15.0 the window owns its menus (`web/src/ui/menus.ts`): the in-window bar on Linux, Windows and the browser, and on macOS the system menu built by the page from the same list through `@tauri-apps/api/menu`. The shell keeps setting its own menu on macOS only (`if cfg!(target_os = "macos")` in `setup`, unchanged), as the menu that shows from launch until the page has drawn, and as the fallback if the page cannot build one; Tauri 2 makes no default menu on Linux or Windows, so no GTK or Win32 bar is drawn there and the window draws its own. Events from the shell's menu still reach the window through `cmd:` ids and `window.__formledgerRun`; items the page builds carry their own action callbacks, and their generated ids have no `cmd:` or `zoom:` prefix, so `handle` ignores them and nothing runs twice. + +Edits, one hand edit per region, removed lines quoted: +- menu.rs app menu: `.item(&item(app, "cmd:nav.account", "Settings...", Some("CmdOrCtrl+,"))?)` became `cmd:app.preferences`, "Preferences...", the new Preferences view, as in the page's list. +- menu.rs View and Go: `.item(&item(app, "cmd:nav.home", "Home", None)?)` (twice) became `cmd:app.home`, the new Home start screen. +- menu.rs `handle`: the inline zoom arm (`let zoom = app.state::(); let mut z = zoom.0.lock().unwrap(); *z = match id { "zoom:in" => step(*z, true), "zoom:out" => step(*z, false), _ => 1.0 }; let _ = window.set_zoom(*z);`) moved into `apply_zoom(app, window, how)`, shared with the new `zoom` command, so the page's View > Zoom In, Zoom Out and Actual Size step the same `Zoom` state and the same steps (0.67 to 1.75) as the shell's menu did. `zoom` refuses any step but `in`, `out` and `reset`. +- main.rs: `generate_handler![reveal::app_ready]` became `generate_handler![reveal::app_ready, menu::zoom]`. +- build.rs: the app manifest's commands `&["app_ready"]` became `&["app_ready", "zoom"]`, which makes the `allow-zoom` permission. +- capabilities/main.json (the remote capability for `http://127.0.0.1:*`): `"permissions": ["allow-app-ready"]` became `allow-app-ready`, `allow-zoom`, `core:menu:default` (build and set the app menu, set enabled and checked), and `core:window:allow-minimize`, `allow-toggle-maximize`, `allow-set-fullscreen`, `allow-is-fullscreen`, `allow-close` for the in-window Window menu and File > Close Window. The description says the same. diff --git a/src-tauri/build.rs b/src-tauri/build.rs index d0dc58b..6c9133d 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -1,6 +1,6 @@ fn main() { tauri_build::try_build( - tauri_build::Attributes::new().app_manifest(tauri_build::AppManifest::new().commands(&["app_ready"])), + tauri_build::Attributes::new().app_manifest(tauri_build::AppManifest::new().commands(&["app_ready", "zoom"])), ) .expect("failed to run the Tauri build step"); } diff --git a/src-tauri/capabilities/main.json b/src-tauri/capabilities/main.json index 4818b4a..2a84b18 100644 --- a/src-tauri/capabilities/main.json +++ b/src-tauri/capabilities/main.json @@ -1,8 +1,17 @@ { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "main-ready", - "description": "The main window shows the page the bundled server serves on 127.0.0.1, a remote origin to Tauri. It may call one command, app_ready, which tells the shell the page has drawn its first content.", + "description": "The main window shows the page the bundled server serves on 127.0.0.1, a remote origin to Tauri. It may call app_ready, which tells the shell the page has drawn its first content, and zoom, which steps the window's zoom for the View menu. It may build the macOS menu bar from the page's menu list (core:menu:default) and, for the in-window Window menu, minimize, maximize, go full screen and close its own window.", "windows": ["main"], "remote": { "urls": ["http://127.0.0.1:*"] }, - "permissions": ["allow-app-ready"] + "permissions": [ + "allow-app-ready", + "allow-zoom", + "core:menu:default", + "core:window:allow-minimize", + "core:window:allow-toggle-maximize", + "core:window:allow-set-fullscreen", + "core:window:allow-is-fullscreen", + "core:window:allow-close" + ] } diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 7a4e294..19ff8cc 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -355,7 +355,7 @@ fn main() { }) .manage(menu::Zoom(Mutex::new(1.0))) .on_menu_event(menu::handle) - .invoke_handler(tauri::generate_handler![reveal::app_ready]) + .invoke_handler(tauri::generate_handler![reveal::app_ready, menu::zoom]) .setup(|app| { reveal::round_splash(app.handle()); if cfg!(target_os = "macos") { diff --git a/src-tauri/src/menu.rs b/src-tauri/src/menu.rs index 70947a6..bb310a0 100644 --- a/src-tauri/src/menu.rs +++ b/src-tauri/src/menu.rs @@ -59,7 +59,7 @@ pub fn build(app: &AppHandle) -> tauri::Result> { let app_menu = SubmenuBuilder::new(app, "FormLedger") .about(None) .separator() - .item(&item(app, "cmd:nav.account", "Settings...", Some("CmdOrCtrl+,"))?) + .item(&item(app, "cmd:app.preferences", "Preferences...", Some("CmdOrCtrl+,"))?) .separator() .services() .separator() @@ -101,7 +101,7 @@ pub fn build(app: &AppHandle) -> tauri::Result> { .separator() .item(&item(app, "cmd:nav.back", "Back", Some("CmdOrCtrl+["))?) .item(&item(app, "cmd:nav.forward", "Forward", Some("CmdOrCtrl+]"))?) - .item(&item(app, "cmd:nav.home", "Home", None)?) + .item(&item(app, "cmd:app.home", "Home", None)?) .item(&item(app, "cmd:go.dashboards", "Dashboards", None)?) .separator() .item(&item(app, "zoom:in", "Zoom In", Some("CmdOrCtrl+="))?) @@ -112,7 +112,7 @@ pub fn build(app: &AppHandle) -> tauri::Result> { .fullscreen() .build()?; let go = SubmenuBuilder::new(app, "Go") - .item(&item(app, "cmd:nav.home", "Home", None)?) + .item(&item(app, "cmd:app.home", "Home", None)?) .item(&item(app, "cmd:go.dashboards", "Dashboards", None)?) .item(&item(app, "cmd:go.templates", "Templates", None)?) .separator() @@ -147,6 +147,26 @@ fn step(current: f64, up: bool) -> f64 { } } +fn apply_zoom(app: &AppHandle, window: &tauri::WebviewWindow, how: &str) { + let zoom = app.state::(); + let mut z = zoom.0.lock().unwrap(); + *z = match how { + "in" => step(*z, true), + "out" => step(*z, false), + _ => 1.0, + }; + let _ = window.set_zoom(*z); +} + +#[tauri::command] +pub fn zoom(app: AppHandle, window: tauri::WebviewWindow, how: String) -> Result<(), String> { + if !matches!(how.as_str(), "in" | "out" | "reset") { + return Err(format!("unknown zoom step {how}")); + } + apply_zoom(&app, &window, &how); + Ok(()) +} + pub fn handle(app: &AppHandle, event: MenuEvent) { let Some(window) = app.get_webview_window("main") else { return; @@ -158,16 +178,7 @@ pub fn handle(app: &AppHandle, event: MenuEvent) { return; } match id { - "zoom:in" | "zoom:out" | "zoom:reset" => { - let zoom = app.state::(); - let mut z = zoom.0.lock().unwrap(); - *z = match id { - "zoom:in" => step(*z, true), - "zoom:out" => step(*z, false), - _ => 1.0, - }; - let _ = window.set_zoom(*z); - } + "zoom:in" | "zoom:out" | "zoom:reset" => apply_zoom(app, &window, &id[5..]), "app:reload" => { let _ = window.eval("location.reload()"); } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index ef6bae5..df17a0a 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "FormLedger", "mainBinaryName": "formledger-desktop", - "version": "0.14.0", + "version": "0.15.0", "identifier": "ai.nodemode.formledger", "build": { "frontendDist": "splash" }, "app": { diff --git a/templates/README.md b/templates/README.md new file mode 100644 index 0000000..026d0ca --- /dev/null +++ b/templates/README.md @@ -0,0 +1,32 @@ +# Document templates + +Starting points for FormLedger's Templates screen: each `.json` file here is one document template in exactly the shape `POST /api/templates` takes (`kind`, `name`, `description`, `category`, `termsDays`, `notes`, `lines`). Once loaded, a template shows on the Templates screen, and Use opens a new draft from it. + +| Kind | Files | +| --- | --- | +| Sales invoices (trades, services, food, products) | 20 | +| Quotes | 8 | +| Sales orders | 5 | +| Purchase orders | 6 | +| Supplier bills (purchase invoices) | 9 | + +Every line is a free line booked to an account of the starter chart (4100 Sales, 4900 Other income, 5100 Purchases and cost of sales, 5200 Freight in, 6100 Rent, 6300 Utilities, 6400 Office supplies, 6500 Bank charges), so a template loads into any company that started from the starter chart. Change the prices, quantities and words to your own once it is loaded. + +## Load one + +With FormLedger running and an app token in `FORMLEDGER_TOKEN` (`./formledger cli token` says how to make one): + +``` +curl -s -X POST http://127.0.0.1:8340/api/templates \ + -H "Authorization: Bearer $FORMLEDGER_TOKEN" -H "Content-Type: application/json" \ + --data @templates/consulting-day-rate.json +``` + +All of them: + +``` +for f in templates/*.json; do curl -s -o /dev/null -w "%{http_code} $f\n" -X POST http://127.0.0.1:8340/api/templates \ + -H "Authorization: Bearer $FORMLEDGER_TOKEN" -H "Content-Type: application/json" --data @"$f"; done +``` + +Licence Apache-2.0, as FormLedger. Written for FormLedger by nodemode.ai; no third-party content. diff --git a/templates/annual-subscription.json b/templates/annual-subscription.json new file mode 100644 index 0000000..100200a --- /dev/null +++ b/templates/annual-subscription.json @@ -0,0 +1,12 @@ +{ + "kind": "sales-invoice", + "name": "Annual subscription invoice", + "description": "A yearly licence or membership billed once, with extra seats on their own line.", + "category": "Subscriptions", + "termsDays": 30, + "notes": "Covers twelve months from the invoice date.", + "lines": [ + {"description": "Annual subscription, base plan", "quantityMilli": 1000, "unitPrice": 120000, "currentPrice": false, "account": "4100"}, + {"description": "Additional seats, per year", "quantityMilli": 3000, "unitPrice": 18000, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/bakery-wholesale.json b/templates/bakery-wholesale.json new file mode 100644 index 0000000..2ef3320 --- /dev/null +++ b/templates/bakery-wholesale.json @@ -0,0 +1,13 @@ +{ + "kind": "sales-invoice", + "name": "Bakery wholesale invoice (weekly)", + "description": "A week of bread and pastries delivered to a shop or cafe.", + "category": "Food and hospitality", + "termsDays": 14, + "notes": "Standing order, delivered before 7 each morning.", + "lines": [ + {"description": "Sourdough loaf", "quantityMilli": 42000, "unitPrice": 380, "currentPrice": false, "account": "4100"}, + {"description": "Butter croissant", "quantityMilli": 84000, "unitPrice": 140, "currentPrice": false, "account": "4100"}, + {"description": "Seeded rye loaf", "quantityMilli": 21000, "unitPrice": 420, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/bill-card-fees.json b/templates/bill-card-fees.json new file mode 100644 index 0000000..f00b577 --- /dev/null +++ b/templates/bill-card-fees.json @@ -0,0 +1,12 @@ +{ + "kind": "purchase-invoice", + "name": "Supplier bill: card terminal fees", + "description": "A monthly statement from a card payment provider, booked to bank charges.", + "category": "Overheads", + "termsDays": 0, + "notes": "", + "lines": [ + {"description": "Card terminal rental", "quantityMilli": 1000, "unitPrice": 1900, "currentPrice": false, "account": "6500"}, + {"description": "Transaction fees for the month", "quantityMilli": 1000, "unitPrice": 8600, "currentPrice": false, "account": "6500"} + ] +} diff --git a/templates/bill-cleaning.json b/templates/bill-cleaning.json new file mode 100644 index 0000000..a662065 --- /dev/null +++ b/templates/bill-cleaning.json @@ -0,0 +1,11 @@ +{ + "kind": "purchase-invoice", + "name": "Supplier bill: premises cleaning", + "description": "A contract cleaner's monthly bill for the shop or office.", + "category": "Overheads", + "termsDays": 30, + "notes": "", + "lines": [ + {"description": "Contract cleaning, per visit", "quantityMilli": 8000, "unitPrice": 6500, "currentPrice": false, "account": "6100"} + ] +} diff --git a/templates/bill-equipment-service.json b/templates/bill-equipment-service.json new file mode 100644 index 0000000..66186e3 --- /dev/null +++ b/templates/bill-equipment-service.json @@ -0,0 +1,12 @@ +{ + "kind": "purchase-invoice", + "name": "Supplier bill: equipment servicing", + "description": "A service visit for machines such as an espresso machine or a compressor.", + "category": "Overheads", + "termsDays": 30, + "notes": "", + "lines": [ + {"description": "Service visit and labour", "quantityMilli": 1000, "unitPrice": 14500, "currentPrice": false, "account": "6400"}, + {"description": "Seals, filters and parts", "quantityMilli": 1000, "unitPrice": 6800, "currentPrice": false, "account": "6400"} + ] +} diff --git a/templates/bill-freight.json b/templates/bill-freight.json new file mode 100644 index 0000000..a719f0c --- /dev/null +++ b/templates/bill-freight.json @@ -0,0 +1,12 @@ +{ + "kind": "purchase-invoice", + "name": "Supplier bill: inbound freight", + "description": "A haulier's bill for goods brought in, booked to freight in.", + "category": "Purchasing", + "termsDays": 14, + "notes": "", + "lines": [ + {"description": "Pallet delivery", "quantityMilli": 2000, "unitPrice": 8500, "currentPrice": false, "account": "5200"}, + {"description": "Tail-lift surcharge", "quantityMilli": 1000, "unitPrice": 2500, "currentPrice": false, "account": "5200"} + ] +} diff --git a/templates/bill-rent.json b/templates/bill-rent.json new file mode 100644 index 0000000..ac3f38a --- /dev/null +++ b/templates/bill-rent.json @@ -0,0 +1,12 @@ +{ + "kind": "purchase-invoice", + "name": "Supplier bill: monthly rent", + "description": "A landlord's monthly rent bill, booked to rent expense.", + "category": "Overheads", + "termsDays": 0, + "notes": "", + "lines": [ + {"description": "Rent for the month", "quantityMilli": 1000, "unitPrice": 150000, "currentPrice": false, "account": "6100"}, + {"description": "Service charge", "quantityMilli": 1000, "unitPrice": 12000, "currentPrice": false, "account": "6100"} + ] +} diff --git a/templates/bill-software.json b/templates/bill-software.json new file mode 100644 index 0000000..e924dfc --- /dev/null +++ b/templates/bill-software.json @@ -0,0 +1,12 @@ +{ + "kind": "purchase-invoice", + "name": "Supplier bill: software subscriptions", + "description": "Monthly software seats and storage, booked to office supplies.", + "category": "Overheads", + "termsDays": 0, + "notes": "", + "lines": [ + {"description": "Software seats, per user", "quantityMilli": 3000, "unitPrice": 2400, "currentPrice": false, "account": "6400"}, + {"description": "Cloud storage, 2 TB", "quantityMilli": 1000, "unitPrice": 1000, "currentPrice": false, "account": "6400"} + ] +} diff --git a/templates/bill-stock-purchase.json b/templates/bill-stock-purchase.json new file mode 100644 index 0000000..0ac4b63 --- /dev/null +++ b/templates/bill-stock-purchase.json @@ -0,0 +1,12 @@ +{ + "kind": "purchase-invoice", + "name": "Supplier bill: goods for resale", + "description": "A supplier's invoice for goods bought to sell, booked to purchases.", + "category": "Purchasing", + "termsDays": 30, + "notes": "", + "lines": [ + {"description": "Goods for resale", "quantityMilli": 20000, "unitPrice": 1250, "currentPrice": false, "account": "5100"}, + {"description": "Carriage", "quantityMilli": 1000, "unitPrice": 1500, "currentPrice": false, "account": "5200"} + ] +} diff --git a/templates/bill-subcontractor.json b/templates/bill-subcontractor.json new file mode 100644 index 0000000..8206013 --- /dev/null +++ b/templates/bill-subcontractor.json @@ -0,0 +1,11 @@ +{ + "kind": "purchase-invoice", + "name": "Supplier bill: subcontractor", + "description": "A freelancer or subcontractor billing days worked on a client project.", + "category": "Purchasing", + "termsDays": 30, + "notes": "Client project: ", + "lines": [ + {"description": "Subcontracted work, per day", "quantityMilli": 4000, "unitPrice": 52000, "currentPrice": false, "account": "5100"} + ] +} diff --git a/templates/bill-utilities.json b/templates/bill-utilities.json new file mode 100644 index 0000000..c8cf70b --- /dev/null +++ b/templates/bill-utilities.json @@ -0,0 +1,13 @@ +{ + "kind": "purchase-invoice", + "name": "Supplier bill: utilities", + "description": "Electricity, gas and water on one bill, booked to utilities.", + "category": "Overheads", + "termsDays": 14, + "notes": "", + "lines": [ + {"description": "Electricity", "quantityMilli": 1000, "unitPrice": 18000, "currentPrice": false, "account": "6300"}, + {"description": "Gas", "quantityMilli": 1000, "unitPrice": 9500, "currentPrice": false, "account": "6300"}, + {"description": "Water and drainage", "quantityMilli": 1000, "unitPrice": 4200, "currentPrice": false, "account": "6300"} + ] +} diff --git a/templates/bookkeeping-monthly.json b/templates/bookkeeping-monthly.json new file mode 100644 index 0000000..8dde3c5 --- /dev/null +++ b/templates/bookkeeping-monthly.json @@ -0,0 +1,12 @@ +{ + "kind": "sales-invoice", + "name": "Bookkeeping service (monthly)", + "description": "A monthly bookkeeping fee with payroll runs and year-end work as extra lines.", + "category": "Professional services", + "termsDays": 14, + "notes": "Monthly fee covers up to 150 transactions.", + "lines": [ + {"description": "Monthly bookkeeping and bank reconciliation", "quantityMilli": 1000, "unitPrice": 42000, "currentPrice": false, "account": "4100"}, + {"description": "Payroll run", "quantityMilli": 2000, "unitPrice": 6500, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/cleaning-contract-monthly.json b/templates/cleaning-contract-monthly.json new file mode 100644 index 0000000..dab4d4c --- /dev/null +++ b/templates/cleaning-contract-monthly.json @@ -0,0 +1,12 @@ +{ + "kind": "sales-invoice", + "name": "Office cleaning contract (monthly)", + "description": "Scheduled cleaning visits for a month, with consumables at a fixed charge.", + "category": "Trades and home services", + "termsDays": 30, + "notes": "Visits as scheduled in the service agreement.", + "lines": [ + {"description": "Cleaning visit, three hours", "quantityMilli": 12000, "unitPrice": 7800, "currentPrice": false, "account": "4100"}, + {"description": "Consumables and supplies", "quantityMilli": 1000, "unitPrice": 4500, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/consulting-day-rate.json b/templates/consulting-day-rate.json new file mode 100644 index 0000000..36318a4 --- /dev/null +++ b/templates/consulting-day-rate.json @@ -0,0 +1,12 @@ +{ + "kind": "sales-invoice", + "name": "Consulting invoice (day rate)", + "description": "Days of consulting at a day rate, with travel at cost on its own line.", + "category": "Professional services", + "termsDays": 30, + "notes": "Day rate as agreed in the engagement letter. Travel is billed at cost.", + "lines": [ + {"description": "Consulting, per day", "quantityMilli": 5000, "unitPrice": 95000, "currentPrice": false, "account": "4100"}, + {"description": "Travel and accommodation at cost", "quantityMilli": 1000, "unitPrice": 0, "currentPrice": false, "account": "4900"} + ] +} diff --git a/templates/craft-stockist.json b/templates/craft-stockist.json new file mode 100644 index 0000000..69de10f --- /dev/null +++ b/templates/craft-stockist.json @@ -0,0 +1,13 @@ +{ + "kind": "sales-invoice", + "name": "Handmade goods to a stockist", + "description": "Handmade products sold at trade price to a shop that resells them.", + "category": "Products", + "termsDays": 30, + "notes": "Trade prices. Recommended retail price is twice the trade price.", + "lines": [ + {"description": "Hand-thrown mug", "quantityMilli": 24000, "unitPrice": 1100, "currentPrice": false, "account": "4100"}, + {"description": "Linen tea towel", "quantityMilli": 30000, "unitPrice": 700, "currentPrice": false, "account": "4100"}, + {"description": "Packing and courier", "quantityMilli": 1000, "unitPrice": 1800, "currentPrice": false, "account": "4900"} + ] +} diff --git a/templates/design-milestone.json b/templates/design-milestone.json new file mode 100644 index 0000000..fa9b255 --- /dev/null +++ b/templates/design-milestone.json @@ -0,0 +1,11 @@ +{ + "kind": "sales-invoice", + "name": "Design project milestone invoice", + "description": "One stage of a fixed-price design project, named by milestone.", + "category": "Creative", + "termsDays": 14, + "notes": "Milestone billing as set out in the project proposal.", + "lines": [ + {"description": "Milestone 2 of 4: concepts and first round of changes", "quantityMilli": 1000, "unitPrice": 180000, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/electrical-job.json b/templates/electrical-job.json new file mode 100644 index 0000000..86e63b2 --- /dev/null +++ b/templates/electrical-job.json @@ -0,0 +1,13 @@ +{ + "kind": "sales-invoice", + "name": "Electrical installation invoice", + "description": "Labour, materials and the safety certificate for an installation job.", + "category": "Trades and home services", + "termsDays": 14, + "notes": "The installation certificate is sent with this invoice.", + "lines": [ + {"description": "Electrician, per hour", "quantityMilli": 8000, "unitPrice": 6800, "currentPrice": false, "account": "4100"}, + {"description": "Cable, fittings and consumer unit", "quantityMilli": 1000, "unitPrice": 0, "currentPrice": false, "account": "4100"}, + {"description": "Testing and installation certificate", "quantityMilli": 1000, "unitPrice": 9500, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/equipment-rental.json b/templates/equipment-rental.json new file mode 100644 index 0000000..2b70aed --- /dev/null +++ b/templates/equipment-rental.json @@ -0,0 +1,13 @@ +{ + "kind": "sales-invoice", + "name": "Equipment rental invoice", + "description": "Hire of equipment by the day, delivery and collection, and a damage waiver.", + "category": "Rental", + "termsDays": 7, + "notes": "Equipment remains our property and must be returned clean.", + "lines": [ + {"description": "Equipment hire, per day", "quantityMilli": 3000, "unitPrice": 6500, "currentPrice": false, "account": "4100"}, + {"description": "Delivery and collection", "quantityMilli": 1000, "unitPrice": 4000, "currentPrice": false, "account": "4100"}, + {"description": "Damage waiver", "quantityMilli": 1000, "unitPrice": 1500, "currentPrice": false, "account": "4900"} + ] +} diff --git a/templates/event-catering.json b/templates/event-catering.json new file mode 100644 index 0000000..61e838b --- /dev/null +++ b/templates/event-catering.json @@ -0,0 +1,13 @@ +{ + "kind": "sales-invoice", + "name": "Event catering invoice", + "description": "Food per guest, staff hours and equipment hire for an event.", + "category": "Food and hospitality", + "termsDays": 14, + "notes": "Final guest numbers as confirmed three days before the event.", + "lines": [ + {"description": "Buffet menu, per guest", "quantityMilli": 60000, "unitPrice": 2800, "currentPrice": false, "account": "4100"}, + {"description": "Serving staff, per hour", "quantityMilli": 12000, "unitPrice": 2600, "currentPrice": false, "account": "4100"}, + {"description": "Crockery, linen and urns hire", "quantityMilli": 1000, "unitPrice": 15000, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/freelance-writing.json b/templates/freelance-writing.json new file mode 100644 index 0000000..080d619 --- /dev/null +++ b/templates/freelance-writing.json @@ -0,0 +1,12 @@ +{ + "kind": "sales-invoice", + "name": "Freelance writing invoice", + "description": "Articles at a fee each, with research hours and image licensing passed on.", + "category": "Creative", + "termsDays": 30, + "notes": "First publication rights only, as agreed.", + "lines": [ + {"description": "Feature article, about 1500 words", "quantityMilli": 2000, "unitPrice": 45000, "currentPrice": false, "account": "4100"}, + {"description": "Research and interviews, per hour", "quantityMilli": 4000, "unitPrice": 5000, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/landscaping-visit.json b/templates/landscaping-visit.json new file mode 100644 index 0000000..9f6f4c8 --- /dev/null +++ b/templates/landscaping-visit.json @@ -0,0 +1,13 @@ +{ + "kind": "sales-invoice", + "name": "Garden maintenance visit", + "description": "Crew hours on site, green waste removal and plants supplied.", + "category": "Trades and home services", + "termsDays": 14, + "notes": "Green waste is taken to a composting site.", + "lines": [ + {"description": "Crew hours on site", "quantityMilli": 6000, "unitPrice": 5500, "currentPrice": false, "account": "4100"}, + {"description": "Green waste removal, per load", "quantityMilli": 1000, "unitPrice": 6000, "currentPrice": false, "account": "4100"}, + {"description": "Plants and materials supplied", "quantityMilli": 1000, "unitPrice": 0, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/order-made-to-order-furniture.json b/templates/order-made-to-order-furniture.json new file mode 100644 index 0000000..a9bd037 --- /dev/null +++ b/templates/order-made-to-order-furniture.json @@ -0,0 +1,13 @@ +{ + "kind": "sales-order", + "name": "Sales order: made-to-order furniture", + "description": "A commissioned piece with its finish and delivery, confirmed before making starts.", + "category": "Sales orders", + "termsDays": 14, + "notes": "Made to order in about six weeks. Finish samples are approved before making starts.", + "lines": [ + {"description": "Oak dining table, 1.8 m, made to order", "quantityMilli": 1000, "unitPrice": 185000, "currentPrice": false, "account": "4100"}, + {"description": "Hard wax oil finish", "quantityMilli": 1000, "unitPrice": 12000, "currentPrice": false, "account": "4100"}, + {"description": "Delivery and placement", "quantityMilli": 1000, "unitPrice": 9000, "currentPrice": false, "account": "4900"} + ] +} diff --git a/templates/order-print.json b/templates/order-print.json new file mode 100644 index 0000000..91c5457 --- /dev/null +++ b/templates/order-print.json @@ -0,0 +1,12 @@ +{ + "kind": "sales-order", + "name": "Sales order: confirmed print job", + "description": "A print job confirmed from an accepted quote, ready to produce and invoice.", + "category": "Sales orders", + "termsDays": 30, + "notes": "Confirmed against the signed-off proof.", + "lines": [ + {"description": "Flyers, A5, double sided", "quantityMilli": 2000000, "unitPrice": 6, "currentPrice": false, "account": "4100"}, + {"description": "Posters, A2", "quantityMilli": 50000, "unitPrice": 320, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/order-subscription-box.json b/templates/order-subscription-box.json new file mode 100644 index 0000000..98a526f --- /dev/null +++ b/templates/order-subscription-box.json @@ -0,0 +1,12 @@ +{ + "kind": "sales-order", + "name": "Sales order: quarterly subscription boxes", + "description": "Three monthly boxes for a customer, confirmed and invoiced as one order.", + "category": "Sales orders", + "termsDays": 7, + "notes": "Boxes ship in the first week of each month.", + "lines": [ + {"description": "Monthly box", "quantityMilli": 3000, "unitPrice": 3900, "currentPrice": false, "account": "4100"}, + {"description": "Postage, per box", "quantityMilli": 3000, "unitPrice": 450, "currentPrice": false, "account": "4900"} + ] +} diff --git a/templates/order-uniforms.json b/templates/order-uniforms.json new file mode 100644 index 0000000..ad4223b --- /dev/null +++ b/templates/order-uniforms.json @@ -0,0 +1,13 @@ +{ + "kind": "sales-order", + "name": "Sales order: staff uniforms", + "description": "Embroidered workwear by size, with a one-off setup charge for the logo.", + "category": "Sales orders", + "termsDays": 30, + "notes": "Sizes as listed on the customer's order form.", + "lines": [ + {"description": "Polo shirt, embroidered", "quantityMilli": 40000, "unitPrice": 1650, "currentPrice": false, "account": "4100"}, + {"description": "Fleece jacket, embroidered", "quantityMilli": 20000, "unitPrice": 3400, "currentPrice": false, "account": "4100"}, + {"description": "Logo digitising, one-off", "quantityMilli": 1000, "unitPrice": 4500, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/order-wholesale-beans.json b/templates/order-wholesale-beans.json new file mode 100644 index 0000000..872896a --- /dev/null +++ b/templates/order-wholesale-beans.json @@ -0,0 +1,12 @@ +{ + "kind": "sales-order", + "name": "Sales order: standing coffee order", + "description": "A monthly standing order of roasted beans for a cafe customer.", + "category": "Sales orders", + "termsDays": 30, + "notes": "Standing order, roasted and delivered on the first Monday of the month.", + "lines": [ + {"description": "Espresso blend, 1 kg bag", "quantityMilli": 20000, "unitPrice": 2200, "currentPrice": false, "account": "4100"}, + {"description": "Decaf, 1 kg bag", "quantityMilli": 4000, "unitPrice": 2400, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/photography-session.json b/templates/photography-session.json new file mode 100644 index 0000000..7746f4b --- /dev/null +++ b/templates/photography-session.json @@ -0,0 +1,13 @@ +{ + "kind": "sales-invoice", + "name": "Photography session invoice", + "description": "A session fee, edited images and prints, each on its own line.", + "category": "Creative", + "termsDays": 14, + "notes": "Images are licensed for the use agreed at booking.", + "lines": [ + {"description": "Session fee, half day", "quantityMilli": 1000, "unitPrice": 45000, "currentPrice": false, "account": "4100"}, + {"description": "Edited images", "quantityMilli": 20000, "unitPrice": 1500, "currentPrice": false, "account": "4100"}, + {"description": "Prints, 8 by 10 inches", "quantityMilli": 4000, "unitPrice": 2500, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/plumbing-callout.json b/templates/plumbing-callout.json new file mode 100644 index 0000000..05f39a8 --- /dev/null +++ b/templates/plumbing-callout.json @@ -0,0 +1,13 @@ +{ + "kind": "sales-invoice", + "name": "Plumbing call-out invoice", + "description": "A call-out charge, labour by the hour and parts fitted.", + "category": "Trades and home services", + "termsDays": 7, + "notes": "Parts carry the maker's warranty; our workmanship is guaranteed for 12 months.", + "lines": [ + {"description": "Call-out charge", "quantityMilli": 1000, "unitPrice": 8500, "currentPrice": false, "account": "4100"}, + {"description": "Labour, per hour", "quantityMilli": 2000, "unitPrice": 7000, "currentPrice": false, "account": "4100"}, + {"description": "Parts fitted", "quantityMilli": 1000, "unitPrice": 0, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/po-cafe-supplies.json b/templates/po-cafe-supplies.json new file mode 100644 index 0000000..67f6ec1 --- /dev/null +++ b/templates/po-cafe-supplies.json @@ -0,0 +1,13 @@ +{ + "kind": "purchase-order", + "name": "Purchase order: weekly cafe supplies", + "description": "Milk, cups and lids ordered each week from a catering supplier.", + "category": "Purchasing", + "termsDays": 30, + "notes": "Deliver before 8 in the morning, back door.", + "lines": [ + {"description": "Whole milk, 2 litre", "quantityMilli": 36000, "unitPrice": 165, "currentPrice": false, "account": "5100"}, + {"description": "Oat drink, 1 litre", "quantityMilli": 24000, "unitPrice": 190, "currentPrice": false, "account": "5100"}, + {"description": "Takeaway cups and lids, sleeve of 50", "quantityMilli": 10000, "unitPrice": 750, "currentPrice": false, "account": "5100"} + ] +} diff --git a/templates/po-hardware-restock.json b/templates/po-hardware-restock.json new file mode 100644 index 0000000..5829e50 --- /dev/null +++ b/templates/po-hardware-restock.json @@ -0,0 +1,13 @@ +{ + "kind": "purchase-order", + "name": "Purchase order: hardware restock", + "description": "Restocking tools and fixings from a trade wholesaler, with freight.", + "category": "Purchasing", + "termsDays": 30, + "notes": "Please quote this order number on the delivery note.", + "lines": [ + {"description": "Claw hammer, 16 oz", "quantityMilli": 24000, "unitPrice": 1100, "currentPrice": false, "account": "5100"}, + {"description": "Wood screws, box of 500", "quantityMilli": 60000, "unitPrice": 310, "currentPrice": false, "account": "5100"}, + {"description": "Freight, per pallet", "quantityMilli": 1000, "unitPrice": 8500, "currentPrice": false, "account": "5200"} + ] +} diff --git a/templates/po-office-supplies.json b/templates/po-office-supplies.json new file mode 100644 index 0000000..4d7af85 --- /dev/null +++ b/templates/po-office-supplies.json @@ -0,0 +1,13 @@ +{ + "kind": "purchase-order", + "name": "Purchase order: office supplies", + "description": "Paper, toner and stationery for the office, booked to office supplies.", + "category": "Purchasing", + "termsDays": 30, + "notes": "", + "lines": [ + {"description": "Copier paper, box of five reams", "quantityMilli": 4000, "unitPrice": 2600, "currentPrice": false, "account": "6400"}, + {"description": "Toner cartridge, black", "quantityMilli": 2000, "unitPrice": 7800, "currentPrice": false, "account": "6400"}, + {"description": "Notebooks, pens and folders", "quantityMilli": 1000, "unitPrice": 4500, "currentPrice": false, "account": "6400"} + ] +} diff --git a/templates/po-packaging.json b/templates/po-packaging.json new file mode 100644 index 0000000..8db7928 --- /dev/null +++ b/templates/po-packaging.json @@ -0,0 +1,13 @@ +{ + "kind": "purchase-order", + "name": "Purchase order: packaging", + "description": "Boxes, mailers and labels for shipping orders to customers.", + "category": "Purchasing", + "termsDays": 30, + "notes": "", + "lines": [ + {"description": "Shipping box, medium, pack of 50", "quantityMilli": 10000, "unitPrice": 2900, "currentPrice": false, "account": "5100"}, + {"description": "Paper mailer, pack of 100", "quantityMilli": 5000, "unitPrice": 3400, "currentPrice": false, "account": "5100"}, + {"description": "Shipping labels, roll of 500", "quantityMilli": 4000, "unitPrice": 1600, "currentPrice": false, "account": "5100"} + ] +} diff --git a/templates/po-wholesale-produce.json b/templates/po-wholesale-produce.json new file mode 100644 index 0000000..e6b1030 --- /dev/null +++ b/templates/po-wholesale-produce.json @@ -0,0 +1,13 @@ +{ + "kind": "purchase-order", + "name": "Purchase order: kitchen produce", + "description": "Fresh produce and dry goods for a restaurant or bakery kitchen.", + "category": "Purchasing", + "termsDays": 14, + "notes": "Chilled items delivered at 5 degrees or below.", + "lines": [ + {"description": "Strong bread flour, 16 kg sack", "quantityMilli": 10000, "unitPrice": 1450, "currentPrice": false, "account": "5100"}, + {"description": "Unsalted butter, 10 kg block", "quantityMilli": 3000, "unitPrice": 8900, "currentPrice": false, "account": "5100"}, + {"description": "Free-range eggs, tray of 30", "quantityMilli": 12000, "unitPrice": 720, "currentPrice": false, "account": "5100"} + ] +} diff --git a/templates/po-workshop-materials.json b/templates/po-workshop-materials.json new file mode 100644 index 0000000..02f7288 --- /dev/null +++ b/templates/po-workshop-materials.json @@ -0,0 +1,13 @@ +{ + "kind": "purchase-order", + "name": "Purchase order: workshop raw materials", + "description": "Timber, finishes and abrasives for a joinery or furniture workshop.", + "category": "Purchasing", + "termsDays": 30, + "notes": "Timber kiln dried to 10 percent or less.", + "lines": [ + {"description": "Oak board, per cubic metre", "quantityMilli": 1500, "unitPrice": 165000, "currentPrice": false, "account": "5100"}, + {"description": "Hard wax oil, 2.5 litre", "quantityMilli": 4000, "unitPrice": 6200, "currentPrice": false, "account": "5100"}, + {"description": "Sanding discs, box of 100", "quantityMilli": 6000, "unitPrice": 2400, "currentPrice": false, "account": "5100"} + ] +} diff --git a/templates/quote-catering.json b/templates/quote-catering.json new file mode 100644 index 0000000..cca812c --- /dev/null +++ b/templates/quote-catering.json @@ -0,0 +1,13 @@ +{ + "kind": "quote", + "name": "Quote: event catering", + "description": "Menu per guest, staff and hire for an event, for the customer to confirm.", + "category": "Quotes", + "termsDays": 14, + "notes": "Valid for 14 days. A 30 percent deposit secures the date.", + "lines": [ + {"description": "Canapes, six per guest", "quantityMilli": 80000, "unitPrice": 1200, "currentPrice": false, "account": "4100"}, + {"description": "Main buffet, per guest", "quantityMilli": 80000, "unitPrice": 2400, "currentPrice": false, "account": "4100"}, + {"description": "Serving staff, per hour", "quantityMilli": 16000, "unitPrice": 2600, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/quote-event-photography.json b/templates/quote-event-photography.json new file mode 100644 index 0000000..ad1a84e --- /dev/null +++ b/templates/quote-event-photography.json @@ -0,0 +1,13 @@ +{ + "kind": "quote", + "name": "Quote: event photography", + "description": "Coverage by the hour, an edited gallery and an optional printed album.", + "category": "Quotes", + "termsDays": 30, + "notes": "Valid for 30 days. The album is optional and can be removed.", + "lines": [ + {"description": "Photographer, per hour of coverage", "quantityMilli": 6000, "unitPrice": 15000, "currentPrice": false, "account": "4100"}, + {"description": "Edited online gallery", "quantityMilli": 1000, "unitPrice": 35000, "currentPrice": false, "account": "4100"}, + {"description": "Printed album, 30 pages", "quantityMilli": 1000, "unitPrice": 42000, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/quote-garden-design.json b/templates/quote-garden-design.json new file mode 100644 index 0000000..9bf64cf --- /dev/null +++ b/templates/quote-garden-design.json @@ -0,0 +1,13 @@ +{ + "kind": "quote", + "name": "Quote: garden design and planting", + "description": "A planting plan, ground preparation and plants for a garden.", + "category": "Quotes", + "termsDays": 30, + "notes": "Valid for 30 days. Plant prices may change with the season.", + "lines": [ + {"description": "Site survey and planting plan", "quantityMilli": 1000, "unitPrice": 48000, "currentPrice": false, "account": "4100"}, + {"description": "Ground preparation, per square metre", "quantityMilli": 60000, "unitPrice": 900, "currentPrice": false, "account": "4100"}, + {"description": "Plants, supplied and planted", "quantityMilli": 1000, "unitPrice": 120000, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/quote-it-support.json b/templates/quote-it-support.json new file mode 100644 index 0000000..d1c712c --- /dev/null +++ b/templates/quote-it-support.json @@ -0,0 +1,12 @@ +{ + "kind": "quote", + "name": "Quote: IT support contract", + "description": "A yearly support contract per device, with onboarding as a one-off line.", + "category": "Quotes", + "termsDays": 30, + "notes": "Valid for 30 days. Response within four working hours.", + "lines": [ + {"description": "Support per device, per month, for 12 months", "quantityMilli": 180000, "unitPrice": 2500, "currentPrice": false, "account": "4100"}, + {"description": "Onboarding and device audit", "quantityMilli": 1000, "unitPrice": 60000, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/quote-kitchen-refit.json b/templates/quote-kitchen-refit.json new file mode 100644 index 0000000..ebf6920 --- /dev/null +++ b/templates/quote-kitchen-refit.json @@ -0,0 +1,14 @@ +{ + "kind": "quote", + "name": "Quote: kitchen refit", + "description": "Strip-out, fitting, worktops and making good, priced as separate stages.", + "category": "Quotes", + "termsDays": 30, + "notes": "Valid for 30 days. Appliances are supplied by the customer unless listed.", + "lines": [ + {"description": "Strip-out and disposal of the old kitchen", "quantityMilli": 1000, "unitPrice": 65000, "currentPrice": false, "account": "4100"}, + {"description": "Fit units, per linear metre", "quantityMilli": 6000, "unitPrice": 18000, "currentPrice": false, "account": "4100"}, + {"description": "Worktops, supplied and fitted", "quantityMilli": 1000, "unitPrice": 140000, "currentPrice": false, "account": "4100"}, + {"description": "Plastering, tiling and making good", "quantityMilli": 1000, "unitPrice": 90000, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/quote-moving.json b/templates/quote-moving.json new file mode 100644 index 0000000..d61506c --- /dev/null +++ b/templates/quote-moving.json @@ -0,0 +1,13 @@ +{ + "kind": "quote", + "name": "Quote: house or office move", + "description": "Crew and van by the hour, packing materials and insurance cover.", + "category": "Quotes", + "termsDays": 14, + "notes": "Valid for 14 days. Hours beyond the estimate are billed at the same rate.", + "lines": [ + {"description": "Van and crew of three, per hour", "quantityMilli": 7000, "unitPrice": 11000, "currentPrice": false, "account": "4100"}, + {"description": "Boxes, tape and wrapping", "quantityMilli": 1000, "unitPrice": 8500, "currentPrice": false, "account": "4100"}, + {"description": "Goods in transit cover", "quantityMilli": 1000, "unitPrice": 4000, "currentPrice": false, "account": "4900"} + ] +} diff --git a/templates/quote-print-run.json b/templates/quote-print-run.json new file mode 100644 index 0000000..e6eaac2 --- /dev/null +++ b/templates/quote-print-run.json @@ -0,0 +1,13 @@ +{ + "kind": "quote", + "name": "Quote: print run", + "description": "Printed matter by quantity, with proofs and delivery.", + "category": "Quotes", + "termsDays": 14, + "notes": "Valid for 14 days. Printing starts once the proof is signed off.", + "lines": [ + {"description": "Booklet, 24 pages, A5, full colour", "quantityMilli": 500000, "unitPrice": 185, "currentPrice": false, "account": "4100"}, + {"description": "Printed proof", "quantityMilli": 1000, "unitPrice": 2500, "currentPrice": false, "account": "4100"}, + {"description": "Delivery to one address", "quantityMilli": 1000, "unitPrice": 3000, "currentPrice": false, "account": "4900"} + ] +} diff --git a/templates/quote-website-build.json b/templates/quote-website-build.json new file mode 100644 index 0000000..872cf93 --- /dev/null +++ b/templates/quote-website-build.json @@ -0,0 +1,14 @@ +{ + "kind": "quote", + "name": "Quote: website build", + "description": "A small business website: design, build, content entry and launch.", + "category": "Quotes", + "termsDays": 30, + "notes": "This quote is valid for 30 days. Half is invoiced on acceptance, half at launch.", + "lines": [ + {"description": "Design, home page and two page layouts", "quantityMilli": 1000, "unitPrice": 160000, "currentPrice": false, "account": "4100"}, + {"description": "Build, up to eight pages", "quantityMilli": 1000, "unitPrice": 220000, "currentPrice": false, "account": "4100"}, + {"description": "Content entry, per page", "quantityMilli": 8000, "unitPrice": 4500, "currentPrice": false, "account": "4100"}, + {"description": "Launch and one month of support", "quantityMilli": 1000, "unitPrice": 30000, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/repair-parts-labour.json b/templates/repair-parts-labour.json new file mode 100644 index 0000000..6b48a58 --- /dev/null +++ b/templates/repair-parts-labour.json @@ -0,0 +1,13 @@ +{ + "kind": "sales-invoice", + "name": "Repair invoice (parts and labour)", + "description": "A workshop repair with diagnosis, labour and parts on separate lines.", + "category": "Repairs", + "termsDays": 0, + "notes": "Payable on collection. Repairs are guaranteed for 90 days.", + "lines": [ + {"description": "Diagnosis", "quantityMilli": 1000, "unitPrice": 3500, "currentPrice": false, "account": "4100"}, + {"description": "Workshop labour, per hour", "quantityMilli": 1500, "unitPrice": 6000, "currentPrice": false, "account": "4100"}, + {"description": "Replacement parts", "quantityMilli": 1000, "unitPrice": 0, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/trade-counter.json b/templates/trade-counter.json new file mode 100644 index 0000000..d425c17 --- /dev/null +++ b/templates/trade-counter.json @@ -0,0 +1,13 @@ +{ + "kind": "sales-invoice", + "name": "Trade counter account invoice", + "description": "Building supplies collected on a trade account, with the job reference in the notes.", + "category": "Products", + "termsDays": 30, + "notes": "Job reference: ", + "lines": [ + {"description": "Timber, 2 by 4, 2.4 m", "quantityMilli": 40000, "unitPrice": 650, "currentPrice": false, "account": "4100"}, + {"description": "Wood screws, box of 500", "quantityMilli": 4000, "unitPrice": 899, "currentPrice": false, "account": "4100"}, + {"description": "Plasterboard sheet", "quantityMilli": 20000, "unitPrice": 1150, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/translation-per-word.json b/templates/translation-per-word.json new file mode 100644 index 0000000..09b6440 --- /dev/null +++ b/templates/translation-per-word.json @@ -0,0 +1,13 @@ +{ + "kind": "sales-invoice", + "name": "Translation invoice (per word)", + "description": "Words translated at a per-word rate, with proofreading and a rush fee line.", + "category": "Professional services", + "termsDays": 30, + "notes": "Word count taken from the source document.", + "lines": [ + {"description": "Translation, per source word", "quantityMilli": 4200000, "unitPrice": 12, "currentPrice": false, "account": "4100"}, + {"description": "Proofreading by a second translator", "quantityMilli": 1000, "unitPrice": 9000, "currentPrice": false, "account": "4100"}, + {"description": "Rush delivery within 48 hours", "quantityMilli": 1000, "unitPrice": 0, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/tutoring-package.json b/templates/tutoring-package.json new file mode 100644 index 0000000..6e69af7 --- /dev/null +++ b/templates/tutoring-package.json @@ -0,0 +1,12 @@ +{ + "kind": "sales-invoice", + "name": "Tutoring package invoice", + "description": "A block of lessons paid in advance, with learning materials.", + "category": "Education", + "termsDays": 7, + "notes": "Lessons cancelled with less than 24 hours' notice are counted as taken.", + "lines": [ + {"description": "One-to-one lesson, 60 minutes", "quantityMilli": 10000, "unitPrice": 4500, "currentPrice": false, "account": "4100"}, + {"description": "Workbooks and practice papers", "quantityMilli": 1000, "unitPrice": 2400, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/web-care-monthly.json b/templates/web-care-monthly.json new file mode 100644 index 0000000..15ac5f0 --- /dev/null +++ b/templates/web-care-monthly.json @@ -0,0 +1,13 @@ +{ + "kind": "sales-invoice", + "name": "Website hosting and care plan (monthly)", + "description": "Hosting, updates and a block of support hours, billed each month in advance.", + "category": "Subscriptions", + "termsDays": 14, + "notes": "Billed monthly in advance. Unused support hours do not carry over.", + "lines": [ + {"description": "Managed hosting, one site", "quantityMilli": 1000, "unitPrice": 4500, "currentPrice": false, "account": "4100"}, + {"description": "Updates, backups and monitoring", "quantityMilli": 1000, "unitPrice": 6000, "currentPrice": false, "account": "4100"}, + {"description": "Support hours included", "quantityMilli": 2000, "unitPrice": 7500, "currentPrice": false, "account": "4100"} + ] +} diff --git a/templates/wholesale-coffee.json b/templates/wholesale-coffee.json new file mode 100644 index 0000000..b1425b6 --- /dev/null +++ b/templates/wholesale-coffee.json @@ -0,0 +1,13 @@ +{ + "kind": "sales-invoice", + "name": "Wholesale coffee invoice", + "description": "Roasted beans by the kilogram for a cafe or office, with delivery.", + "category": "Food and hospitality", + "termsDays": 30, + "notes": "Roasted to order. Best within six weeks of the roast date.", + "lines": [ + {"description": "Espresso blend, 1 kg bag", "quantityMilli": 12000, "unitPrice": 2200, "currentPrice": false, "account": "4100"}, + {"description": "Single origin filter, 1 kg bag", "quantityMilli": 4000, "unitPrice": 2800, "currentPrice": false, "account": "4100"}, + {"description": "Delivery", "quantityMilli": 1000, "unitPrice": 1200, "currentPrice": false, "account": "4900"} + ] +} diff --git a/web/HASHOUT_LOG.md b/web/HASHOUT_LOG.md index c6eaf9f..dc0ef99 100644 --- a/web/HASHOUT_LOG.md +++ b/web/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for the web client. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of the web side: read it first, then edit code surgically. -Current build version: v0.14.0 +Current build version: v0.15.0 Last updated: 2026-11-26 (US Eastern) · account screens, and the fixes from the throttled browser check --- @@ -775,3 +775,188 @@ The server sends `style-src 'self'`, which blocks every `style` attribute, so th - logged: v0.14.0 · 2026-11-27 A line with no item now shows the account the server will use, "5100 Purchases and cost of sales" on buying and "4100 Sales" on selling, read from the account lookup once and written by `refreshHints`; the codes mirror the server defaults, so if the owner changes `purchase.expense_account` or `sales.income_account` the hint still names 5100 or 4100. A refusal that starts "line N" also lands on that line's error tag. `put` writes the data of the cell's one text node instead of replacing it; that alone left 0.00007 with input, because right-aligned text that grows a digit moves its start point, and the price input's inner text is replaced by the browser on select-all. Numeric cells, inputs and totals are `direction: rtl` with `unicode-bidi: plaintext`, which keeps the anchor at the right edge and leaves the reading order of the number as typed. Policy enforced, no bypass, 4x CPU, 400 ms, 50000 B/s, cache off, hard reload, 1400 by 900, blank purchase and sales invoices: load 0 and 0, typing "Courier fee", 1, then 42.50 after select-all 0 and 0, Post 0 and 0, 0 violations; PI-2026-000001 posted 5100 debit 42.50 against 2110, SI-2026-000001 posted 1200 against 4100 credit 42.50. The exit script's twenty-line invoice posted with 0 and 0 on every step. + +## aesthetic · family tokens, one layer scale, glass popovers (0.15.0, L3) + +### src/ui/theme/tokens.css · the family token names mapped onto FormLedger's own +- refers-to: src/ui/theme/tokens.css :: the layer scale block, the family alias block, the light block +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +FormVis's `tokens.css` (the family sheet) names its colours `--accent-color`, `--bg-primary`, `--bg-secondary`, `--bg-tertiary`, `--text-primary`, `--text-secondary`, `--border-color`, `--border-light`, `--surface-*`, `--line-*`, `--glass-*`, `--ctl-*`, `--fs-*` and `--z-*`; FormLedger names the same roles `--accent`, `--sheet`, `--surface`, `--surface-2`, `--text`, `--border`, `--border-strong`. The family names are added as aliases in a second `:root` block, so a stylesheet written for the family (the menu bar, Home, Preferences, the dock) resolves in FormLedger, and no existing rule reads a new name, so no existing component changes colour. The mapping: `--bg-primary` is the sheet, `--bg-secondary` the sidebar surface, `--bg-tertiary` and `--bg-input` the second surface, `--border-color` the quiet border, `--border-light` the strong border, `--text-secondary` a mix between `--text` and `--text-muted`. Names that FormLedger already owns with a different value were kept, not redefined: `--text-muted` (family value is dimmer), `--radius-xs`, `--radius-sm`, `--radius` (3, 4 and 6 in the family; 4, 6 and 8 here, kept so no corner moves), `--space-1` to `--space-8` except the two missing steps `--space-5` and `--space-7` that were added, `--font-mono`, `--accent-wash`, `--danger`, `--success`, `--warning` and `--info`. Added without a clash: `--radius-md`, `--radius-lg`, `--radius-xl`, `--radius-pill`, `--fs-9` to `--fs-18`, `--font-ui`, `--ctl-sm` to `--ctl-xl`, `--shadow-sm` to `--shadow-window`, `--transition-*`, `--ease-glass`, the glass set (`--glass-bg`, `--glass-border`, `--glass-highlight`, `--glass-filter`, `--glass-shadow`) with the family's values, and the semantic `--ok`, `--warn`, `--danger-soft`, `--danger-text`, fills. `--shadow-md` is the exception to the family value: `grid.css` reads `var(--shadow-md, 0 4px 16px rgb(0 0 0 / 0.2))` for the picker, and defining the family's 0.4 would have darkened it, so the token carries the old fallback. Debit and credit colours, chart series and the status colours (`--success`, `--warning`, `--danger`, `--info`) are untouched; the accent stays FormLedger's `#9a8cff` (`#5a46e0` in light). + +Light mode follows the family's approach (an override layer over the same names, a lighter and warmer shadow set, a warm scrim, the CTA flipped to the text colour, the group head on the second surface) but keyed on the app's own `:root[data-theme="light"]`, which `index.html` sets before first paint, not on `body.theme-light`. A second `:root[data-theme="light"]` block follows the existing one and overrides only the derived tokens that need to differ: `--group-head`, `--line-0`, `--surface-raised`, `--cta-*`, `--bg-input`, `--bg-scrim`, the soft status tints, `--shadow-sm`, `--shadow-lg`, `--shadow-window`, `--glass-bg`, `--glass-shadow`. They are on the same element as the base light values, so every `color-mix` re-resolves with the light inputs. The family's `light-mode.css` is two lines (menu, dialog and toast shadows under `body.theme-light`); the same effect comes from `--glass-shadow` and `--shadow-lg` here, so no `light-mode.css` file was added. + +### src/ui/theme/tokens.css, src/styles/*.css · one z-index scale +- refers-to: src/ui/theme/tokens.css :: the layer scale; src/styles/palette.css :: .cpal-scrim, .cpal; src/styles/key-notice.css :: .keynote; src/styles/views/grid.css :: .picker-layer; src/styles/overlays.css :: .menu +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +No raw `z-index` number existed in any stylesheet or in a `style` string; all ten uses already read `var(--z-*)`, so nothing was swapped for a number. What changed is the scale behind the names, which is now the family's (`--z-under` -1, `--z-base` 0, `--z-local-2/4/5`, `--z-raised` 8, `--z-selected` 9, `--z-rail` 10, `--z-chrome` 100, `--z-menu` 200, `--z-temp` 500, `--z-companion` 800, `--z-taskbar` 900, `--z-modal` 1000, `--z-settings` 1500, `--z-context` 2000, `--z-toast` 3000, `--z-portal` 4000, `--z-home` 10000 and its three neighbours, `--z-overlay` 50000, `--z-overlay-modal` 60000, `--z-debug` 100000). Two names are new to it: `--z-sticky` (9, the sticky grid head over `--z-raised` 8, as 200 over 100 before) and `--z-dock` (850, above `--z-companion` and below `--z-taskbar`, `--z-modal` and the menu popups, so the command palette and every menu draw over the dock). The menu layer for the in-window bar is `--z-menu` (200), the dock layer is `--z-dock` (850). Relative order of every pair that existed is kept (chrome, scrim, palette, popovers, toast). The four old names with no family equivalent were remapped, one hand edit each, removed lines quoted: +- `palette.css` `.cpal-scrim`: `z-index: var(--z-scrim);` became `z-index: calc(var(--z-modal) - 1);` +- `palette.css` `.cpal`: `z-index: var(--z-overlay);` became `z-index: var(--z-modal);` (the name `--z-overlay` now means the family's 50000 and would have lifted the palette over everything) +- `key-notice.css` `.keynote`, `grid.css` `.picker-layer`, `overlays.css` `.menu`: `z-index: var(--z-popover);` became `z-index: var(--z-context);` in each, still over the palette and under the toast +The old `--z-dropdown`, `--z-tooltip`, `--z-popover` and `--z-scrim` were removed from the scale; nothing else read them (grep over `src/`). + +### src/styles/scrollbars.css, base.css, main.css · scrollbars as FormVis +- refers-to: src/styles/scrollbars.css; src/styles/base.css; src/styles/main.css +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +FormVis draws no scrollbar anywhere and says so in `scrollbars.css`; FormLedger already did the same in two rules at the top of `base.css`, which were removed from there (`* { scrollbar-width: none !important; }` and `*::-webkit-scrollbar { display: none !important; }`) and written in the family form in a new `scrollbars.css`, imported straight after `base.css`: `-ms-overflow-style`, the button, track, thumb and corner pseudo-elements, and `html, body`. Scrolling by wheel, trackpad, touch and keys is unchanged. The sidebar's `scrollbar-width: thin` and `scrollbar-gutter: stable` in `shell.css` were already overridden by the `!important` rule and reserve no space; left as they are. Fonts: FormVis loads Inter and JetBrains Mono through `@fontsource`; FormLedger bundles Inter Variable as woff2 (`src/fonts/`) and no mono face, so its own fonts stay and the system mono stack remains `--font-mono`. + +### src/styles/overlays.css, palette.css · glass on the menu and the palette +- refers-to: src/styles/overlays.css :: .menu; src/styles/palette.css :: .cpal +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +The family gives every menu, dropdown and flyout one liquid-glass look from the theme's own surface. `.menu` and `.cpal` now read it. Removed lines, `.menu`: `background: var(--surface-2);` and `box-shadow: var(--shadow-pop);`; added `background: var(--glass-bg)`, the hairline `inset 0 0 0 1px var(--glass-border)` as an inset shadow (not a border, so the box is the same size and nothing moves), `inset 0 1px 0 var(--glass-highlight)`, `var(--glass-shadow)` and `backdrop-filter: var(--glass-filter)`. `.cpal`: `background: var(--sheet);` and `box-shadow: var(--shadow-pop);` became `background: var(--glass-bg);` and the highlight plus glass shadow, with `border: 1px solid var(--glass-border)` replacing the `--border` hairline of the same width, and the same backdrop filter. Both already fade with opacity and a small transform; the filter is set in the resting state, so no filter is added or removed while they animate. No DOM, size or position changed. + +### src/styles/views/docform.css · whole dates and one row of buttons from 1000 px +- refers-to: src/styles/views/docform.css :: .df, .df-fields, .df-actions, .df-btn +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +At a 1200 px window the form is 888 px wide and the eight equal field tracks left each date input 101 px, so the year was cut; at 1000 px it was 76 px. A date needs about 128 px in the app's font (the text "00/00/0000" is 81 px, plus 2 px border, 16 px padding and the picker icon), so `--df-date-w: 128px` joins the `.df` tokens. The bottom row held 905 px of buttons (three Make buttons 399, Save draft 107, Cancel document 151, Amend 89, Confirm 111, gaps) and wrapped below 905 px, leaving the primary button on a second row. Nothing was hidden or removed and no DOM changed: `.df` is now a size container named `df` (`container: df / inline-size`; its width still comes from the page, and the only fixed-position layers, the pickers and menus, live on `body`), so both rules follow the form's own width, which also moves when the dock opens at the right or the sidebar is toggled, where a viewport query would not. +- Fields, `@container df (max-width: 1107px)`: 1107 is eight dates plus seven 12 px gaps. Below it the tracks become four of `minmax(var(--df-date-w), 1fr)`; the customer (or supplier) spans two, then date and due date; the warehouse takes one and notes the rest of the second row (three, or two beside the supplier reference). The row gains one field row (63 px) in the narrow case and keeps its height otherwise; the lines box is the `1fr` row and gives that height up. +- Actions, `@container df (max-width: 959px)`: Save draft, Cancel document and Amend keep their icons and lose their visible words (the label span is clipped to 1 px, still the button's accessible name), with `padding-inline` of `--space-2`, so they are 34 px wide instead of 107, 151 and 89, and the row needs 668 px; `.df-btn` gained `position: relative` to hold the clipped label. Confirm or Post and the three Make buttons keep their words. Removed text, none; added only. +- Checked in a seeded ledger under 4x CPU, sales and purchase forms, 1000, 1200, 1440 and 1871 px wide, dark and light: date inputs 163, 213, 131 and 184 px; visible buttons on one row and the last one ending at the form's right edge at every width; no horizontal scroll; after clicking a date, typing 11042026 and Tab, every field, button, the lines box and the error line kept its rectangle to a tenth of a pixel. The Make buttons and Confirm sit under the "Quote" kind picker, so their labels are the draft's. + +### src/ui/views/docform.ts, src/styles/views/docform.css, src/styles/views/grid.css · titles, the lead line and the Description column at 1000 px +- refers-to: src/ui/views/docform.ts :: mountForm (saveBtn, cancelBtn, amendBtn); src/styles/views/docform.css :: .page__heading:has(> .df-title); src/styles/views/grid.css :: .grid, .grid__table, .grid__row +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +Titles: the three buttons that lose their words below 960 px of form width now carry `title` set once when they are made (`Save draft`, `Cancel document`, `Amend`, the words of their labels), so hover text names them; no node is added or replaced. + +Lead line: the heading is a flex item that gives way to the actions (488 px: the template box, Print and the kind picker), but its grid columns come from the 30 character title and the status column, 554 px, and the lead spanned both, so at 1000 and 1200 px it ran under "Save as template...". The heading with a `.df-title` is now an inline-size container (flex-basis falls to zero and `flex-grow` fills what the actions leave, the same width the flex shrink gave it) and its lead is `max-inline-size: min(72ch, 100cqw)`, so it ends in the ellipsis it already had before the actions: 472 px at 1000 (the text reads "One quote, order or invoi..."), 672 at 1200, whole at 1440 and 1871. Title, status and kind picker did not move. + +Description column: the line grid's `min-inline-size` on `.grid__table` was `calc(var(--grid-c-item) * 3 +var(--grid-c-qty) + ...)`; a `+` touching `var(` is not valid inside `calc`, so the declaration was dropped and the table had no minimum. At a 688 px form the fixed columns (168, 80, 112, 136, 120, 32 and gaps) left 0 px for the description, so its header read "D". Now `--grid-c-desc: 96px` is the description track's minimum (`minmax(var(--grid-c-desc), 1fr)`) and the table minimum is the real sum of the columns plus `--space-1 * 10` for eight gaps and the row padding: 784 px, which fits from a 784 px form up. Under `@container df (max-width: 799px)` the numeric columns narrow (item 128, quantity 64, unit price 96, tax 112, amount 104), so the sum is 672 px and the grid does not scroll sideways down to a 688 px form (a 1000 px window). Removed line: `min-inline-size: calc(var(--grid-c-item) * 3 +var(--grid-c-qty) + var(--grid-c-price) + var(--grid-c-tax) + var(--grid-c-num) + var(--grid-c-rm));`. +- Checked as before (seeded ledger, 4x CPU, sales and purchase forms, 1000, 1200, 1440 and 1871 px, dark and light): the Description header 114, 202, 442 and 873 px wide and not clipped; the line grid has no sideways scroll and the page none; the lead's right edge always left of the actions (472 against 488 at 1000, 672 against 688 at 1200); one row of buttons; every title present; after typing a date no rectangle moved. + +### src/styles/shell.css, views/docform.css, views/grid.css, palette.css, theme/tokens.css, ui/menus.ts, ui/command-palette.ts, ui/parts/linegrid.ts · verifier's M1, L1, L2, L7 +- refers-to: src/styles/shell.css :: .sidebar__inner, .sidebar__nav; src/styles/views/docform.css :: .grid__c-desc, .grid__hint; src/styles/views/grid.css :: the narrow container block; src/ui/parts/linegrid.ts :: writeHint +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +M1 (sidebar with the dock open): `.app` loses `--ft-dock-h` of height (280 px at the bottom) and the sidebar's four rows (head, top links, list, footer) kept `minmax(0, 1fr)` for the list, so at 1000 by 480 with the dock at the bottom the app is 170 px high and the rows overflowed on top of each other, and the list had no height to scroll in. The list row is now `minmax(calc(var(--row) * 4), 1fr)` (four rows at least; it is still the part that shrinks, and it scrolls inside), and `.sidebar__inner` gets `overflow-y: auto` with `overscroll-behavior: contain`, so when even four rows will not fit the whole column scrolls and the footer comes after the list, never over it. The list's own `overscroll-behavior: contain` became `auto`, so a wheel that reaches the end of the list carries on to the column and the footer is reachable. Removed: `grid-template-rows: auto auto minmax(0, 1fr) auto;` and the list's `overscroll-behavior: contain;`. Checked under 4x CPU at 1280 by 720, 1000 by 480 and 1440 by 900, dark and light, dock closed, at the bottom (Ctrl+J) and at the right: every one of 15 links and the user chip scrolled into view lay inside the app area and was the element under its own centre; the list ended where the footer began in every case; only 1000 by 480 with the dock at the bottom scrolls the whole column. + +L1 (free line description): the account hint was absolute at 45% of the cell and the input kept 45% of it free, so a 114 px cell showed "Office". The hint is now `min(45%, 14ch)` wide and the input's end padding matches. `.grid__c-desc` is an inline-size container and under 240 px the hint is not drawn and the padding is the normal 8 px; the account moves to the input's hover title. The Description input ends its text in an ellipsis when not focused. The narrow grid columns are item 112, quantity 64, unit price 88, tax 96 and amount 96 (they were 128, 64, 96, 112 and 104), so the description is 162 px at 1000 (it was 114) and 442 at 1440, where "Office supplies for the front desk" shows whole beside the hint. `writeHint` now sets the input's title to the text and, when there is an account, "Posts to ..." after it (`Office supplies for the front desk. Posts to 4100 Sales`), and does it before the early return so the title follows typing. Removed line: `setAttr(r.desc, "title", label ? `Posts to ${label}` : null);`. + +L2: `--z-modal-scrim: 999` is a token beside `--z-modal`, and `.cpal-scrim` reads it, in place of `calc(var(--z-modal) - 1)`. + +L7: `view.dock` has `keys: "Mod+J"` in the menu list and the palette's key list has `app.preferences` (Cmd or Ctrl and comma) and `view.dock` (Cmd or Ctrl and J). These are labels: the window's own key handler for the dock and the one in `app.ts` for the comma are the only bindings and were not touched. On macOS the system menu takes the same `keys` as an accelerator, as it already does for Mod+P, so AppKit answers the chord and the page does not see it; not run here, there is no Mac. Seen on Linux: the View menu row reads "Agent Dock Ctrl+J" and the palette rows read "Preferences Ctrl+," and "Agent dock Ctrl+J". + +### src/ui/menu.ts · PopupMenu and MenuBar, ported from FormVis 2.9.0 +- refers-to: src/ui/menu.ts :: PopupMenu, MenuBar, menuCap, barFloor, keyLabel, trimMenu, shows +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +Written by hand from FormVis `frontend/src/ui/menu.ts` (2.9.0, with FORM-MENU-OVERLAP-FIX 1.2.0 rules 1 to 8 and sections 3, 3a, 3b already in it). Class prefix `fl-` (`.fl-menubar`, `.fl-menu`, `.fl-menu-list`, `.fl-menu-more`, `.fl-menu-item`, `.fl-menu-btn`), because FormLedger already has a `.menu` (the user menu in `overlays.css`). What FormVis's comments said, kept here: +- `menuCap(top)`: a bar menu, or a submenu of one, is at most three quarters of the window tall and never past the bottom edge (minus 4 px). Set inline as `max-height` before the menu is measured, so it never paints at the wrong size. +- `barFloor()`: the line a point-anchored menu may not go above, just under `.fl-menubar` when it shows, else 4 px from the window top. `r.height > 0` covers the bar hidden for the macOS system menu. +- `floor`: set when a menu opens; neither the menu nor its submenus go above it. `openUnder` (bar menus) puts the top on `y` with no flip, ever. `openAt` (right-click and other point menus) keeps the pointer at a corner: below and right when it fits, else flipped, clamped to the floor not to 4 px. `openBeside` (submenus) reads the root's floor and uses the same cap. +- The card does not scroll; the rows sit in `.fl-menu-list`, which does, so the mask fades the rows into the card's own glass and not the glass, border and shadow. `showMore(instant)` sets `has-more` while rows remain below; on opening it runs with `no-fade` and a forced style read so the hint is already there on the first painted frame and never fades in. +- A scroll of the list closes an open submenu, because the row it hangs from has moved. +- Keyboard: F10, Alt alone (not on a Mac) or Alt with a menu's first letter opens a menu; arrows move through it and across the bar; Enter or Space runs a row or opens its submenu; Escape steps back; Tab closes; Home and End jump; typed letters jump to the next row that starts with them (700 ms to type a word). Focus goes back to where it was before the menu when the menu closes. +Differences from FormVis: rows are `MenuCommand` objects with their own label and key combo (the window's `Commands` registry has neither a key map nor a label per menu), and the host is a small `MenuHost` (`run`, `enabled`, `checked`) so the menu file does not import the engine. A press on a row calls `preventDefault` on `pointerdown`, so a text field keeps focus and Edit, Cut and the like act on it. `trimMenu` drops rows by platform (`on: "mac" | "other" | "native" | "window"`) instead of FormVis's hidden-ids list (FormLedger has no Edit > Menus). No i18n (`t`), no colour per item, no `relabel`. The panel is placed in `#overlay-root`, which has no z-index of its own, so `.fl-menu` stacks on `--z-menu`. Nothing outside this file reads the panel's children or `scrollTop`. + +### src/ui/native-menu.ts · the macOS system menu from the same list +- refers-to: src/ui/native-menu.ts :: wantsNativeMenus, menusInWindow, setMenusInWindow, MENUS_IN_WINDOW_KEY, accelerator, PREDEFINED, NativeMenus +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +Ported from FormVis `native-menu.ts`. Only in the desktop app on a Mac (`__TAURI_INTERNALS__` and `navigator.platform`), and only while Menus in Window is off (`localStorage["formledger.menusInWindow"] === "1"` keeps the bar in the window; read at start, so the choice applies at the next start). The menu is built with `@tauri-apps/api/menu` from the same `MenuDef` list as the in-window bar, so labels, order, submenus, separators and shortcuts never differ. `accelerator` turns `Mod+Shift+L` into `CmdOrCtrl+Shift+L`; a key Tauri has no name for leaves the item without one rather than failing the menu (the `try` around each item). Edit, the app menu's About, Services, Hide, Hide Others, Show All and Quit, Close Window, Full Screen, Minimize, Zoom and Bring All to Front are Tauri predefined items: they go to the first responder, so Cmd+C and Cmd+V edit a focused field with no command and no `text_edit` shell call (FormVis needed `text_edit.rs` because its Edit rows were app commands; FormLedger's are not). Enabled and tick states refresh 150 ms after a pointer, key, focus or route change, grouped. With Menus in Window on, a minimal system menu is still built (the app menu, Edit, Window, Full Screen and Close), since macOS always shows one and the edit keys need it; the bar shows in the window. + +### src/ui/menus.ts · the MenuDef list and mountMenus +- refers-to: src/ui/menus.ts :: MENUS, SHELL, mountMenus, bindKeys +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +`MENUS` mirrors `src-tauri/src/menu.rs` (FormLedger, File, Edit, View, Go, Window, Help, the five Go submenus by `go.[view]`) plus `app.home`, `app.preferences` (the app menu on a Mac, Edit elsewhere, Cmd or Ctrl+comma), `view.dock` and `view.menus-in-window` (Mac only, ticked when on). `mountMenus(host, run, isEnabled?)` is the interface the wiring uses: it builds the system menu when `wantsNativeMenus()` and hides `host`, otherwise it mounts `MenuBar` in `host` (which gets `.fl-menubar` and `role="menubar"`); if the system menu fails to build (no permission, older shell) it falls back to the bar. A few ids are the shell's and are handled here, not by `run`: `edit.*` (`document.execCommand` on the focused field; enabled only while a text field has focus), `view.zoomIn`, `view.zoomOut`, `view.zoomReset` (the shell's `zoom` command, the same zoom steps as the old Rust menu), `view.fullscreen`, `window.minimize`, `window.maximize`, `window.close`, `app.quit` (`@tauri-apps/api/window`), `app.reload` and `help.notices`. Outside the desktop app the window ones are disabled. In the window (not with the system menu) the shortcuts shown in the bar are bound on `window` keydown in the bubbling phase and skipped when `defaultPrevented`, so a key the app already handles in `app.ts` (Cmd or Ctrl+P, Shift+L, backslash, Alt+P) is never run twice; `edit.*` keys are left to the browser. `menu.css` is imported here so the bar's rules ship with the module that draws it. + +### src/styles/menu.css · the bar, the glass card and the more-below hint +- refers-to: src/styles/menu.css +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +The `.cv-menubar`, `.cv-menu-btn` and `.cv-menu*` rules of FormVis `shell.css` and `panels.css` (both the base set and the glass set at its end), with the 3a hint verbatim under the `fl-` names: the registered `@property --menu-more` so the mask can animate, the opaque-to-transparent mask from `100% - min(88px, 40%)` to `100% - min(22px, 10%)`, the 56 by 12 pill 6 px above the bottom with the 1 px glass border, 160 ms out and 490 ms back in (the transition of the state being entered runs, so `has-more` carries 490 ms), `no-fade` for the opening frame, `scroll-padding-block-end` so a focused row is scrolled clear of the fade, and no transitions under reduced motion. Colours, glass and radii read the family tokens (`--glass-bg`, `--glass-border`, `--glass-highlight`, `--glass-filter`, `--glass-shadow`, `--radius-xl`, `--text-primary`, `--text-secondary`, `--bg-tertiary`, `--fs-13`, `--fs-14`, `--ctl-md`); FormVis's 6 px card padding is `--space-1` here (the scale has no 6). The layer is `--z-menu`. `.fl-menubar` reserves `--ctl-md` of height so the bar's buttons arriving do not move anything, and hides under `.has-native-menus` or `[hidden]`. + +### package.json · @tauri-apps/api +- refers-to: package.json :: dependencies +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +`@tauri-apps/api` 2.12.5, exact, Apache-2.0 OR MIT: the first runtime dependency of the web client, for the macOS system menu, the shell's zoom command and the window buttons. Pinned to the 2.12 line to match the `tauri` crate (2.12.7 in `Cargo.lock`); the Tauri CLI refuses a minor mismatch between the two. Only `native-menu.ts` and `menus.ts` import it, and only by dynamic `import()`, so the browser build never loads it unless the desktop shell is there. + +### src/dock/ · the family agent dock, module 2.2.1 +- refers-to: src/dock/adapter.ts, agents.ts, chat.ts, consent.ts, dock.ts, dom.ts, icons.ts, keys.ts, placement.ts, state.ts, strings.ts, terminal.ts, tour.ts, dock.css +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +Written out by hand from FormVis 2.9.0's `frontend/src/dock/` (FormDeck's copy is the same bytes); every file compares equal to the reference with `cmp`, so the module's `MANIFEST.json` hashes hold for these fourteen files. `CONTRACT.md` and `MANIFEST.json` themselves were not brought over. Nothing in the folder names an app: FormLedger's names, routes, words and classes are all in `dock-adapter.ts`. The terminal emulator (`terminal.ts`, xterm) is loaded by dynamic `import()` when the first tab opens, so it is its own chunk. Icons are the module's inline `currentColor` SVGs. Layers are `--z-raised` and `--z-overlay` from the scale in `ui/theme/tokens.css`. + +### src/dock-adapter.ts · FormLedger's adapter and mountDock +- refers-to: src/dock-adapter.ts :: mountDock, reserveDock, formledgerDock, DockError, errorKind +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +`mountDock(host: HTMLElement): { toggle(): void; open(): void; close(): void }` is the export the wiring uses. It applies the stored placement to `` first (`reserveDock`, also exported so the entry can call it before the first paint), builds the `Dock`, mounts it in `host`, and sends `formledger:dock` with `{ open }` on every change of the dock's own state (its close button, Cmd or Ctrl+J), once after mounting, from a microtask so a listener added right after `mountDock` returns hears it. The dock keeps its layout under `formledger.agentDock`, not `formledger.dock`, which is the Preferences switch's `"1"` or `"0"`. Tabs offered: shell, Claude Code, Codex, Cursor. No Chat tab (FormLedger has no chat engine), no `consent` and no `storedChoice`: FormLedger has no MCP server, so no outside agent can ask anything and the adapter reports no consent questions; the module then shows no consent dialog, no Outside agents entry and no consent step in the guide. The ask line opens Claude Code with the text as its first message. Errors are FormLedger's `{error: {code, message}}`: 401 and 403 are refused, 409 `program_missing` is not installed, the router's own 404 "no such endpoint" or a 405 is an older engine, 429 is busy, 502 to 504 and a failed fetch are unreachable. The stream is a same-origin WebSocket carrying the session cookie; the engine checks the origin. Keys that leave a terminal: on a Mac Cmd+P, Cmd+comma and Cmd+backslash; elsewhere Ctrl+Shift+P and Ctrl+comma (plain Ctrl+P stays with the shell, where it is the previous command). Sentences overridden for FormLedger: `empty`, `tourPanelBody`, `tourChatBody`, `tourInstalledBody` and `tourReadyBody` (no Chat and no Antigravity here). Classes: `icon-btn`, `btn`, `btn--primary`, `input`, `field__hint`. + +### src/styles/dock-tokens.css, src/styles/terminal.css · tokens and placement +- refers-to: src/styles/dock-tokens.css, src/styles/terminal.css +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +`dock-tokens.css` maps every `--dock-*` token onto FormLedger's family names (`--bg-primary`, `--surface-1`, `--line-0` to `--line-2`, `--text-*`, `--accent-*`, `--space-*`, `--radius-*`, `--ctl-*`, `--fs-*`, `--font-mono`), so theme, accent and light mode reach the dock and the terminal colours. `terminal.css` turns the stored size into `--ft-dock-h` (bottom, at most 70vh) or `--ft-dock-w` (right, at most 60vw), both 0 unless the dock is open and the screen is the app. The dock is fixed to the bottom or right edge on `--z-dock` and `.app` gives up exactly that space (`block-size` less `--ft-dock-h`, `margin-inline-end` of `--ft-dock-w`), so opening, closing or dragging the dock moves only the app's bottom or right edge and rebuilds nothing. The `.app` rule is `:root[data-ft-dock][data-ft-dock-side] .app` so it wins over `shell.css` and over `home.css`'s `:root[data-menus="window"] .app` whatever order the sheets load in, and it subtracts `--fl-menubar-h` (0 when the bar is not in the window) as that rule does. The three sheets are imported by `dock-adapter.ts`. + +### src/ui/home.ts, index.html, src/styles/home.css · the Home start screen in FormDeck's form +- refers-to: index.html :: .view--home, .home__brand, .home-start; src/ui/home.ts :: mountHome, section; src/ui/app.ts :: mountApp +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +Home keeps its markup in `index.html` so its head and start cards exist before the app screen shows: the brand mark (the favicon at a fixed 26 by 26) and name, the daypart greeting, a Preferences button, and six start cards that each open a screen that already works (new sales invoice, new quote, new purchase invoice, record payment, the general ledger, templates). FormDeck's other actions have no FormLedger counterpart today: there is no import endpoint and no second company to open, so neither has a card. The existing dashboard tiles and the last five sales and purchase invoices are the body; `mountHome`, `tile` and `recentBlock` moved unchanged from `app.ts` into `home.ts`, now under "At a glance" and "Recent" headings, and they replace the `[data-ref="home-body"]` placeholder once at mount, while the app screen is still hidden. Removed from index.html: `

FormLedger

`, `
New invoice`, `Record payment` (both are start cards now). Removed from app.ts: `home.classList.add("home--dash");` (the class is in the markup). + +### src/ui/prefs.ts, src/ui/themes.ts, src/styles/prefs.css · Preferences in FormVis's form, theme and accent from the first frame +- refers-to: src/ui/prefs.ts :: prefsView, attachDock, toggleDock, menusInWindow; src/ui/themes.ts :: applyTheme, setTheme, setAccent, followSystem; src/ui/views.ts :: defsAll; index.html :: boot script +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +Preferences is the view `#/preferences` (group Setup): a sticky rail of section tabs on the left and the sections stacked on the right, as FormVis's dialog lays them out; a tab scrolls to its section and an IntersectionObserver marks the tab in view, which changes only `aria-selected`. Sections: Appearance (Dark, Light, Match the system; six accents), Menus in Window (only on macOS; writes `formledger.menusInWindow`, the key `native-menu.ts` reads, and says it applies at the next start), Agents (a switch that opens or closes the dock through its handle and follows the dock's `formledger:dock` event; the dock keeps its own state under `formledger.agentDock`), Security (the app lock switch, through the existing `account.lock` command, shown under the same rule as the Account page). The four server settings in `internal/settings` (`instance.name`, `stock.allow_negative`, `purchasing.grni_account`, `purchase.expense_account`) have no HTTP route, so Preferences cannot show them without a new endpoint; none was added. The theme stays under `formledger.theme`; the accent is `formledger.accent`. The head script now also sets `data-accent` and `data-menus` (`native` only for the Tauri shell on macOS with Menus in Window off) before the body is parsed, and accents are CSS rules on `:root[data-accent]` with a light-theme pair each, so no style attribute is written (the server's `style-src 'self'` blocks those). `applyTheme` writes an attribute only when its value changes. Removed from app.ts: `const THEME_KEY = "formledger.theme";` and its `applyTheme(pref: string)` (now in `themes.ts`), the `localStorage.setItem(THEME_KEY, ...)` blocks in the user menu and `shell.theme.toggle`, and the inline `matchMedia(...).addEventListener("change", ...)` (now `followSystem`). + +### src/ui/app.ts, src/engine/commands.ts, src/styles/home.css · wiring the menu bar and the dock +- refers-to: src/ui/app.ts :: mountShell, bindCommands; src/engine/commands.ts :: SHELL_COMMANDS; index.html :: .fl-menubar-host, .fl-dock-host +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +`SHELL_COMMANDS` names `app.home`, `app.preferences` (Mod+comma), `view.dock` and `view.menus-in-window` (hidden and disabled off macOS); `bindCommands` registers them. Ctrl or Cmd+comma is handled in the existing keydown handler, which calls `preventDefault`, so `menus.ts`'s key binding skips it. `mountShell` runs last in `mountApp`: `mountMenus` on the header above `#app`, with `enabled` read from the registry, and `mountDock` on `.fl-dock-host` (`display: contents`, so the dock's own `--z-dock` decides its layer); `reserveDock` runs first in `mountApp`. The bar's 30 px is a token, `--fl-menubar-h`, set only under `:root[data-menus="window"]`; `.app` loses that height and `--ft-dock-h`, so the bar never pushes the window. The host has `fl-menubar` from first paint and is hidden off the app screen and when the macOS menu is native. Checked with 4x CPU, 400 ms latency, 50000 B/s and cache off, hard reload at 1400 by 900, production build through `vite preview` against the 0.14.0 server binary: the first frame already had the theme and accent (dark violet, light orange, dark on Preferences), 0 later theme changes, layout shift 0 on each load; the bar was 0 high while the app was hidden and 30 high in the same frame the app appeared, sheet top 30 from that frame on. Theme and accent changes on Preferences: 0 shift, 1 text change in `.app` (the accent's name). Dock open and close: one step each, no in-between frame, `.app` 870 to 590 and back, bar and sheet top unchanged; Chrome counted 0.005 and 0.011 shift, both the sidebar footer following the app's bottom edge, which is the dock's reserved space and not a jump. + +### src/ui/menus.ts · the in-window fallback claims the bar row + +When the macOS system menu fails to build, `mountMenus` falls back to the in-window bar, but the head script had already set `data-menus="native"`, and `home.css` hides `.fl-menubar-host` and gives `.app` no bar row under that value, so the fallback bar stayed hidden. The fallback now sets `data-menus="window"` on the root before it unhides the host, so the row opens in the same task as the bar is built. Before: `void new NativeMenus(menuHost, () => MENUS).build().catch(() => {` followed directly by `host.hidden = false;`. + +### src/dock-adapter.ts · xterm's styles under the strict CSP, as constructed sheets +- refers-to: src/dock-adapter.ts :: adoptScriptStyles, mountDock +- kind: rationale +- logged: v0.15.0 · 2026-12-01 (EST) + +The window's CSP is `style-src 'self'` and stays so. xterm 6 creates three `

Window

A list for every document type · one form with a line grid for sales and purchase documents · payments with allocation · setup lists · a dashboard of revenue, expenses, profit, cash and top customers by month · a command palette that reaches every screen · light, dark or system theme. See docs/window/

Window

A list for every document type · one form with a line grid for sales and purchase documents · payments with allocation · setup lists · a dashboard of revenue, expenses, profit, cash and top customers by month · a command palette that reaches every screen · light, dark or system theme · from 0.15.0, a menu bar (in the window on Windows and Linux, the system menu on macOS), a Home start screen and Preferences (theme, accent, the agent dock and the app lock). See docs/window/

Reports

Trial balance · general ledger · profit and loss · balance sheet · receivables and payables aging · stock balance and value

Taking figures out

CSV of every list and report · PDF of quotes, orders, invoices, purchase documents and customer statements · a read-only SQLite snapshot of the books. See docs/EXPORT.md, docs/PRINT.md and docs/SNAPSHOT.md