Calculation history #7

Open
opened 2026-11-21 03:35:34 +00:00 by lab-admin · 3 comments
Owner

Keep a short history of successful calculations.

Requirements

  • The server keeps the last 10 successful calculations in memory (newest first).
  • GET /api/history returns 200 {"items": [{"a": <number>, "b": <number or null>, "op": "<op>", "result": <number>}]}.
  • DELETE /api/history clears it and returns 204.
  • Failed calculations are not recorded.
  • UI: a "History" list under the calculator that refreshes after each = (and after √), and a "Clear history" button.
  • Tests for the history module/API (ordering, limit of 10, clearing, errors not recorded) and the page.

Acceptance criteria

  1. After 2+3 and 6*7, GET /api/history lists 6*7=42 first and 2+3=5 second.
  2. After 12 calculations only the newest 10 are returned.
  3. A failed calculation (division by zero) is not in the history.
  4. DELETE /api/history returns 204 and the history is empty afterwards.
  5. The page shows the history list and a Clear history button.
Keep a short history of successful calculations. ## Requirements - The server keeps the last 10 successful calculations in memory (newest first). - `GET /api/history` returns `200 {"items": [{"a": <number>, "b": <number or null>, "op": "<op>", "result": <number>}]}`. - `DELETE /api/history` clears it and returns `204`. - Failed calculations are not recorded. - UI: a "History" list under the calculator that refreshes after each `=` (and after `√`), and a "Clear history" button. - Tests for the history module/API (ordering, limit of 10, clearing, errors not recorded) and the page. ## Acceptance criteria 1. After `2+3` and `6*7`, `GET /api/history` lists `6*7=42` first and `2+3=5` second. 2. After 12 calculations only the newest 10 are returned. 3. A failed calculation (division by zero) is not in the history. 4. `DELETE /api/history` returns 204 and the history is empty afterwards. 5. The page shows the history list and a Clear history button.
Collaborator

Aira · queued

Aira picked up this task. Branch aira/7-calculation-history.

**Aira · queued** Aira picked up this task. Branch `aira/7-calculation-history`.
Collaborator

Aira · planning

Orchestrator thread started (composer-2.5). Planning on aira/7-calculation-history.

T3 thread: mcp:launch:cfee6f6953d7cba687fe8fa61ee2c740445048ea518c17ac65166190cd3e3070

**Aira · planning** Orchestrator thread started (composer-2.5). Planning on `aira/7-calculation-history`. T3 thread: `mcp:launch:cfee6f6953d7cba687fe8fa61ee2c740445048ea518c17ac65166190cd3e3070`
Collaborator

Aira · Plan (round 1) at 1aab3aae

Wrote issue-7 implementation plan (history module, API, UI, tests, risks), committed docs/plans/issue-7.md, ran npm test (50 pass), pushed aira/7-calculation-history.

docs/plans/issue-7.md

Issue #7: Calculation history

Goal

Keep a short in-memory history of successful calculations on the server (newest first, max 10), expose it via GET /api/history and DELETE /api/history, and show a History list with a Clear history control in the UI that updates after each successful = or √.

Acceptance criteria

  1. After 2+3 and 6*7, GET /api/history lists 6*7=42 first and 2+3=5 second.
  2. After 12 calculations only the newest 10 are returned.
  3. A failed calculation (division by zero) is not in the history.
  4. DELETE /api/history returns 204 and the history is empty afterwards.
  5. The page shows the history list and a Clear history button.

Design

History module (lib/history.js) — new

  • Single in-memory store (module-level array), no persistence across process restarts.
  • Entry shape: { a: number, b: number | null, op: string, result: number }.
    • For unary sqrt, store b: null (operands are the parsed numbers used in the calculation, not raw query strings).
  • record(entry): prepend the entry (newest first). If length exceeds 10, drop the oldest entries so at most 10 remain.
  • list(): return a shallow copy of the current array (newest first).
  • clear(): reset the store to [].
  • Export resetHistory() (alias of clear) for tests so HTTP suites can isolate cases without cross-test leakage from shared module state.

Pure logic only; no HTTP.

HTTP layer (server.js)

  • handleCalculate (after successful calculate):
    • Build history entry from request context: op from query; a as the finite number used for the left operand; b as null when op === 'sqrt', otherwise the finite number from b; result from calculate.
    • Reuse the same parsing rules as the calculator (call calculate first; on success, derive stored operands—e.g. parseNumber from lib/calculator.js for a, and for binary ops b, so stored values match what was computed).
    • Call record only on HTTP 200 success paths (never in the catch branch).
  • GET /api/history: 200 with {"items": [...]} where each item matches the entry shape above; empty store → {"items":[]}.
  • DELETE /api/history: clear(), respond 204 with no body (no JSON).
  • Unknown methods/paths on /api/history → existing 404 JSON pattern.

Recording uses the API op names (add, multiply, sqrt, etc.), consistent with query params.

UI (public/index.html)

  • Below the keypad (still inside main): a History section—heading, <ul id="history-list"> (or similar) for entries, and a Clear history button (id="clear-history" or data-action="clear-history").
  • refreshHistory(): fetch('/api/history'), parse items, render each row (e.g. a, op, b, result—format unary sqrt without a bogus b).
  • Call refreshHistory():
    • On load (show any existing history).
    • After successful = (inside the status === 200 branch).
    • After successful √ (same branch).
  • Clear history: click handler → fetch('/api/history', { method: 'DELETE' }), then refreshHistory() (list should empty).
  • Minimal CSS so the list is readable under the calculator (reuse existing system font / spacing).

Separation of concerns

Layer Responsibility
lib/history.js Cap, order, clear, list
lib/calculator.js Unchanged calculation semantics
server.js Routes, record on success only
public/index.html Display and refresh UX

Files to change

File Action
lib/history.js Create — in-memory store, record, list, clear, resetHistory
server.js Modify — record on successful calculate; GET/DELETE /api/history
public/index.html Modify — History list, Clear button, refreshHistory after = / √
test/history.test.js Create — unit tests for module
test/server.test.js Modify — HTTP tests for all acceptance criteria
test/ui.test.js Modify — History UI and script wiring
AGENTS.md Optional — document history API in implementation if Aira wants docs in sync (not required for AC).

Test plan

Unit (test/history.test.js)

Case Maps to
Empty list() → [] Design
record then list() returns newest first AC1 (module)
12 record calls → list() length 10, first item is the 12th recorded AC2 (module)
clear() then list() → [] AC4 (module)
Entries preserve a, b, op, result including b: null for sqrt-style entries API shape

Call resetHistory() in beforeEach (or start of each test) so tests are independent.

HTTP (test/server.test.js)

Use resetHistory() from lib/history.js at the start of each history-related test (or a dedicated beforeEach block) so ordering assertions are deterministic.

Case Expected Maps to
GET /api/history on fresh server → 200, { items: [] } Design
GET ...?a=2&b=3&op=add then GET ...?a=6&b=7&op=multiply, then GET /api/history Items[0]: multiply 42; items[1]: add 5 AC1
12 distinct successful GET /api/calculate requests GET /api/history → 10 items, newest matches last calculation AC2
GET ...?a=1&b=0&op=divide (400), then successful add History has no divide entry; only successes AC3
After some entries, DELETE /api/history → 204, empty body; GET /api/history → { items: [] } AC4
Successful GET ...?a=9&op=sqrt History item has b: null, op: 'sqrt' API shape
Failed calculate (invalid op, bad operand) does not append AC3 (extended)
Existing health, index, calculate regression tests still pass Regression

Assert DELETE response has no JSON body (e.g. res.status === 204 and empty or null text).

UI (test/ui.test.js)

Case Maps to
HTML contains History heading/label and #history-list (or agreed id) AC5
HTML contains Clear history control (button text or id/data- attribute) AC5
Inline script references /api/history for GET and DELETE AC5
Script calls history refresh after successful calculate paths (= and √) — e.g. match refreshHistory or fetch to /api/history in those branches AC5
Existing REQUIRED_KEYS and sqrt/percent wiring tests still pass Regression

Full suite: npm test must pass before push.

Risks

Risk Mitigation
Shared module state leaks between server tests resetHistory() in history tests; document pattern in test file
Recording on 400 responses Only call record after successful calculate in the 200 branch
Storing string operands instead of numbers Use parseNumber (or equivalent) for stored a/b; assert typeof in HTTP tests
Wrong operand order in history (oldest first) Unit test newest-first; AC1 HTTP test with two calcs
DELETE returns JSON or wrong status Explicit 204 test; res.end() with no body
UI does not refresh after √ Wire refresh in both success handlers; UI test asserts both code paths
Binary vs unary display in list Format sqrt without showing b; optional UI test for op=sqrt in fetch refresh
createServer per test still shares one history store Accept for this app; reset in tests

Implementation order

  1. lib/history.js + test/history.test.js
  2. server.js routes and record-on-success + test/server.test.js history cases
  3. public/index.html History UI + test/ui.test.js
  4. Full npm test, then push aira/7-calculation-history

Attachment: plan-7-r1.md

**Aira · Plan (round 1) at `1aab3aae`** Wrote issue-7 implementation plan (history module, API, UI, tests, risks), committed docs/plans/issue-7.md, ran npm test (50 pass), pushed aira/7-calculation-history. <details><summary>docs/plans/issue-7.md</summary> # Issue #7: Calculation history ## Goal Keep a short in-memory history of **successful** calculations on the server (newest first, max 10), expose it via `GET /api/history` and `DELETE /api/history`, and show a History list with a Clear history control in the UI that updates after each successful `=` or `√`. ## Acceptance criteria 1. After `2+3` and `6*7`, `GET /api/history` lists `6*7=42` first and `2+3=5` second. 2. After 12 calculations only the newest 10 are returned. 3. A failed calculation (division by zero) is not in the history. 4. `DELETE /api/history` returns 204 and the history is empty afterwards. 5. The page shows the history list and a Clear history button. ## Design ### History module (`lib/history.js`) — **new** - Single in-memory store (module-level array), no persistence across process restarts. - **Entry shape**: `{ a: number, b: number | null, op: string, result: number }`. - For unary `sqrt`, store `b: null` (operands are the parsed numbers used in the calculation, not raw query strings). - **`record(entry)`**: prepend the entry (newest first). If length exceeds 10, drop the oldest entries so at most 10 remain. - **`list()`**: return a shallow copy of the current array (newest first). - **`clear()`**: reset the store to `[]`. - Export **`resetHistory()`** (alias of `clear`) for tests so HTTP suites can isolate cases without cross-test leakage from shared module state. Pure logic only; no HTTP. ### HTTP layer (`server.js`) - **`handleCalculate`** (after successful `calculate`): - Build history entry from request context: `op` from query; `a` as the finite number used for the left operand; `b` as `null` when `op === 'sqrt'`, otherwise the finite number from `b`; `result` from `calculate`. - Reuse the same parsing rules as the calculator (call `calculate` first; on success, derive stored operands—e.g. `parseNumber` from `lib/calculator.js` for `a`, and for binary ops `b`, so stored values match what was computed). - Call `record` only on HTTP 200 success paths (never in the `catch` branch). - **`GET /api/history`**: `200` with `{"items": [...]}` where each item matches the entry shape above; empty store → `{"items":[]}`. - **`DELETE /api/history`**: `clear()`, respond `204` with no body (no JSON). - Unknown methods/paths on `/api/history` → existing 404 JSON pattern. Recording uses the **API op names** (`add`, `multiply`, `sqrt`, etc.), consistent with query params. ### UI (`public/index.html`) - Below the keypad (still inside `main`): a **History** section—heading, `<ul id="history-list">` (or similar) for entries, and a **Clear history** button (`id="clear-history"` or `data-action="clear-history"`). - **`refreshHistory()`**: `fetch('/api/history')`, parse `items`, render each row (e.g. `a`, `op`, `b`, `result`—format unary sqrt without a bogus `b`). - Call **`refreshHistory()`**: - On load (show any existing history). - After successful `=` (inside the `status === 200` branch). - After successful `√` (same branch). - **Clear history**: click handler → `fetch('/api/history', { method: 'DELETE' })`, then `refreshHistory()` (list should empty). - Minimal CSS so the list is readable under the calculator (reuse existing system font / spacing). ### Separation of concerns | Layer | Responsibility | |-------|----------------| | `lib/history.js` | Cap, order, clear, list | | `lib/calculator.js` | Unchanged calculation semantics | | `server.js` | Routes, record on success only | | `public/index.html` | Display and refresh UX | ## Files to change | File | Action | |------|--------| | `lib/history.js` | **Create** — in-memory store, `record`, `list`, `clear`, `resetHistory` | | `server.js` | **Modify** — record on successful calculate; `GET`/`DELETE` `/api/history` | | `public/index.html` | **Modify** — History list, Clear button, `refreshHistory` after `=` / `√` | | `test/history.test.js` | **Create** — unit tests for module | | `test/server.test.js` | **Modify** — HTTP tests for all acceptance criteria | | `test/ui.test.js` | **Modify** — History UI and script wiring | | `AGENTS.md` | **Optional** — document history API in implementation if Aira wants docs in sync (not required for AC). | ## Test plan ### Unit (`test/history.test.js`) | Case | Maps to | |------|---------| | Empty `list()` → `[]` | Design | | `record` then `list()` returns newest first | AC1 (module) | | 12 `record` calls → `list()` length 10, first item is the 12th recorded | AC2 (module) | | `clear()` then `list()` → `[]` | AC4 (module) | | Entries preserve `a`, `b`, `op`, `result` including `b: null` for sqrt-style entries | API shape | Call `resetHistory()` in `beforeEach` (or start of each test) so tests are independent. ### HTTP (`test/server.test.js`) Use `resetHistory()` from `lib/history.js` at the start of each history-related test (or a dedicated `beforeEach` block) so ordering assertions are deterministic. | Case | Expected | Maps to | |------|----------|---------| | `GET /api/history` on fresh server → `200`, `{ items: [] }` | Design | | `GET ...?a=2&b=3&op=add` then `GET ...?a=6&b=7&op=multiply`, then `GET /api/history` | Items[0]: multiply 42; items[1]: add 5 | AC1 | | 12 distinct successful `GET /api/calculate` requests | `GET /api/history` → 10 items, newest matches last calculation | AC2 | | `GET ...?a=1&b=0&op=divide` (400), then successful add | History has no divide entry; only successes | AC3 | | After some entries, `DELETE /api/history` → `204`, empty body; `GET /api/history` → `{ items: [] }` | AC4 | | Successful `GET ...?a=9&op=sqrt` | History item has `b: null`, `op: 'sqrt'` | API shape | | Failed calculate (invalid op, bad operand) does not append | AC3 (extended) | | Existing health, index, calculate regression tests still pass | Regression | Assert `DELETE` response has no JSON body (e.g. `res.status === 204` and empty or null text). ### UI (`test/ui.test.js`) | Case | Maps to | |------|---------| | HTML contains History heading/label and `#history-list` (or agreed id) | AC5 | | HTML contains Clear history control (button text or `id`/`data-` attribute) | AC5 | | Inline script references `/api/history` for GET and DELETE | AC5 | | Script calls history refresh after successful calculate paths (`=` and `√`) — e.g. match `refreshHistory` or fetch to `/api/history` in those branches | AC5 | | Existing `REQUIRED_KEYS` and sqrt/percent wiring tests still pass | Regression | Full suite: `npm test` must pass before push. ## Risks | Risk | Mitigation | |------|------------| | Shared module state leaks between server tests | `resetHistory()` in history tests; document pattern in test file | | Recording on 400 responses | Only call `record` after successful `calculate` in the 200 branch | | Storing string operands instead of numbers | Use `parseNumber` (or equivalent) for stored `a`/`b`; assert `typeof` in HTTP tests | | Wrong operand order in history (oldest first) | Unit test newest-first; AC1 HTTP test with two calcs | | `DELETE` returns JSON or wrong status | Explicit 204 test; `res.end()` with no body | | UI does not refresh after `√` | Wire refresh in both success handlers; UI test asserts both code paths | | Binary vs unary display in list | Format sqrt without showing `b`; optional UI test for `op=sqrt` in fetch refresh | | `createServer` per test still shares one history store | Accept for this app; reset in tests | ## Implementation order 1. `lib/history.js` + `test/history.test.js` 2. `server.js` routes and record-on-success + `test/server.test.js` history cases 3. `public/index.html` History UI + `test/ui.test.js` 4. Full `npm test`, then push `aira/7-calculation-history` </details> Attachment: [plan-7-r1.md](https://aira-lab.cluster-dev.spkey.co/attachments/c87c283b-bad4-4cf1-8100-309118014b92)
Sign in to join this conversation.
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
lab/web-calculator-3#7
No description provided.