diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c2dfb3..834f4c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,37 @@ # Changelog +## 0.12.0 + +FormLedger writes a snapshot from the window, keeps its own key on the desktop, tells you when FormTxt did not draw a page, and names the accounts its templates post to. + +### New +- **Write snapshot** in the menubar and the command palette writes the snapshot at once, into a `snapshots` folder inside the data folder, and says where it is and how many tables and rows it holds. Only the owner can write one. +- **A key of its own:** with `FORMLEDGER_KEY_HOME` set and no key file given, the server makes a key once, keeps it there and encrypts the ledger from then on, converting an existing plain ledger on first start. The desktop app is written to set this to its app data folder. +- **Template cards name their accounts,** for example "Posts to 4100 Sales · 4900 Other income", read from your chart of accounts. + +### Improved +- **Printing through FormTxt:** when FormTxt does not draw the page, `cli print` says why under the "printed by" line, for example that FormTxt needs its window open and outside agents allowed, or that it has no such template. FormLedger waits 100 seconds for FormTxt, up from 45. +- **Dashboards** sit closer to form.md's: larger figures on the number cards, short labels on the value axis (2K, not 2000.00), and the same card corners. +- **The command palette** keeps its columns still while you type. + +### Changed +- **Ctrl or Cmd+P opens Search,** as in form.md. Print is Ctrl or Cmd+Alt+P. +- **`formledger encrypt` keeps a plain copy** of the old database beside it, named `formledger-plain-copy-` and the date, and never overwrites an earlier copy. That copy is not encrypted: delete or move it once the encrypted ledger opens. + +### Fixed +- The templates screen no longer moves a line on each card as the names arrive. +- A print that FormTxt refused used to fall back to the plain page without a word. + +### Known issues +- Losing the key loses the books. Back the key file up; `docs/ENCRYPTION.md` says how. On the desktop the first-run warning is in the server's log, not in the window. +- FormLedger ships no FormTxt template. You make one in FormTxt and set `FORMLEDGER_FORMTXT_TEMPLATE_INVOICE` to its id (`docs/PRINT.md`). +- A document started from a template does not show the account each line posts to. +- The short axis labels on charts assume a currency with two decimal places. +- The top bar's title moves slightly as the dashboards screen loads. + +### Under the hood +- Checked for this version: an invoice was drawn by FormTxt 0.38.0 and, with FormTxt stopped, by the plain renderer. Not run: the desktop app and its menubar were not compiled, and nothing ran on macOS or Windows. + ## 0.11.0 FormLedger gets dashboards with charts, document templates, a short sidebar with a command palette and a full menubar, and encryption at rest. diff --git a/Makefile b/Makefile index 839de2e..9b1b7a2 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -VERSION := v0.11.0 +VERSION := v0.12.0 GO_BUILD := CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" .PHONY: build web server check clean diff --git a/README.md b/README.md index 139f78f..d6d91c9 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

- version v0.11.0 + version v0.12.0 Go 1.26+ TypeScript and Vite License: Apache-2.0 @@ -120,6 +120,7 @@ On Windows use `formledger_oc_install.bat` and `formledger.bat`. | `FORMLEDGER_URL` | Server the command line talks to, default `http://127.0.0.1:8340` | | `FORMLEDGER_TOKEN` | App token for the command line | | `FORMLEDGER_KEY_FILE` | Key file that turns on encryption at rest; unset means the ledger is stored plain | +| `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. diff --git a/SECURITY.md b/SECURITY.md index 97d8c0e..cc69f92 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -46,7 +46,10 @@ FormLedger, are ordinary bugs: please open an issue for those. 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. A missing or wrong key stops the server before any +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). diff --git a/cmd/HASHOUT_LOG.md b/cmd/HASHOUT_LOG.md index 5295993..f60d49b 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.11.0 +Current build version: v0.12.0 Last updated: 2026-11-26 (US Eastern) · skeleton port from form.md --- diff --git a/cmd/formledger/main.go b/cmd/formledger/main.go index 0178a88..87f418f 100644 --- a/cmd/formledger/main.go +++ b/cmd/formledger/main.go @@ -70,11 +70,19 @@ func encrypt() int { return 2 } defer release() - if err := store.Encrypt(context.Background(), cfg.DataDir, cfg.KeyFile); err != nil { + copyPath, err := store.Encrypt(context.Background(), cfg.DataDir, cfg.KeyFile) + if err != nil { fmt.Fprintln(os.Stderr, "formledger encrypt:", err) return 1 } + if copyPath == "" { + fmt.Println("the database was already encrypted with this key; nothing changed") + return 0 + } fmt.Println("encrypted the database; start FormLedger with the same FORMLEDGER_KEY_FILE") + fmt.Println("the old plain database was kept at:", copyPath) + fmt.Println(store.PlainCopyNote) + fmt.Println(crypt.LossWarning) return 0 } @@ -118,7 +126,29 @@ func serve() int { if replaced > 0 { log.Info("an engine left running by an earlier start was stopped", "pid", replaced) } - key, err := crypt.Load(cfg.DataDir, crypt.KeyPath(cfg.KeyFile), store.HasData(cfg.DataDir)) + keyPath := crypt.KeyPath(cfg.KeyFile) + if keyPath == "" && cfg.KeyHome != "" { + path, made, err := crypt.EnsureHome(cfg.KeyHome) + if err != nil { + log.Error("encryption", "err", fmt.Errorf("making the desktop key: %w", err)) + return 2 + } + keyPath = path + if made { + log.Warn("made this computer's FormLedger key", "key", path) + log.Warn(crypt.LossWarning) + } + if store.HasData(cfg.DataDir) && !crypt.Encrypted(cfg.DataDir) { + copyPath, err := store.Encrypt(ctx, cfg.DataDir, path) + if err != nil { + log.Error("encryption", "err", err) + return 1 + } + log.Warn("encrypted the existing ledger; the old plain database was kept", "copy", copyPath) + log.Warn(store.PlainCopyNote) + } + } + key, err := crypt.Load(cfg.DataDir, keyPath, store.HasData(cfg.DataDir)) if err != nil { log.Error("encryption", "err", err) return 2 diff --git a/docs/ENCRYPTION.md b/docs/ENCRYPTION.md index 9f69c21..25a0f1a 100644 --- a/docs/ENCRYPTION.md +++ b/docs/ENCRYPTION.md @@ -1,8 +1,8 @@ # Encryption at rest -FormLedger can encrypt its data directory at rest with a 256-bit key that you hold outside the data directory. The wiring is ported from form.md (`internal/crypt/key.go`, `internal/cryptvfs/vfs.go`, `internal/store/store.go`, `internal/ops/encrypt.go`, `cmd/form-md/main.go`, `cmd/form-md/tool.go` and `.docs/wiki/Encryption.md`), changing only names. As in form.md, encryption is on when FormLedger is given a key and off when it is not. +FormLedger can encrypt its data directory at rest with a 256-bit key that you hold outside the data directory. The wiring is ported from form.md (`internal/crypt/key.go`, `internal/cryptvfs/vfs.go`, `internal/store/store.go`, `internal/ops/encrypt.go`, `cmd/form-md/main.go`, `cmd/form-md/tool.go` and `.docs/wiki/Encryption.md`), changing only names. On a server, as in form.md, encryption is on when FormLedger is given a key and off when it is not. The desktop app makes and keeps its own key, so a desktop ledger is always encrypted (below). -**There is no recovery without the key.** If the key is lost, the ledger cannot be read by anyone, including you. Back the key up before you put data in. +**Losing the key loses the books.** There is no recovery without the key: if it is lost, the ledger cannot be read by anyone, including you. Back the key up before you put data in (see "Backing up the key"). ## What is encrypted, and with what @@ -21,7 +21,7 @@ The database, WAL and journal keys and the key check are derived from the one ma - The WAL file header and each WAL frame header, and the `-shm` file. - Tampering is not detected as such: XTS carries no authentication tag, so a page changed on disk decrypts to noise, which SQLite reports as a damaged database. - Anything outside the data directory: memory, network traffic (use TLS), and any snapshot you write (below). -- Copies made before encryption was turned on. `formledger encrypt` converts only the data directory. +- Copies made before encryption was turned on, and the `formledger-plain-copy-*.db` that `formledger encrypt` keeps. ## Where the key is @@ -32,7 +32,23 @@ FormLedger looks for the key in this order: With neither, the ledger is stored plain and the server says so at start: `at-rest encryption off`. The key file holds 32 bytes written as 64 hex characters or as base64. -**On a desktop**, as in form.md, nothing makes a key for you. Make one and keep it outside the data directory, readable only by you: +**In the desktop app**, the app keeps its own key. When it starts its server and no `FORMLEDGER_KEY_FILE` is set, it hands the server `FORMLEDGER_KEY_HOME`, the app's own data folder (not the `~/FormLedger` books folder). The server then: + +1. makes `formledger.key` in that folder once, readable and writable by you only (mode 0600 on macOS and Linux; on Windows the folder is under your user profile, which only your account can read), and logs `made this computer's FormLedger key` with the path and the warning that losing the key loses the books; +2. uses that same key on every later start; +3. if the books folder still holds a plain ledger from an earlier version, encrypts it before opening, keeping the plain database beside it as described in "Turning it on for an existing ledger", and logs where the copy is. + +A fresh desktop install is therefore encrypted from its first database. (In this build the server side was run and checked; the shell's line that passes the folder, `engine_start::key_home` in `src-tauri/src/main.rs`, is written but the desktop app was not compiled for this version.) Where the app data folder is: + +| System | Folder | +|---|---| +| macOS | `~/Library/Application Support/[app identifier]/` | +| Linux | `~/.local/share/[app identifier]/` | +| Windows | `%APPDATA%\[app identifier]\` | + +The app identifier is `identifier` in `src-tauri/tauri.conf.json`, today `ai.nodemode.formledger`. Set `FORMLEDGER_KEY_FILE` before starting the app to use a key of your own instead; the app then makes none. + +**Running the server yourself on a desktop**, make a key and keep it outside the data directory, readable only by you: ``` formledger keygen > ~/formledger.key && chmod 600 ~/formledger.key @@ -51,6 +67,14 @@ LoadCredential=formledger.key:/etc/formledger/formledger.key Copy the key file to somewhere that is not the data directory and not the same disk: a password manager or an offline drive. A backup of the data directory without the key is useless; a key kept beside the data directory protects nothing. +The key is one line of 64 hex characters, so it can be kept as text: + +- **Password manager:** open the key file in a text editor (on the desktop, the `formledger.key` in the app data folder above), copy the line into a secure note, and check that the note shows the same 64 characters. +- **Offline drive:** copy the file, for example `cp ~/.local/share/[app identifier]/formledger.key /media/usb/`, and keep the drive apart from the computer. +- **To restore:** put the file back where it was with mode 0600 (`chmod 600 formledger.key`), or point `FORMLEDGER_KEY_FILE` at it. + +Back the key up again only if you replace it; it never changes on its own. Every backup of the books (`~/FormLedger`) needs that key to open. + ## Turning it on for an existing ledger A key given to a plain ledger is refused, so a plain ledger is never opened as if it were encrypted: @@ -65,7 +89,18 @@ Stop FormLedger, then run: FORMLEDGER_KEY_FILE=~/formledger.key formledger encrypt ``` -It copies the database with `VACUUM INTO` to `formledger.db.encrypting` through the encrypting VFS, opens the copy and runs `PRAGMA integrity_check`, and only when that says `ok` renames the copy over `formledger.db` and writes `encryption.json`. If anything fails, the copy is removed and the plain database is left as it was. As in form.md, the plain database is not kept after a successful swap: take a copy of the data directory first if you want one, and delete it once you have checked the encrypted ledger. +It copies the database with `VACUUM INTO` to `formledger.db.encrypting` through the encrypting VFS, opens the copy and runs `PRAGMA integrity_check`, and only when that says `ok` renames the copy over `formledger.db` and writes `encryption.json`. If anything fails, the copy is removed and the plain database is left as it was. + +Unlike form.md, the old plain database is kept. Before the swap, `formledger encrypt` writes it with `VACUUM INTO` beside the ledger as `formledger-plain-copy-YYYY-MM-DD.db` (mode 0600). It never overwrites a copy that is already there: a second copy on the same day is `formledger-plain-copy-YYYY-MM-DD-2.db`, and so on. It then prints: + +``` +encrypted the database; start FormLedger with the same FORMLEDGER_KEY_FILE +the old plain database was kept at: /path/to/data/formledger-plain-copy-2026-11-27.db +This copy is NOT encrypted: anyone who can read the file can read your books. Delete it or move it somewhere safe once you are sure the encrypted ledger opens. +Losing the key loses the books: without it nobody can read this ledger, not even you. Back the key file up now to a password manager or an offline drive. +``` + +Run on a ledger that is already encrypted with the same key, it changes nothing and says so. The plain copy is in the clear, like a snapshot: once the encrypted ledger opens with the key, delete the copy or move it somewhere as safe as the key. ## Missing or wrong key diff --git a/docs/PRINT.md b/docs/PRINT.md index b099109..46cc64e 100644 --- a/docs/PRINT.md +++ b/docs/PRINT.md @@ -35,11 +35,19 @@ The page uses the PDF core font Helvetica in the Windows-1252 code page, so Lati Rendering goes through a list of renderers, each of which draws a document and a statement, or answers "not available" so the next one is tried. The FormTxt renderer is first and the plain one is last. The response carries `X-FormLedger-Renderer: formtxt` or `plain`, and `./formledger cli print` prints `printed by the plain renderer` (or `formtxt`) on standard error. `--plain` on the command, or `?renderer=plain` on the address, skips FormTxt; `FORMLEDGER_PRINT=plain` in the server's environment skips it for every print. -**Status: unverified.** The FormTxt renderer is built against FormTxt's documented `report run` route and has never produced a PDF here. What it does: +**Status: verified on 2026-11-27 against FormTxt 0.38.0.** An invoice was drawn by FormTxt through `./formledger cli print invoice SI-2026-000001` (stderr `printed by the formtxt renderer`), and the same command with FormTxt's engine stopped drew the plain page. What it does: - It finds FormTxt the way FormTxt's own tools do (`setup/report.py`, `setup/catalogue.py`): the engine at `http://127.0.0.1:$FORMTXT_ENGINE_PORT`, port `8210` when unset. There is no discovery file. - It posts to `/api/reports/run` with the data as `records` (one record per line, the document's header fields repeated on each: `company`, `title`, `number`, `date`, `dueDate`, `customer`, `customerName`, `supplier`, `supplierName`, `currency`, `status`, `memo`, `subtotal`, `taxTotal`, `total`, then `item`, `description`, `quantity`, `unitPrice`, `taxRate`, `lineSubtotal`; a statement's are `customer`, `customerName`, `currency`, `from`, `to`, `opening`, `closing`, then `lineDate`, `event`, `reference`, `debit`, `credit`, `balance`), `mode` `list`, `format` `pdf`, and `out` a file in a fresh temporary folder that it reads back and removes. Amounts arrive formatted, as on the plain page. - The template is a FormTxt document id, named per kind in the server's environment: `FORMLEDGER_FORMTXT_TEMPLATE_INVOICE`, `_QUOTE`, `_ORDER`, `_PURCHASE_ORDER`, `_PURCHASE_INVOICE`, `_GOODS_RECEIPT`, `_STATEMENT`. A kind with no template goes to the plain renderer. -- Any failure (no engine, a refusal, a timeout of 45 seconds, a file that is not a PDF) goes to the plain renderer. +- Any failure (no engine, a refusal, a timeout of 100 seconds, a file that is not a PDF) goes to the plain renderer. When FormTxt answered but did not draw, the response carries the reason in `X-FormLedger-Renderer-Note` (path-escaped) and `cli print` writes it on standard error under the renderer line. A 403 reads: `FormTxt refused to draw the page, so FormLedger drew the plain page. FormTxt said: No FormTxt window is open. Start it with ./formtxt and open the app, then retry. Open FormTxt, allow outside agents when it asks, or turn on Allow outside agents in its Preferences under Privacy, then print again.` A template id FormTxt does not hold (404) names the environment variable to set. The wait is 100 seconds so the person can answer FormTxt's question, and stays under `cli print`'s own two minutes; FormTxt itself waits up to 180 seconds for the answer. -Why no templates ship and why it could not be shown: FormTxt's report route merges into a document that already lives in FormTxt's own store, and creating a document there is answered only by the FormTxt window (`POST /api/documents` answers `Only the FormTxt window can do this`). The route also asks the person **Allow outside agents?** in the open window before it writes a file (FormTxt `README.md`, Mail merge and list reports; `backend/app/routers/reports.py` `run`; `backend/app/routers/mcp.py` `consent`). With FormTxt's engine running and no window, it answers 403 `No FormTxt window is open`, and FormLedger prints with the plain renderer. A person who wants FormTxt pages makes a template in the FormTxt window from its built-in `business-invoice` template with merge fields named as above, allows outside agents once, and sets the environment variables. +### Setting it up + +No templates ship: FormTxt's report route merges into a document in FormTxt's own store, and only the FormTxt window can create one (`POST /api/documents` without the window's key answers `Only the FormTxt window can do this`). + +1. Open the FormTxt window. Make a document with the header fields as merge fields and a table whose line row is marked to repeat (`merge.repeatRow`), its cells holding `item`, `description`, `quantity`, `unitPrice`, `taxRate`, `lineSubtotal`. A list merge refuses a template with no repeating row. +2. Set `FORMLEDGER_FORMTXT_TEMPLATE_INVOICE` (and the other kinds) to that document's id, and `FORMTXT_ENGINE_PORT` when FormTxt is not on 8210, in FormLedger's server environment. +3. Print once with the window open. FormTxt asks **Allow an outside agent to make changes in FormTxt?**, naming the temporary file it will write, with Deny, Allow once and Always allow all outside agents. Always allow saves `agentsAllowed` in FormTxt's own `settings.json` in its data folder (not the system password store), so later prints draw with no window open. Allow once lets that one print through without saving the answer (read from FormTxt's `consent`, not tried here). + +With the engine running and no window, and outside agents not allowed, FormTxt answers 403 `No FormTxt window is open`, and FormLedger prints with the plain renderer and the note above. diff --git a/internal/HASHOUT_LOG.md b/internal/HASHOUT_LOG.md index fff747b..e53d954 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.11.0 +Current build version: v0.12.0 Last updated: 2026-11-27 (US Eastern) · profit and loss and the balance sheet --- @@ -1847,3 +1847,31 @@ Revenue, expenses and profit use the statements' filter (`counted`) per month, s - logged: v0.10.0 · 2026-11-27 Built-in templates live in Go, not in the table, so an upgraded database gets them without a data migration and they can never be changed; their ids start with `builtin-` and change or delete answers 409. Every route is behind `reports.read`; writing and `use` then check `sales.draft` or `purchase.draft` for the template's kind (and, on change, for the stored kind too). Lines are a JSON column because a template is read and written whole. Built-in free lines name 4100, 4900, 5100 and 5200: the starter chart's 4000 and 6000 are groups and a line cannot post to a group. `use` never writes; `currentPrice` takes the item's sale price for purchase templates too, since items carry no purchase price. + +### templates/template.go · Account names on template lines +- refers-to: internal/templates/template.go :: Line.AccountName, Service.accountNames, nameLines, Service.Get, Service.List, Service.Use, clean +- kind: rationale +- logged: v0.12.0 · 2026-11-27 + +`accountName` is read from `accounts` by code on every `Get`, `List` and `use`, never stored: `clean` blanks it before a write, so a renamed chart account shows its new name at once and no template carries a stale one. `nameLines` copies the line slice so the shared built-in list is never changed. A code the chart does not hold gets no name and the screen shows the bare code. With the starter chart the four codes read 4100 Sales, 4900 Other income, 5100 Purchases and cost of sales, 5200 Freight in. + +### internal/crypt/home.go, internal/store/encrypt.go · desktop key and the kept plain copy +- refers-to: internal/crypt/home.go :: EnsureHome, HomeKeyName, LossWarning; internal/store/encrypt.go :: Encrypt, PlainCopyNote, plainCopyName; internal/config/config.go :: KeyHome, Vars (KEY_HOME); cmd/formledger/main.go :: serve, encrypt; src-tauri/src/engine_start.rs :: KEY_HOME_ENV, key_home +- kind: rationale +- logged: v0.12.0 · 2026-11-27 + +The owner said yes to both: the desktop app makes and keeps its own key, and `formledger encrypt` keeps a plain copy (a break from form.md, which keeps none). The seam is `FORMLEDGER_KEY_HOME`, set only by the shell: with no key file and no systemd credential, `serve` calls `EnsureHome`, which makes `formledger.key` once with `O_EXCL` and mode 0600 (a lost race reads the winner's file), then, if the data folder holds a plain ledger, runs `Encrypt` before `crypt.Load`, inside the data-folder claim. A configured key always wins and the home is then ignored. The copy is `VACUUM INTO` with the default VFS after the WAL checkpoint, so it is a whole plain database, mode 0600, named `formledger-plain-copy-YYYY-MM-DD.db` in local time with `-2`, `-3` when taken; it is removed again if any later step fails. `Encrypt` returns an empty path when the folder was already encrypted with the same key. On Windows the 0600 mode only clears write bits for others; the protection there is the user profile folder's own access list. Proven by starting the binary as main.rs would, twice, on a fresh folder and on a plain one with a planted copy name. + +### internal/snapshot/route.go · Write Snapshot from the window +- refers-to: internal/snapshot/route.go :: Module, Mount, written; internal/server/server.go :: Build (snapshot.Module); internal/snapshot/snapshot.go :: Write +- kind: rationale +- logged: v0.12.0 · 2026-11-27 + +`POST /api/snapshot` is behind `settings.manage`, so only the owner can take a whole copy of the books; an app token is refused by `Require` like any other session-only write would be. The server never takes a path from the request: it writes `formledger-snapshot-YYYY-MM-DD-HHMMSS.sqlite` (Eastern time, to the second) into a `snapshots` folder it makes inside the data folder with mode 0700, so no caller can aim it at another file, and the second-level name plus a `TryLock` (409 `snapshot_busy`) keep two clicks from meeting on one file. Writing to the data folder rather than streaming a download fits the CLI's `Write` as is and keeps the file on the machine that holds the ledger; netguard is not involved because nothing is fetched. The answer is 201 with `file`, `folder`, the absolute `path`, `tables` (name and rows, sorted) and the summed `rows`. On the seeded ledger it wrote 13 tables and 90 rows; Python's sqlite3 read the same counts, plus `sqlite_stat1` and `sqlite_stat4` left by ANALYZE, which are not counted. + +### internal/printout/formtxt.go · FormTxt really drew an invoice +- refers-to: internal/printout/formtxt.go :: run, refused; internal/printout/document.go :: pick, Render, RenderStatement; internal/printout/module.go :: Mount, setNote; internal/printout/command.go :: Command +- kind: rationale +- logged: v0.12.0 · 2026-11-27 + +Run against a copy of FormTxt 0.38.0 (engine on 8504, its window built from its own frontend and opened in headless Chrome). The route, the `records` payload, `mode list`, `format pdf` and the fresh `out` path were right as written; FormTxt answered 200 and the page came out with every merge field filled. What was wrong was the silence: a template id FormTxt does not hold came back 404 and FormLedger printed plain with no word why, and a 403 did the same. `refused` carries a sentence and still `Is` `ErrUnavailable`, so the chain falls through unchanged; `pick` keeps the first such sentence and the route sends it path-escaped in `X-FormLedger-Renderer-Note`, because a header cannot hold every character a FormTxt detail may contain. The wait went from 45 to 100 seconds: the first print blocks on FormTxt's Allow question (FormTxt waits up to 180 seconds and withdraws the question when the caller hangs up), and 100 stays inside `cli print`'s two minute client. Always allow all outside agents saved `agentsAllowed: true` in FormTxt's data-folder `settings.json`; no system password store is involved, so the sandbox had nothing to refuse. diff --git a/internal/app/version.go b/internal/app/version.go index 73bbaf5..1737f8e 100644 --- a/internal/app/version.go +++ b/internal/app/version.go @@ -1,5 +1,5 @@ package app -var Version = "v0.11.0" +var Version = "v0.12.0" const Product = "FormLedger" diff --git a/internal/config/config.go b/internal/config/config.go index 9064eea..bd0493d 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -20,6 +20,7 @@ type Config struct { TLSKey string KeyFile string + KeyHome string ACMEDomains []string ACMEEmail string @@ -41,6 +42,7 @@ var Vars = []Var{ {"TLS_CERT", "", "path to a TLS certificate; set together with FORMLEDGER_TLS_KEY"}, {"TLS_KEY", "", "path to the TLS private key; set together with FORMLEDGER_TLS_CERT"}, {"KEY_FILE", "", "path to the at-rest encryption key (formledger keygen makes one); keep it outside the data directory. A systemd credential named formledger.key is used when this is unset"}, + {"KEY_HOME", "", "set by the desktop app to its own data folder: with no key file given, the server makes a key there once (owner-only) and encrypts the ledger with it. Leave unset"}, {"ACME_DOMAINS", "", "comma-separated host names to get certificates for automatically (Let's Encrypt by default); needs ports 443 and 80 reachable"}, {"ACME_EMAIL", "", "contact address given to the certificate authority"}, {"ACME_DIRECTORY", "https://acme-v02.api.letsencrypt.org/directory", "ACME directory URL; point it at a staging or private CA to test"}, @@ -55,6 +57,7 @@ func Load() (Config, error) { TLSCert: get("TLS_CERT"), TLSKey: get("TLS_KEY"), KeyFile: get("KEY_FILE"), + KeyHome: get("KEY_HOME"), ACMEEmail: get("ACME_EMAIL"), ACMEDirectory: get("ACME_DIRECTORY"), diff --git a/internal/crypt/home.go b/internal/crypt/home.go new file mode 100644 index 0000000..03823f6 --- /dev/null +++ b/internal/crypt/home.go @@ -0,0 +1,38 @@ +package crypt + +import ( + "errors" + "os" + "path/filepath" +) + +const HomeKeyName = "formledger.key" + +func EnsureHome(dir string) (string, bool, error) { + if err := os.MkdirAll(dir, 0o700); err != nil { + return "", false, err + } + path := filepath.Join(dir, HomeKeyName) + if _, err := os.Stat(path); err == nil { + return path, false, nil + } + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if errors.Is(err, os.ErrExist) { + return path, false, nil + } + if err != nil { + return "", false, err + } + if _, err := f.WriteString(Generate() + "\n"); err != nil { + f.Close() + os.Remove(path) + return "", false, err + } + if err := f.Close(); err != nil { + os.Remove(path) + return "", false, err + } + return path, true, nil +} + +const LossWarning = "Losing the key loses the books: without it nobody can read this ledger, not even you. Back the key file up now to a password manager or an offline drive." diff --git a/internal/printout/command.go b/internal/printout/command.go index 926ac39..6c14ff8 100644 --- a/internal/printout/command.go +++ b/internal/printout/command.go @@ -91,6 +91,9 @@ func Command(args []string, out io.Writer) error { return fmt.Errorf("print %s %s answered %d: %s", pos[0], pos[1], resp.StatusCode, strings.TrimSpace(string(body))) } fmt.Fprintf(os.Stderr, "printed by the %s renderer\n", resp.Header.Get("X-FormLedger-Renderer")) + if note, err := url.PathUnescape(resp.Header.Get("X-FormLedger-Renderer-Note")); err == nil && note != "" { + fmt.Fprintln(os.Stderr, note) + } if file == "" { _, err = out.Write(body) return err diff --git a/internal/printout/document.go b/internal/printout/document.go index 8ff3411..cc0d771 100644 --- a/internal/printout/document.go +++ b/internal/printout/document.go @@ -15,25 +15,30 @@ type Renderer interface { var renderers = []Renderer{formtxt{}, plain{}} -func pick(plainOnly bool, draw func(Renderer) ([]byte, error)) ([]byte, string, error) { +func pick(plainOnly bool, draw func(Renderer) ([]byte, error)) ([]byte, string, string, error) { + note := "" for _, r := range renderers { if plainOnly && r.Name() != "plain" { continue } b, err := draw(r) + var why refused + if errors.As(err, &why) && note == "" { + note = why.why + } if errors.Is(err, ErrUnavailable) { continue } - return b, r.Name(), err + return b, r.Name(), note, err } - return nil, "", ErrUnavailable + return nil, "", note, ErrUnavailable } -func Render(d *Document, plainOnly bool) ([]byte, string, error) { +func Render(d *Document, plainOnly bool) ([]byte, string, string, error) { return pick(plainOnly, func(r Renderer) ([]byte, error) { return r.Render(d) }) } -func RenderStatement(s *Statement, plainOnly bool) ([]byte, string, error) { +func RenderStatement(s *Statement, plainOnly bool) ([]byte, string, string, error) { return pick(plainOnly, func(r Renderer) ([]byte, error) { return r.Statement(s) }) } diff --git a/internal/printout/formtxt.go b/internal/printout/formtxt.go index b0abab3..847c61e 100644 --- a/internal/printout/formtxt.go +++ b/internal/printout/formtxt.go @@ -3,6 +3,8 @@ package printout import ( "bytes" "encoding/json" + "errors" + "io" "net/http" "os" "path/filepath" @@ -93,17 +95,39 @@ func (formtxt) run(kind, title string, rows []map[string]any) ([]byte, error) { if err != nil { return nil, ErrUnavailable } - resp, err := (&http.Client{Timeout: 45 * time.Second}).Post(base+"/api/reports/run", "application/json", bytes.NewReader(body)) + resp, err := (&http.Client{Timeout: 100 * time.Second}).Post(base+"/api/reports/run", "application/json", bytes.NewReader(body)) if err != nil { + var late interface{ Timeout() bool } + if errors.As(err, &late) && late.Timeout() { + return nil, refused{"FormTxt did not answer within 100 seconds, so FormLedger drew the plain page. If FormTxt is asking Allow outside agents?, answer it and print again."} + } return nil, ErrUnavailable } + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 8192)) resp.Body.Close() if resp.StatusCode != http.StatusOK { - return nil, ErrUnavailable + var why struct { + Detail any `json:"detail"` + } + _ = json.Unmarshal(raw, &why) + detail, _ := why.Detail.(string) + switch resp.StatusCode { + case http.StatusForbidden: + return nil, refused{"FormTxt refused to draw the page, so FormLedger drew the plain page. FormTxt said: " + strings.TrimSpace(detail) + " Open FormTxt, allow outside agents when it asks, or turn on Allow outside agents in its Preferences under Privacy, then print again."} + case http.StatusNotFound: + return nil, refused{"FormTxt has no template " + template + " for " + kind + ". Set FORMLEDGER_FORMTXT_TEMPLATE_" + strings.ToUpper(strings.ReplaceAll(kind, "-", "_")) + " to the id of a FormTxt document with merge fields."} + } + return nil, refused{"FormTxt could not draw the page (" + resp.Status + ": " + detail + "), so FormLedger drew the plain page."} } pdf, err := os.ReadFile(out) if err != nil || !bytes.HasPrefix(pdf, []byte("%PDF")) { - return nil, ErrUnavailable + return nil, refused{"FormTxt answered but wrote no PDF, so FormLedger drew the plain page."} } return pdf, nil } + +type refused struct{ why string } + +func (r refused) Error() string { return r.why } + +func (refused) Is(target error) bool { return target == ErrUnavailable } diff --git a/internal/printout/module.go b/internal/printout/module.go index b6637b1..3c90aea 100644 --- a/internal/printout/module.go +++ b/internal/printout/module.go @@ -51,15 +51,16 @@ func (module) Mount(rt *httpx.Router, d *app.Deps) error { } st, err := DecodeStatement(raw, company) var body []byte - var by string + var by, note string if err == nil { - body, by, err = RenderStatement(st, r.URL.Query().Get("renderer") == "plain") + body, by, note, err = RenderStatement(st, r.URL.Query().Get("renderer") == "plain") } if err != nil { httpx.Error(w, http.StatusInternalServerError, "internal", "the PDF could not be drawn") return } w.Header().Set("X-FormLedger-Renderer", by) + setNote(w, note) w.Header().Set("Content-Type", "application/pdf") w.Header().Set("Content-Disposition", `attachment; filename="statement-`+safeName(st.Customer.Code)+`-`+safeName(st.To)+`.pdf"`) _, _ = w.Write(body) @@ -95,12 +96,13 @@ func (module) Mount(rt *httpx.Router, d *app.Deps) error { httpx.Error(w, http.StatusNotFound, "not_found", "no "+r.PathValue("kind")+" with that id or number") return } - body, by, err := Render(doc, r.URL.Query().Get("renderer") == "plain") + body, by, note, err := Render(doc, r.URL.Query().Get("renderer") == "plain") if err != nil { httpx.Error(w, http.StatusInternalServerError, "internal", "the PDF could not be drawn") return } w.Header().Set("X-FormLedger-Renderer", by) + setNote(w, note) name := doc.Number if name == "" { name = doc.Kind + "-draft" @@ -112,6 +114,12 @@ func (module) Mount(rt *httpx.Router, d *app.Deps) error { return nil } +func setNote(w http.ResponseWriter, note string) { + if note != "" { + w.Header().Set("X-FormLedger-Renderer-Note", url.PathEscape(note)) + } +} + func safeName(s string) string { var b strings.Builder for _, r := range s { diff --git a/internal/server/server.go b/internal/server/server.go index be4ce9f..29724fd 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -29,6 +29,7 @@ import ( "github.com/nodemode-ai/formledger/internal/reports" "github.com/nodemode-ai/formledger/internal/sales" "github.com/nodemode-ai/formledger/internal/salesflow" + "github.com/nodemode-ai/formledger/internal/snapshot" "github.com/nodemode-ai/formledger/internal/static" "github.com/nodemode-ai/formledger/internal/stock" "github.com/nodemode-ai/formledger/internal/store" @@ -74,6 +75,7 @@ func Build(ctx context.Context, cfg config.Config, log *slog.Logger, st *store.S reports.Module(accounts), sales.Module(accounts), salesflow.Module(st, accounts), + snapshot.Module(accounts), stock.Module(st, accounts), suppliers.Module(st, accounts), taxrates.Module(accounts), diff --git a/internal/snapshot/route.go b/internal/snapshot/route.go new file mode 100644 index 0000000..cab036c --- /dev/null +++ b/internal/snapshot/route.go @@ -0,0 +1,69 @@ +package snapshot + +import ( + "net/http" + "os" + "path/filepath" + "sort" + "sync" + "time" + + "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" +) + +type module struct { + auth *auth.Service + busy *sync.Mutex +} + +func Module(a *auth.Service) app.Module { return module{a, &sync.Mutex{}} } + +func (module) ID() string { return "snapshot" } + +type table struct { + Name string `json:"name"` + Rows int64 `json:"rows"` +} + +type written struct { + File string `json:"file"` + Folder string `json:"folder"` + Path string `json:"path"` + Tables []table `json:"tables"` + Rows int64 `json:"rows"` +} + +func (m module) Mount(r *httpx.Router, d *app.Deps) error { + r.HandleFunc("POST /api/snapshot", m.auth.Require(policy.SettingsManage, func(w http.ResponseWriter, req *http.Request, _ *policy.Principal) error { + if !m.busy.TryLock() { + return httpx.Fail(http.StatusConflict, "snapshot_busy", "A snapshot is being written. Try again in a moment.") + } + defer m.busy.Unlock() + dir := filepath.Join(d.Config.DataDir, "snapshots") + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + now := time.Now() + loc, err := time.LoadLocation(TimeZone) + if err != nil { + loc = time.Local + } + name := "formledger-snapshot-" + now.In(loc).Format("2006-01-02-150405") + ".sqlite" + res, err := Write(req.Context(), d.Store, filepath.Join(dir, name), Options{Now: now}) + if err != nil { + return err + } + out := written{File: name, Folder: "snapshots", Path: res.Path, Tables: []table{}} + for k, n := range res.Tables { + out.Tables = append(out.Tables, table{k, n}) + out.Rows += n + } + sort.Slice(out.Tables, func(i, j int) bool { return out.Tables[i].Name < out.Tables[j].Name }) + httpx.JSON(w, http.StatusCreated, out) + return nil + })) + return nil +} diff --git a/internal/store/encrypt.go b/internal/store/encrypt.go index 2f8cb0a..5caae56 100644 --- a/internal/store/encrypt.go +++ b/internal/store/encrypt.go @@ -8,25 +8,26 @@ import ( "os" "path/filepath" "strings" + "time" "github.com/nodemode-ai/formledger/internal/crypt" ) -func Encrypt(ctx context.Context, dataDir, keyFile string) error { +func Encrypt(ctx context.Context, dataDir, keyFile string) (string, error) { path := crypt.KeyPath(keyFile) if path == "" { - return errors.New("set FORMLEDGER_KEY_FILE to the key (formledger keygen makes one, keep it outside the data directory)") + return "", errors.New("set FORMLEDGER_KEY_FILE to the key (formledger keygen makes one, keep it outside the data directory)") } key, err := crypt.ReadKey(path) if err != nil { - return err + return "", err } if crypt.Encrypted(dataDir) { _, err := crypt.Load(dataDir, path, true) - return err + return "", err } if !HasData(dataDir) { - return errors.New("there is no ledger to encrypt; start FormLedger with FORMLEDGER_KEY_FILE set and it is encrypted from the first write") + return "", errors.New("there is no ledger to encrypt; start FormLedger with FORMLEDGER_KEY_FILE set and it is encrypted from the first write") } dbPath := filepath.Join(dataDir, FileName) @@ -34,43 +35,67 @@ func Encrypt(ctx context.Context, dataDir, keyFile string) error { os.Remove(encPath) plain, err := sql.Open("sqlite", dbPath+"?_pragma=busy_timeout(5000)") if err != nil { - return err + return "", err } if _, err := plain.ExecContext(ctx, "PRAGMA wal_checkpoint(TRUNCATE)"); err != nil { plain.Close() - return err + return "", err } + copyPath := plainCopyName(dataDir, time.Now()) + if _, err := plain.ExecContext(ctx, "VACUUM INTO "+sqlString(copyPath)); err != nil { + plain.Close() + os.Remove(copyPath) + return "", fmt.Errorf("keeping a plain copy: %w", err) + } + os.Chmod(copyPath, 0o600) if err := Register(key); err != nil { plain.Close() - return err + os.Remove(copyPath) + return "", err } _, err = plain.ExecContext(ctx, "VACUUM INTO "+sqlString("file:"+encPath+"?vfs="+VFSName)) plain.Close() if err != nil { os.Remove(encPath) - return fmt.Errorf("encrypting the database: %w", err) + os.Remove(copyPath) + return "", fmt.Errorf("encrypting the database: %w", err) } enc, err := sql.Open("sqlite", "file:"+encPath+"?vfs="+VFSName) if err != nil { - return err + os.Remove(copyPath) + return "", err } var check string err = enc.QueryRowContext(ctx, "PRAGMA integrity_check").Scan(&check) enc.Close() if err != nil || check != "ok" { os.Remove(encPath) - return fmt.Errorf("the encrypted copy failed its check: %v %s", err, check) + os.Remove(copyPath) + return "", fmt.Errorf("the encrypted copy failed its check: %v %s", err, check) } if err := os.Chmod(encPath, 0o600); err != nil { - return err + return "", err } if err := os.Rename(encPath, dbPath); err != nil { - return err + return "", err } for _, suffix := range []string{"-wal", "-shm"} { os.Remove(dbPath + suffix) } - return key.WriteMeta(dataDir) + return copyPath, key.WriteMeta(dataDir) +} + +const PlainCopyNote = "This copy is NOT encrypted: anyone who can read the file can read your books. Delete it or move it somewhere safe once you are sure the encrypted ledger opens." + +func plainCopyName(dataDir string, now time.Time) string { + base := filepath.Join(dataDir, "formledger-plain-copy-"+now.Format("2006-01-02")) + p := base + ".db" + for n := 2; ; n++ { + if _, err := os.Lstat(p); errors.Is(err, os.ErrNotExist) { + return p + } + p = fmt.Sprintf("%s-%d.db", base, n) + } } func sqlString(s string) string { diff --git a/internal/templates/template.go b/internal/templates/template.go index a7bbad5..7c6b601 100644 --- a/internal/templates/template.go +++ b/internal/templates/template.go @@ -25,6 +25,7 @@ type Line struct { CurrentPrice bool `json:"currentPrice"` TaxRate string `json:"taxRate,omitempty"` Account string `json:"account,omitempty"` + AccountName string `json:"accountName,omitempty"` } type Template struct { @@ -130,7 +131,7 @@ func clean(t *Template) error { } for i := range t.Lines { l := &t.Lines[i] - l.Item, l.Description = strings.TrimSpace(l.Item), strings.TrimSpace(l.Description) + l.Item, l.Description, l.AccountName = strings.TrimSpace(l.Item), strings.TrimSpace(l.Description), "" if l.Item == "" && l.Description == "" { return invalid("bad_line", "each line needs an item or a description") } @@ -156,14 +157,46 @@ func scan(row interface{ Scan(...any) error }) (Template, error) { const cols = `id, kind, name, description, category, party_id, currency, terms_days, notes, lines_json, created_at, updated_at` +func (s *Service) accountNames(ctx context.Context) (map[string]string, error) { + rows, err := s.st.R.QueryContext(ctx, `SELECT code, name FROM accounts`) + if err != nil { + return nil, err + } + defer rows.Close() + names := map[string]string{} + for rows.Next() { + var code, name string + if err := rows.Scan(&code, &name); err != nil { + return nil, err + } + names[code] = name + } + return names, rows.Err() +} + +func nameLines(t *Template, names map[string]string) { + lines := make([]Line, len(t.Lines)) + for i, l := range t.Lines { + l.AccountName = names[l.Account] + lines[i] = l + } + t.Lines = lines +} + func (s *Service) Get(ctx context.Context, id string) (Template, error) { + names, err := s.accountNames(ctx) + if err != nil { + return Template{}, err + } if t, ok := builtin(id); ok { + nameLines(&t, names) return t, nil } t, err := scan(s.st.R.QueryRowContext(ctx, `SELECT `+cols+` FROM doc_templates WHERE id = ?`, id)) if errors.Is(err, sql.ErrNoRows) { return t, fail(http.StatusNotFound, "template_not_found", "no template with id "+id) } + nameLines(&t, names) return t, err } @@ -203,7 +236,18 @@ func (s *Service) List(ctx context.Context, kind, q string) ([]Template, error) } } sort.SliceStable(own, func(i, j int) bool { return strings.ToLower(own[i].Name) < strings.ToLower(own[j].Name) }) - return append(out, own...), rows.Err() + if err := rows.Err(); err != nil { + return nil, err + } + out = append(out, own...) + names, err := s.accountNames(ctx) + if err != nil { + return nil, err + } + for i := range out { + nameLines(&out[i], names) + } + return out, nil } func (s *Service) Create(ctx context.Context, q store.Querier, t Template) (Template, error) { @@ -253,7 +297,7 @@ func (s *Service) Use(ctx context.Context, t Template, today time.Time) (map[str info := kinds[t.Kind] lines := make([]map[string]any, 0, len(t.Lines)) for _, l := range t.Lines { - out := map[string]any{"description": l.Description, "quantityMilli": l.QuantityMilli, "unitPrice": l.UnitPrice, "taxRate": l.TaxRate, "account": l.Account} + out := map[string]any{"description": l.Description, "quantityMilli": l.QuantityMilli, "unitPrice": l.UnitPrice, "taxRate": l.TaxRate, "account": l.Account, "accountName": l.AccountName} if l.Item != "" { it, err := s.items.Get(ctx, nil, l.Item) if err != nil { diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 349790a..da1f62d 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1106,7 +1106,7 @@ dependencies = [ [[package]] name = "formledger-desktop" -version = "0.11.0" +version = "0.12.0" dependencies = [ "objc2", "objc2-app-kit", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 3b189a2..b49c1e8 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formledger-desktop" -version = "0.11.0" +version = "0.12.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 a9d2e38..8474f12 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.11.0 +Current build version: v0.12.0 Last updated: 2026-11-26 (US Eastern) · the shell ported from form.md's src-tauri and renamed for FormLedger --- @@ -324,3 +324,17 @@ The owner supplied the official artwork on 2026-11-26; the six originals (1024 p - logged: v0.10.0 · 2026-11-27 Ported from form.md `src-tauri/src/menu.rs` and its wiring in `src-tauri/src/main.rs` (`manage(menu::Zoom)`, `on_menu_event(menu::handle)`). An item id `cmd:[command]` evaluates `window.__formledgerRun(command)` in the main window, which runs the window command of that id; `zoom:`, `app:reload` and `app:notices` are handled here. The Go menu lists every screen by `cmd:go.[view id]`; the window registers those commands in `web/src/ui/views.ts`. The menubar is still built on macOS only, as before. It has not been compiled: this sandbox has no GTK, so `cargo check` cannot run here. + +### src/engine_start.rs · key_home +- refers-to: src/engine_start.rs :: KEY_HOME_ENV, key_home; src/main.rs :: start (not yet wired) +- kind: todo +- logged: v0.12.0 · 2026-11-27 + +`key_home` returns the pair `FORMLEDGER_KEY_HOME` = the app's own data folder, or nothing when `FORMLEDGER_KEY_FILE` is set in the shell's environment. The server makes the key there once and encrypts the ledger (see internal/HASHOUT_LOG.md, desktop key). main.rs, owned by another slice, must add one line to the sidecar chain in `start`: `.envs(engine_start::key_home(handle.path().app_data_dir().ok()))`. Until it does, the desktop stays plain. engine_start.rs compiled alone with `rustc --crate-type lib`; main.rs and the crate were not compiled (no GTK here). + +### src/menu.rs, src/main.rs · menubar read line by line, Search on Cmd or Ctrl+P +- refers-to: src/menu.rs :: build, item, screens, handle; src/main.rs :: main, start +- kind: rationale +- 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. diff --git a/src-tauri/src/engine_start.rs b/src-tauri/src/engine_start.rs index bcd86dc..ef6480b 100644 --- a/src-tauri/src/engine_start.rs +++ b/src-tauri/src/engine_start.rs @@ -4,6 +4,7 @@ use std::time::Duration; pub const APP: &str = "FormLedger"; pub const SHELL_ENV: &str = "FORMLEDGER_SHELL_PID"; +pub const KEY_HOME_ENV: &str = "FORMLEDGER_KEY_HOME"; pub const ADDRESS_WAIT: Duration = Duration::from_secs(90); pub const EXIT_WAIT: Duration = Duration::from_secs(1); pub const BUSY_CODE: i32 = 2; @@ -70,6 +71,14 @@ pub fn message(failure: &Failure, lines: &[String], log: Option<&Path>) -> Strin text } +pub fn key_home(app_data: Option) -> Option<(&'static str, PathBuf)> { + let configured = std::env::var_os("FORMLEDGER_KEY_FILE").is_some_and(|v| !v.is_empty()); + if configured { + return None; + } + app_data.map(|folder| (KEY_HOME_ENV, folder)) +} + pub fn keep(folder: &Path, lines: &[String]) -> Option { if lines.is_empty() { return None; diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 0b3b498..7a4e294 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -219,6 +219,7 @@ fn start(handle: AppHandle) { .env("FORMLEDGER_DATA", dir.as_os_str()) .env("FORMLEDGER_ADDR", PREFERRED_ADDR) .env(engine_start::SHELL_ENV, std::process::id().to_string()) + .envs(engine_start::key_home(handle.path().app_data_dir().ok())) .spawn() }); let (mut rx, child) = match spawned { diff --git a/src-tauri/src/menu.rs b/src-tauri/src/menu.rs index 2d092f2..70947a6 100644 --- a/src-tauri/src/menu.rs +++ b/src-tauri/src/menu.rs @@ -79,10 +79,10 @@ pub fn build(app: &AppHandle) -> tauri::Result> { .item(&item(app, "cmd:new.paymentOut", "Make Payment", None)?) .separator() .item(&item(app, "cmd:file.exportCsv", "Export CSV...", None)?) - .item(&item(app, "cmd:file.print", "Print...", Some("CmdOrCtrl+P"))?) - .item(&item(app, "cmd:file.snapshot", "Write Snapshot...", None)?) + .item(&item(app, "cmd:file.print", "Print...", Some("CmdOrCtrl+Alt+P"))?) + .item(&item(app, "cmd:file.snapshot", "Write Snapshot", None)?) .separator() - .item(&item(app, "cmd:palette.open", "Find a Command...", None)?) + .item(&item(app, "cmd:palette.open", "Search...", Some("CmdOrCtrl+P"))?) .separator() .close_window() .build()?; diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 01aa3fa..98e50a0 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.11.0", + "version": "0.12.0", "identifier": "ai.nodemode.formledger", "build": { "frontendDist": "splash" }, "app": { diff --git a/web/HASHOUT_LOG.md b/web/HASHOUT_LOG.md index f7db438..67cf141 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.11.0 +Current build version: v0.12.0 Last updated: 2026-11-26 (US Eastern) · account screens, and the fixes from the throttled browser check --- @@ -712,3 +712,24 @@ Ported from form.md `web/src/ui/bar-chart.ts` (the reuse-in-place `svg` and rect - logged: v0.10.0 · 2026-11-27 Ported from form.md `web/src/ui/templates-dialog.ts` (rail with search and category counts, card grid) and `web/src/styles/templates.css` (`.tplgal__*`, `.tplcard`, `.tplcard__flag`), as a page instead of a dialog and with token sizes. The gallery draws eight placeholder cards at final size before the list arrives and then writes into them; Edit and Delete keep their slot with `visibility` on built-in cards. Save as template and Print sit in the page head, not in `.df-actions`, so the action row cannot wrap and `.df-actions button` index 1 stays Post or Confirm; the name field lives in a fixed `30ch` box and Print is hidden with `visibility` on a new draft. A free line from a template keeps its account in a description-to-account map, because the line grid has no account column; the draft body sends it as `incomeAccount` or `expenseAccount`. + +### src/ui/views/templates.ts · Zero shift and named accounts on template cards +- refers-to: src/ui/views/templates.ts :: accountLabel, accountsOf, makeCard, writeCard; src/styles/views/templates.css :: .tplcard__text, .tplcard__accts +- kind: rationale +- logged: v0.12.0 · 2026-11-27 + +The 0.00007 to 0.00033 shift came from `.tplcard__meta`: on a placeholder card the empty name span was zero high, so the meta line filled the stretch row and dropped 4 px when the names arrived. `.tplcard__text` now fixes its rows (a control-high name row and two text rows), which also reserves the new accounts line. That line reads "Posts to 4100 Sales · 4900 Other income" from `accountName`, which the server looks up from the chart on every read, so a renamed account shows its new name; the full list is the line's tooltip and each preview row carries its own account as a tooltip. A template whose lines all name items reads "Posts to item accounts". Checked under 4x CPU and the slowed network after a hard reload at 1400 by 900: layout shift 0 without input and 0 with input. + +### src/ui/parts/chart.ts, src/styles/views/dashboards.css · Dashboards measured against a running form.md +- refers-to: src/ui/parts/chart.ts :: axisLabel, xyChart; src/styles/views/dashboards.css :: .dash__card, .kpi, .kpi__figure +- kind: rationale +- logged: v0.12.0 · 2026-11-27 + +Measured side by side at 1400 by 900, dark, against a form.md build run from a copy (its Sales dashboard template). Same on both sides: card padding 8 px and 12 px, card background, 1 px border at 0.075 white, 32 px head, 12.5 px semibold muted title, 11 px faint axis labels, dashed grid, 2 px line, 0.12 area. Different and changed: card radius was 14 px here against 12 px (now `--radius` plus `--radius-xs`); the KPI figure was 22 px at weight 600 against form.md's 40 px at 650 with -0.02em tracking (now `--text-title`, 650, the same tracking; 40 px does not fit a one-quarter card holding "1,852.20 USD"); the value axis printed "250.30" where form.md prints "$80K" (now compact figures from `Intl.NumberFormat`, assuming two minor digits, with hover readouts still exact). Left alone: form.md KPI body is 150 px against 132 px here (a taller card would push the second row down on every view), form.md draws point dots with value labels on line charts and puts the change figure beside the number, and form.md keeps its legend inside the SVG; each would add reserved height or restructure the card. Checked under 4x CPU and the slowed network after a hard reload at 1400 by 900: layout shift on the dashboards 0 without input and 0 with input; the only shift entry (0.0001) is the shell breadcrumb title. + +### src/ui/snapshot-action.ts, src/ui/command-palette.ts, src/styles/palette.css · Write Snapshot and the palette columns +- refers-to: src/ui/snapshot-action.ts :: writeSnapshot; src/ui/command-palette.ts :: KEYS; src/styles/palette.css :: .cpal__row, .cpal__group, .cpal__keys +- kind: rationale +- logged: v0.12.0 · 2026-11-27 + +`writeSnapshot` posts to `/api/snapshot` and shows one toast (id `snapshot`) only when the answer comes: the absolute path, the table count and the row count; a 403 reads "Only the owner can write a snapshot." A waiting toast was tried first and dropped: it grew from one line to four when the answer replaced it and moved by 0.00108. A second call while one runs is ignored. The `file.snapshot` command in `app.ts` still shows the old command-line hint until its owner points it at `writeSnapshot(engine)`; the check ran on a private copy with that change. Palette rows were `1fr auto auto`, so the group label moved sideways whenever the row's text or key hint changed (0.0001 with input while typing); the columns are now `1fr 12ch 10ch` with the group placed in the trailing column and the key hint ending against it. Print shows Cmd or Ctrl+Alt+P because Cmd or Ctrl+P now opens Search, as in form.md. Checked under 4x CPU and the slowed network at 1400 by 900, palette open, "snapshot" typed, Enter: layout shift 0 without input and 0 with input. diff --git a/web/package-lock.json b/web/package-lock.json index 11c13b4..3b8c389 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -1,12 +1,12 @@ { "name": "formledger", - "version": "0.11.0", + "version": "0.12.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formledger", - "version": "0.11.0", + "version": "0.12.0", "license": "Apache-2.0", "devDependencies": { "@types/node": "^22.20.5", diff --git a/web/package.json b/web/package.json index df2933a..a5bb613 100644 --- a/web/package.json +++ b/web/package.json @@ -1,7 +1,7 @@ { "name": "formledger", "private": true, - "version": "0.11.0", + "version": "0.12.0", "license": "Apache-2.0", "type": "module", "scripts": { diff --git a/web/src/engine/templates.ts b/web/src/engine/templates.ts index 0c63478..f2d0e4e 100644 --- a/web/src/engine/templates.ts +++ b/web/src/engine/templates.ts @@ -11,6 +11,7 @@ export interface TemplateLine { currentPrice: boolean; taxRate?: string | undefined; account?: string | undefined; + accountName?: string | undefined; } export interface Template { @@ -35,6 +36,7 @@ export interface UsedLine { unitPrice: number; taxRate: string; account?: string; + accountName?: string; } export interface UsedDraft { diff --git a/web/src/styles/palette.css b/web/src/styles/palette.css index 9db8d02..ed95961 100644 --- a/web/src/styles/palette.css +++ b/web/src/styles/palette.css @@ -90,7 +90,7 @@ .cpal__row { display: grid; - grid-template-columns: minmax(0, 1fr) auto auto; + grid-template-columns: minmax(0, 1fr) 12ch 10ch; align-items: center; column-gap: var(--space-3); padding: 0 var(--space-2); @@ -133,9 +133,16 @@ font-size: var(--text-xs); color: var(--text-faint); white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + text-align: end; + grid-column: 3; + grid-row: 1; } .cpal__keys { + grid-column: 2; + grid-row: 1; min-inline-size: 0; padding: 0; font-family: var(--font-mono); @@ -143,10 +150,7 @@ color: var(--text-muted); background: transparent; border: 0; -} - -.cpal__keys:empty { - display: none; + justify-self: end; } .cpal__none { diff --git a/web/src/styles/views/dashboards.css b/web/src/styles/views/dashboards.css index a4ef7a8..dbb1f6d 100644 --- a/web/src/styles/views/dashboards.css +++ b/web/src/styles/views/dashboards.css @@ -55,7 +55,7 @@ padding: var(--space-2) var(--space-3) var(--space-3); background: var(--surface); border: 1px solid var(--border); - border-radius: var(--radius-lg, var(--radius-sheet)); + border-radius: calc(var(--radius) + var(--radius-xs)); } .dash__card[data-kind="kpi"] { @@ -115,15 +115,16 @@ .kpi { display: grid; - grid-template-rows: calc(var(--text-xl) * 1.25) 40px calc(var(--text-xs) * 2); + grid-template-rows: calc(var(--text-title) * 1.25) 40px calc(var(--text-xs) * 2); row-gap: var(--space-2); block-size: 100%; } .kpi__figure { margin: 0; - font-size: var(--text-xl); - font-weight: var(--weight-semibold, 600); + font-size: var(--text-title); + font-weight: 650; + letter-spacing: -0.02em; line-height: 1.25; color: var(--text); white-space: nowrap; diff --git a/web/src/styles/views/templates.css b/web/src/styles/views/templates.css index 981bc1c..968c6d9 100644 --- a/web/src/styles/views/templates.css +++ b/web/src/styles/views/templates.css @@ -300,8 +300,8 @@ .tplcard__text { display: grid; + grid-template-rows: var(--control) repeat(2, calc(var(--text-xs) * var(--leading))); gap: 2px; - block-size: calc(var(--control) + var(--text-xs) * var(--leading)); padding: 0 var(--space-2); } @@ -318,7 +318,8 @@ block-size: var(--control); } -.tplcard__meta { +.tplcard__meta, +.tplcard__accts { overflow: hidden; font-size: var(--text-xs); color: var(--text-faint); @@ -349,7 +350,8 @@ } .tplcard.is-pending .tplcard__name, -.tplcard.is-pending .tplcard__meta { +.tplcard.is-pending .tplcard__meta, +.tplcard.is-pending .tplcard__accts { background: var(--hover); border-radius: var(--radius-xs); } diff --git a/web/src/ui/app.ts b/web/src/ui/app.ts index 69a8b5c..2842a49 100644 --- a/web/src/ui/app.ts +++ b/web/src/ui/app.ts @@ -2,6 +2,7 @@ import type { Engine, Health } from "../engine"; import { money } from "../engine/format"; import { byId, delayedIndicator, h, ref, setAttr, setText } from "./dom"; import { openPalette } from "./command-palette"; +import { writeSnapshot } from "./snapshot-action"; import { dismissToast, toast } from "./toast"; import { mountAccount } from "./account"; import { hashFor, mountViews } from "./views"; @@ -302,9 +303,7 @@ function bindCommands(engine: Engine): void { else toast({ tone: "info", message: "This screen has nothing to export. Open a list or a report first." }); }); add("file.print", "Print", "File", () => window.print()); - add("file.snapshot", "Write snapshot", "File", () => - toast({ tone: "info", message: "A snapshot is written from the command line: formledger snapshot [file]." }), - ); + add("file.snapshot", "Write snapshot", "File", () => void writeSnapshot(engine)); add("nav.back", "Back", "View", () => history.back()); add("nav.forward", "Forward", "View", () => history.forward()); add("shell.toggleSidebar", "Toggle sidebar", "View", () => { @@ -321,14 +320,15 @@ function bindCommands(engine: Engine): void { applyTheme(next); }); add("shell.showShortcuts", "Keyboard shortcuts", "Help", () => - toast({ tone: "info", message: "Find a command: Ctrl or Cmd+Shift+P. Sidebar: Ctrl or Cmd+\\. Dark mode: Ctrl or Cmd+Shift+L. Back and forward: Ctrl or Cmd+[ and ]." }), + toast({ tone: "info", message: "Search: Ctrl or Cmd+P. Find a command: Ctrl or Cmd+Shift+P. Print: Ctrl or Cmd+Alt+P. Sidebar: Ctrl or Cmd+\\. Dark mode: Ctrl or Cmd+Shift+L. Back and forward: Ctrl or Cmd+[ and ]." }), ); ref("nav-search").addEventListener("click", () => engine.commands.run("palette.open")); document.addEventListener("keydown", (e) => { const mod = e.metaKey || e.ctrlKey; - if (!mod || e.altKey) return; + if (!mod) return; const k = e.key.toLowerCase(); - const id = e.shiftKey && k === "p" ? "palette.open" : e.shiftKey && k === "l" ? "shell.theme.toggle" : !e.shiftKey && e.key === "\\" ? "shell.toggleSidebar" : null; + const p = e.code === "KeyP"; + const id = e.altKey ? (p && !e.shiftKey ? "file.print" : null) : p ? "palette.open" : e.shiftKey && k === "l" ? "shell.theme.toggle" : !e.shiftKey && e.key === "\\" ? "shell.toggleSidebar" : null; if (!id || !inApp()) return; e.preventDefault(); engine.commands.run(id); diff --git a/web/src/ui/command-palette.ts b/web/src/ui/command-palette.ts index 0794b2c..5829455 100644 --- a/web/src/ui/command-palette.ts +++ b/web/src/ui/command-palette.ts @@ -223,7 +223,7 @@ const KEYS: Record = { "shell.theme.toggle": MAC ? "⇧⌘L" : "Ctrl+Shift+L", "nav.back": MAC ? "⌘[" : "Ctrl+[", "nav.forward": MAC ? "⌘]" : "Ctrl+]", - "file.print": MAC ? "⌘P" : "Ctrl+P", + "file.print": MAC ? "⌥⌘P" : "Ctrl+Alt+P", }; let palette: Palette | null = null; diff --git a/web/src/ui/parts/chart.ts b/web/src/ui/parts/chart.ts index 5509b45..45160ea 100644 --- a/web/src/ui/parts/chart.ts +++ b/web/src/ui/parts/chart.ts @@ -57,6 +57,12 @@ export function monthName(period: string, withYear = false): string { return withYear ? `${m} ${period.slice(0, 4)}` : m; } +const COMPACT = new Intl.NumberFormat("en-US", { notation: "compact", maximumFractionDigits: 1 }); + +function axisLabel(minor: number): string { + return COMPACT.format(Math.round(minor / 100)); +} + function scale(values: number[]): { lo: number; hi: number } { let lo = Math.min(0, ...values); let hi = Math.max(0, ...values); @@ -124,7 +130,7 @@ export function xyChart(kind: "bars" | "line", label: string, fmt: Fmt, area = f }); fit(ticks, levels.length, () => svg("text", { class: "chart__tick", x: String(LEFT - 6), "text-anchor": "end", "dominant-baseline": "middle" })).forEach((t, i) => { t.setAttribute("y", y(levels[i] ?? 0).toFixed(1)); - t.textContent = fmt(Math.round(levels[i] ?? 0)); + t.textContent = axisLabel(levels[i] ?? 0); }); const zy = y(0).toFixed(1); zero.setAttribute("y1", zy); diff --git a/web/src/ui/snapshot-action.ts b/web/src/ui/snapshot-action.ts new file mode 100644 index 0000000..c854706 --- /dev/null +++ b/web/src/ui/snapshot-action.ts @@ -0,0 +1,34 @@ +import { ApiError, type Engine } from "../engine"; +import { toast } from "./toast"; + +interface Written { + file: string; + folder: string; + path: string; + tables: { name: string; rows: number }[]; + rows: number; +} + +const ID = "snapshot"; +let running = false; + +const count = (n: number, one: string, many: string): string => `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`; + +export async function writeSnapshot(engine: Engine): Promise { + if (running) return; + running = true; + try { + const w = await engine.api.call("POST", "/api/snapshot"); + toast({ + id: ID, + tone: "success", + message: `Snapshot written to ${w.path}. It holds ${count(w.tables.length, "table", "tables")} and ${count(w.rows, "row", "rows")}.`, + durationMs: 12000, + }); + } catch (e) { + const message = e instanceof ApiError && e.status === 403 ? "Only the owner can write a snapshot." : e instanceof Error ? e.message : "The snapshot was not written."; + toast({ id: ID, tone: "danger", message, durationMs: 8000 }); + } finally { + running = false; + } +} diff --git a/web/src/ui/views/templates.ts b/web/src/ui/views/templates.ts index 241f931..d99c891 100644 --- a/web/src/ui/views/templates.ts +++ b/web/src/ui/views/templates.ts @@ -30,6 +30,7 @@ interface Card { total: HTMLElement; name: HTMLElement; meta: HTMLElement; + accts: HTMLElement; flag: HTMLElement; use: HTMLButtonElement; edit: HTMLButtonElement; @@ -48,6 +49,20 @@ function money(n: number, currency: string): string { return currency ? `${formatMoney(n)} ${currency}` : formatMoney(n); } +function accountLabel(l: { account?: string | undefined; accountName?: string | undefined }): string { + if (!l.account) return ""; + return l.accountName ? `${l.account} ${l.accountName}` : l.account; +} + +function accountsOf(t: Template): string { + const seen = new Set(); + for (const l of t.lines) { + const label = accountLabel(l as { account?: string; accountName?: string }); + if (label) seen.add(label); + } + return [...seen].join(" · "); +} + function makeCard(): Card { const kind = h("span", { class: "tplmini__kind" }); const party = h("span", { class: "tplmini__party" }); @@ -69,6 +84,7 @@ function makeCard(): Card { const name = h("span", { class: "tplcard__name" }); const rename = h("input", { class: "input tplcard__rename", attrs: { type: "text", maxlength: "120", "aria-label": "Template name", hidden: "" } }); const meta = h("span", { class: "tplcard__meta" }); + const accts = h("span", { class: "tplcard__accts" }); const use = h("button", { class: "btn btn--primary tplcard__use", attrs: { type: "button" }, text: "Use" }); const edit = btn("Edit", "tplcard__edit"); const dup = btn("Duplicate", "tplcard__dup"); @@ -77,10 +93,10 @@ function makeCard(): Card { "article", { class: "tplcard is-pending", attrs: { "aria-busy": "true" } }, h("div", { class: "tplcard__thumb" }, mini, flag), - h("div", { class: "tplcard__text" }, name, rename, meta), + h("div", { class: "tplcard__text" }, name, rename, meta, accts), h("div", { class: "tplcard__actions" }, use, dup, edit, del), ); - return { el, kind, party, rows, total, name, meta, flag, use, edit, dup, del, rename, t: null, armed: false }; + return { el, kind, party, rows, total, name, meta, accts, flag, use, edit, dup, del, rename, t: null, armed: false }; } function writeCard(c: Card, t: Template, canWrite: boolean): void { @@ -96,11 +112,15 @@ function writeCard(c: Card, t: Template, canWrite: boolean): void { const l = t.lines[i]; r.row.classList.toggle("is-empty", !l); setText(r.desc, l ? l.description || l.item || "" : ""); + setAttr(r.row, "title", l ? accountLabel(l as { account?: string; accountName?: string }) || null : null); setText(r.amt, l ? (l.currentPrice ? "current price" : money(lineTotal(l), t.currency)) : ""); }); setText(c.total, money(t.lines.reduce((s, l) => s + lineTotal(l), 0), t.currency)); setText(c.name, t.name); setText(c.meta, `${KIND_LABELS[t.kind]} · ${t.lines.length} ${t.lines.length === 1 ? "line" : "lines"}`); + const accts = accountsOf(t); + setText(c.accts, accts ? `Posts to ${accts}` : "Posts to item accounts"); + setAttr(c.accts, "title", accts || null); setText(c.flag, t.builtIn ? "Built in" : "Yours"); setAttr(c.flag, "data-tone", t.builtIn ? "builtin" : "own"); setText(c.del, "Delete");