<!-- Generated by book/tools/make-index.py from the book source. -->

> Hedengren, J. (Ed.) (2027). Chapter 12: Build Your Own Performance App. In *Data-Driven Athletics: Measuring, Modeling and Coaching Human Performance with Video and Wearable Data* (pp. 329–354). IRSRI Sports Research Institute. CC BY 4.0.

**Question.** A coach says: “My runners record their heart in the morning, and the files sit on their phones. I just want to know whether this morning's file is good enough to use, and what the number is. Can you make me something?” What is the smallest tool that answers that one question?

**Objectives.**
- Reduce a coach's question to a one-page specification of the smallest tool that answers it.
- Name the parts of a browser app (page, script, worker, canvas, build tool, static host) and say what each one does.
- Direct an AI assistant to build an app in small steps, test what it builds against answers you worked by hand, and test that it survives normal, missing and invalid input.
- Keep a user's data on their own device, and say on the page what the tool cannot do.
- Run a user test with five people and three tasks, and change the app because of what you saw.

# 12 Build Your Own Performance App

For eleven weeks you have added one step a week to a small web page. It loads a file, draws a chart, computes a number and remembers a baseline. This chapter turns those steps into a tool someone else can use. The tool is small on purpose. A coach does not need a dashboard with forty numbers. A coach needs one decision made easier, on the phone in their pocket, without sending an athlete's data to anyone.

The running example is the coach's question in the opener. You will write its specification, build it as a real app called *Resting heart check*, test it against hand calculations, keep its data on the device, give it a Basic screen and a report, test it with five users, put it online, and check that it is a responsible tool. The full source is in this chapter's `code/student-app` folder, and every listing below is cut from those files. The app was built with Vite 8.4 and passed its tests on the day this chapter was written (CHECKS.md records the commands).

## 12.1 Start from One Decision

Most student apps fail in the same way: they do too much. Someone asks a small question, and the builder answers ten questions nobody asked. Each extra number needs a test, a label, an explanation and a person who wants it. Start instead from the one decision the user has to make, and build only what that decision needs.

A *specification* (spec) is a short written description of what the tool must do, written before any code. A good one fits on one page. Writing it first saves time twice: it tells the AI assistant what to build, and it tells you when to stop.

*Table 12.1. A one-page specification for the running example. Each line is a promise you can check.*

| User | A cross-country coach, and each runner on the team, on a phone. |
|---|---|
| Question | Is this morning's recording clean enough to use, and what are its RMSSD and average heart rate? |
| Input | One CSV file of RR intervals in milliseconds, in a column named `rr` or `rr_ms`. Blank cells are allowed, because the strap logger's file has them. |
| One screen | Two large numbers (RMSSD, average heart rate), a chart of every interval with removed beats marked, and a short text summary. |
| Output | A plain-text summary to copy or save, and a printable report the browser can save as a PDF. |
| Rules | Remove an interval outside 300 to 2000 ms or more than 25% from the median of its neighbors. Warn when more than 5% are removed or the file is under one minute. |
| Test | Five intervals of 800, 820, 790, 810 and 800 ms give an RMSSD of 21.21 ms and 74.63 bpm. |
| Will not do | No diagnosis, no “readiness” verdict, no accounts, no upload, no comparison with other people. |

Table 12.1 is the spec for the running example. Read the last line twice. “Will not do” is the most useful line on the page, because it is where scope creep (the slow growth of a project's goals) gets stopped. When a teammate says “it would be cool if it also predicted injuries,” the spec already says no, and says why: the tool is not built or tested for that, and that claim would make it a medical device (Section 12.10).

Notice also the “Test” line. The spec contains a worked answer before the code exists. That one line will catch more errors than any amount of reading code, because an AI assistant can write a function that looks right and computes the wrong thing.

> **Key idea.**
> 
> Write the decision, the input, the one screen, the output, one test with a hand-worked answer, and what the tool will not do. If you cannot fill a line, you are not ready to ask for code.

> **Body science: What the app measures.**
> 
> Each heartbeat starts with an electrical wave whose tallest spike, the R wave, is easy to find. The time from one R wave to the next is an *RR interval*, about 1000 ms at 60 bpm. The intervals are not equal. When you breathe in, the vagus nerve's braking effect on the heart eases and the intervals shorten; when you breathe out, they lengthen. *RMSSD*, the root mean square of successive differences, measures this beat-to-beat change . Athletes often track its natural logarithm, lnRMSSD, from short morning recordings, and look at averages over a week rather than at single days, because one day's value moves a lot . Chapter 5 covers the physiology; here you only need the formula and the fact that the value is compared with the same person, measured the same way.

## 12.2 How a Browser App Is Put Together

A browser app is a set of plain files that a web server hands out unchanged. The browser does all the work. Six parts matter.

- **The page.**  `index.html` holds the text, the buttons and the empty places where results will go.

- **The script.**  `main.js` reacts to what the user does: a file is chosen, a box is ticked, a button is pressed.

- **The worker.**  A *Web Worker* is a second script that runs in the background, on its own thread, so a long calculation does not freeze the page . The page and the worker talk only by passing messages.

- **The canvas.**  A `<canvas>` element is a rectangle of pixels the script draws on with lines, circles and text. Charts in both the Heart app and the student app are drawn this way, by hand, without a chart library.

- **The build tool.**  A *build tool* gathers the source files, bundles the imports and writes a small folder of files ready to serve. The student app uses Vite ; the form apps also use Vite; the Heart app uses another bundler, esbuild.

- **The static host.**  Any web server that hands out files. There is no program on the server and no database, so there is nothing on the server that could store an athlete's data (Section 12.9).

*Figure 12.1. The parts of the student app. The web server sends only the app's own files. The athlete's file goes from the phone's storage to the page and to the worker, and never back to the server. The dashed box runs on a background thread.*

> **Try it in the app: Watch a worker at work.**
> 
> Open the Heart app and load a recording (your own from Chapter 5, or the de-identified example in its public repository). Watch the progress bar: each message comes from the worker. Then open the browser's Network panel and load the file again; no request carries the file.
> 
> 
> https://apopt.com/heart

Figure 12.1 shows how the parts connect in the student app. Before you build your own, look at how two real apps arrange the same parts.

### 12.2.1 Messages between the page and the worker

The page and the worker share no variables. The page posts a message, the worker does its work and posts a message back, and each side reacts in a function that runs when a message arrives. Listing 12.1 is the page's half for the student app. The first line starts the worker in the form Vite recommends, with `new URL(\ldots, import.meta.url)`, so the build tool can find the worker's file and bundle it .

**Listing 12.1.** Starting the worker and sending it a file's text (`main.js`). (`code/student-app/src/main.js`)

```javascript
const worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });
```

The file is read by `file.text()`, which turns the chosen file into a string inside the browser, and the string goes to the worker. Nothing in these lines names a server. The reply arrives in `worker.onmessage`, which either shows the error in words (`Could not read this file: No "rr" or "rr_ms" column in this file.`) or fills the two numbers, the summary, the list of removed beats and the chart. A worker cannot touch the page, which is a feature: `analysis.js` cannot draw, and the page cannot compute, so each can be tested alone.

What changes for a different question? Only `analysis.js` and the words on the page. A jump-testing version would read the jump heights a team saved from the jump app, one row per jump, and report each athlete's best and mean; the worker, the chart, the summary, the modes and the report stay the same. That is why the build thread asked you to keep the calculation in its own file from week 2 on.

### 12.2.2 A tour of the Heart app

The Heart app at https://apopt.com/heart analyzes chest-strap ECG recordings. Its file analyzer is public under the MIT License . Its source folder holds twelve plain JavaScript modules, about 7,350 lines, bundled with esbuild into two files: `app.js` for the page and `analysis-worker.js` for the worker. The README states the design in one sentence: all parsing and analysis runs in a Web Worker in your own browser, and the deployed site is static files.

Follow one file through it.

- *Files in.* The user chooses one or more CSV files or a ZIP archive. The page passes the file objects to the worker; the worker opens ZIP archives itself and sorts the CSV files by name.

- *Analysis in a worker.* The worker finds R peaks in the ECG, screens the rhythm, computes heart rate variability and builds a report object. While it works it sends progress messages (“Parsing 3 CSV file(s)\ldots”, a percentage), which the page shows on a progress bar.

- *Charts drawn by hand.* The page draws more than twenty charts on canvases with its own drawing functions. Each starts the same way: it reads the canvas's size on screen and multiplies by the device's pixel ratio, so lines stay sharp on a phone's dense screen.

- *A PDF.* A PDF library builds a printable report from the same report object, with the charts copied in.

- *A text summary.* A section headed “Full summary for AI synthesis” holds the results as labeled lines of `key=value` pairs, with the raw ECG left out, ready to copy into an AI assistant.

The deployed app at https://apopt.com/heart adds Live Capture: it connects to the strap over Web Bluetooth and records the strap's raw ECG, heart rate with RR intervals and accelerometer motion, stores the recording on the device and exports a CSV file. That part is not in the public repository, so this chapter describes it but does not quote it.

### 12.2.3 A tour of a form app

The jump app at https://apopt.com/jump/jump.php is one of the 22 movement apps. It shares its design with the others through a common `shared/` folder. Its parts are different because its input is different.

- *Video in.* The user chooses a clip. The page reads the frame rate from the file's header, because a slow-motion clip stores the wrong one (Chapter 8).

- *A pose model.* Each frame goes through a pose model that runs in the browser; the default is MoveNet Thunder. The heavy arithmetic runs on the graphics processor. Unlike the Heart app, the form apps run the model from the page itself, not from a Web Worker.

- *Metrics.* Plain TypeScript functions turn keypoints into numbers. The jump app's headline height, for example, is the rise of the hips from standing to the top of the flight, scaled by the athlete's height; beside the flight time it also gives $g t^2/8$ (Chapter 3), with $g=\SI{9.80665}{\metre\per\second\squared}$. With the default model, which has no toe keypoints, it times takeoff and touchdown where the ankle's motion breaks sharply; with a model that sees the toes, it counts the foot airborne once it clears the ground by 4 cm and adds back the time spent below that (Chapter 10).

- *An overlay.* The skeleton and the event markers are drawn over the video on a canvas.

- *Three outputs.* A PDF report, a highlight video and a text result in Markdown, all built from one results object.

The form apps are written in TypeScript (JavaScript with types) with the React library. Your app uses plain JavaScript, which needs no framework and is easier to read when you are new to it. Take the design from these apps, not their files.

## 12.3 Building with an Assistant

You will build with an AI assistant, as you have all term. The assistant types quickly and confidently, and it is sometimes wrong. Your job is to plan, to check and to decide. The method is the one from Chapter 4: specify, generate, verify, defend. For an app, five habits make it work.

\paragraph{Ask for a plan before code.} Paste the spec and ask: “List the files you would create and what each one does. Do not write code yet.” Read the plan. If it adds a server, an account system or a chart library you did not ask for, say no now, while it costs nothing.

\paragraph{Take small steps.} One request, one change you can see: “Add a file input and print the number of RR intervals.” Then “move the parsing into `analysis.js` and export it.” Then “add a worker that calls it.” After each step, open the page and check it works. A step that breaks something is easy to undo when it is small.

Table 12.2 shows how this chapter's app was built, one request at a time, and what was checked before the next request. Notice that the check is never “the code looks fine.”

*Table 12.2. The student app in eight requests. Each row is one change to the assistant and one check by a person before the next.*

|  | Request | Check before going on |
|---|---|---|
| 1 | An empty Vite page with a title and a file input | The page opens on a laptop and a phone |
| 2 | Parse a CSV file's `rr` column into numbers | A five-line file prints five numbers; a file with blank cells skips them |
| 3 | RMSSD and mean heart rate in `analysis.js`, with the tests of Listing 12.3 | Tests pass against the hand values |
| 4 | The cleaning rule | The missed-beat test passes; the example file loses exactly beats 81, 201, 202 |
| 5 | Move the work into a worker | Same numbers as before; the page stays responsive |
| 6 | Chart, summary, copy, download, print | Look at the screen: this is where the blank chart was found |
| 7 | Basic and Advanced modes | A fresh browser starts in Basic; the choice survives a reload |
| 8 | Build for a subfolder | `dist/` works when copied to a folder that is not the site's root |

\paragraph{Keep the numbers in their own file.} Put every calculation in a module with no page in it, `analysis.js`. The same file then runs in the browser's worker and in a test on your laptop. Listing 12.2 is the core of the student app's `analysis.js`: the cleaning rule and RMSSD.

**Listing 12.2.** The cleaning rule and RMSSD, from `analysis.js` (lines 30–50). (`code/student-app/src/analysis.js`)

```javascript
export function cleanRR(rr, lim = LIMITS) {
  return rr.map((value, i) => {
    const near = rr
      .slice(Math.max(0, i - lim.halfWindow), i + lim.halfWindow + 1)
      .filter((x) => x >= lim.minMs && x <= lim.maxMs);
    const m = median(near) || value;
    return value >= lim.minMs && value <= lim.maxMs
      && Math.abs(value - m) / m <= lim.maxDeviation;
  });
}

export function rmssd(rr, keep) {
  let sum = 0;
  let pairs = 0;
  for (let i = 1; i < rr.length; i++) {
    if (!keep[i] || !keep[i - 1]) continue; // only beats that really follow each other
    sum += (rr[i] - rr[i - 1]) ** 2;
    pairs++;
  }
  return pairs ? Math.sqrt(sum / pairs) : NaN;
}
```

The rule in lines 30–39 follows the Heart app's rule for a clean beat: an interval counts if it lies between 300 and 2000 ms and within 25% of the median of the ten intervals on each side. Lines 41–50 compute

$$\RMSSD = \sqrt{\frac{1}{P}\sum_{\text{pairs}} \left(RR_{i} - RR_{i-1}\right)^2}$$

over the $P$ pairs of kept intervals that follow each other. Line 45 is a design choice, and Section 12.4 shows what it changes.

\paragraph{Write the test first.} A *known-answer test* runs the code on an input whose correct output you worked out another way, by hand or with another tool, and fails if the code disagrees. Write it before you ask for the function. Listing 12.3 shows the first two of the student app's five known-answer tests; Section 12.4.4 adds three more for bad input. Node.js, the program that runs JavaScript outside a browser, has a test runner built in, so the tests need nothing installed.

**Listing 12.3.** Two known-answer tests, from `test/analysis.test.js`. (`code/student-app/test/analysis.test.js`)

```javascript
const near = (a, b, tol = 0.01) => assert.ok(Math.abs(a - b) <= tol, `${a} vs ${b}`);

test('five clean beats: the hand calculation', () => {
  const r = analyze([800, 820, 790, 810, 800]);
  near(r.rmssd, Math.sqrt(450));   // 21.21 ms
  near(r.meanHr, 60000 / 804);     // 74.63 beats/min
  assert.equal(r.removed, 0);
});

test('a missed beat is removed and its pairs are skipped', () => {
  const r = analyze([800, 820, 1610, 810, 800]);
  assert.deepEqual(r.keep, [true, true, false, true, true]);
  near(r.rmssd, Math.sqrt(250));   // pairs 800-820 and 810-800 only
});
```

\paragraph{Read the diff, and look at the screen.} A *diff* is the list of lines a change adds and removes. Read every one before you accept it. Then look at what the page actually shows. Tests check numbers; only your eyes check that a chart appeared. While this chapter's app was being built, all five tests passed and the chart was blank. The page drew the chart while its section was still hidden, and a hidden canvas measures zero pixels wide, so the chart was drawn into nothing. One look at a screenshot found it, and the fix was to swap two lines (`main.js`, line 49).

\paragraph{Know when to start over.} If three requests in a row fail to fix the same fault, or the assistant starts changing files you did not mention, stop. Go back to the last version that worked, which is why you save a copy (a commit) after every working step. Then ask again, smaller, with the failing test pasted in.

> **Check the AI: A test that agrees with the bug.**
> 
> You ask an assistant for a test of `rmssd`. It runs the function on five intervals, prints `21.2132`, and writes `assert.equal(rmssd(rr), 21.2132)`. The test passes. What is wrong? The expected value came from the code under test, so the test can only ever confirm the code, right or wrong. A known answer must come from somewhere else: your hand calculation, a spreadsheet or the Python check in this chapter's `code/check_rr.py`.

## 12.4 Getting the Numbers Right

An app that shows a wrong number in a large font is worse than no app. Three checks, in rising order of effort, catch most errors: a hand calculation, synthetic data with a known answer, and a comparison with an existing tool.

### 12.4.1 A hand calculation as a test

**Example 12.1: RMSSD and heart rate from five beats.**

Five RR intervals: 800, 820, 790, 810 and 800 ms. All lie in 300 to 2000 ms, and the median is 800 ms, so every interval is within 25% of it and all five are kept.

*Differences.* $820-800=20$, $790-820=-30$, $810-790=20$, $800-810=-10$. *Checkpoint:* {four differences.}

*Squares and mean.* $400+900+400+100=1800$, and $1800/4=450$. *Checkpoint:* {450 ms².}

*Root.* $\sqrt{450}=\SI{21.21}{\milli\second}$.

*Average heart rate.* The mean interval is $4020/5=\SI{804}{\milli\second}$, and there are 60000 ms in a minute, so $60000/804=\SI{74.63}{\bpm}$.

*Now confirm it in the app.* Save the five numbers under a header `rr` in a file, load it, and read 21.2 ms and 75 bpm. The browser check in this chapter's code did exactly that and read those values.

Divide by the number of *differences*, four, not the number of intervals, five. Dividing by five gives $\sqrt{360}=\SI{18.97}{\milli\second}$, an error of 11% that no one would notice by looking. Mean heart rate is $60000$ divided by the mean interval, not the mean of $60000/RR_i$; the two differ slightly whenever the intervals vary.

### 12.4.2 Synthetic data with a known answer

A hand calculation tests five numbers. A real file has hundreds. *Synthetic data* is data you make with a program so that you know the right answer exactly. Two kinds help.

The first is a pattern whose answer you can see without a calculator. Intervals that alternate 950, 1050, 950, 1050\ldots have every difference equal to 100 ms in size, so RMSSD is exactly 100 ms, and the mean interval of 1000 ms is 60 bpm. The third test in the student app checks this on 300 intervals.

The second is a realistic recording with planted faults. This chapter's `code/make_rr.py` makes 331 intervals, about 5.4 minutes, near 975 ms. Breathing at 12 breaths a minute moves each interval up and down by up to 45 ms, and random noise is added. Then the script plants three faults a real strap produces: one missed beat, where two intervals are read as one (1895 ms at beat 81), and one extra beat, where one interval is split in two (449 and 549 ms at beats 201 and 202). Figure 12.2 shows the file; the app should remove exactly those three.

*Figure 12.2. The synthetic example file: 331 RR intervals with breathing-driven variation and three planted faults. The cleaning rule removes the missed beat near 80 s and the split beat near 195 s (open circles) and keeps every other interval. Bottom: the first minute on a finer scale, where the rise and fall with each 5 s breath shows.*

### 12.4.3 Comparing with an existing tool

The last check is a second, independent calculation. This chapter's `code/check_rr.py` computes the same quantities in Python with numpy, written without looking at the JavaScript. Both give 3 removed beats, an RMSSD of 39.09 ms and an average of 61.54 bpm on the example file, and the fifth test in Listing 12.3's file holds the app to the Python values within 0.01 .

Comparing with the Heart app teaches something more. The Heart app cleans beats with the same rule, but computes RMSSD over its list of clean intervals as if they were consecutive, so a difference is formed across the gap where a beat was removed. The student app skips such pairs (Listing 12.2, line 45). Neither is a bug; they are two defensible choices, and they give different numbers.

> **Check it by hand: One missed beat, three answers.**
> 
> Intervals 800, 820, 1610, 810, 800 ms: the strap missed a beat, so 1610 ms is two intervals read as one. The median is 810, and $|1610-810|/810=0.99>0.25$, so it is removed.
> 
> *No cleaning:* differences 20, 790, $-800$, $-10$; mean square $1264600/4=316150$; RMSSD $=562.3 ms$. *Checkpoint:* {one fault makes the value about 36 times the cleaned value below (15.81 ms).}
> 
> *Skip pairs that touch the removed beat* (the student app): pairs 800–820 and 810–800; $(400+100)/2=250$; RMSSD $=15.81 ms$.
> 
> *Join across the gap* (the Heart app's way): 800, 820, 810, 800 gives differences 20, $-10$, $-10$; $600/3=200$; RMSSD $=14.14 ms$.
> 
> On the 5.4-minute example file, where three of 331 intervals are removed, the two cleaned methods give 39.09 and 39.25 ms, and no cleaning gives 89.11 ms.

The lesson is in the size of the differences. Cleaning matters enormously: one fault can multiply RMSSD many times over. The choice of how to treat the gap matters little when faults are rare (0.16 ms here) and more when they are common. Write your choice down in the app's Advanced view, so a user who compares your number with another tool's knows why they differ.

### 12.4.4 Three inputs every app must survive

The three checks so far all feed the app a good file. Users will not. They will choose the wrong file, a file with nothing in it, or a file in the wrong units. So every app you build needs a second, required set of tests, one for each kind of input:

- ***Normal input*.**  A good file. Expected: the right answer. Use the hand calculation of Example 12.1, so this test is the one you already have.

- ***Missing input*.**  An empty file, a header with no rows, a file without an `rr` column. Expected: no number, and a message that says what is missing.

- ***Invalid input*.**  Values that are present but cannot be right: RR intervals typed in seconds (0.80) instead of milliseconds (800), text, negative numbers. Expected: no number, and a message that says how to fix the file.

Write down the expected behavior before you write the test, exactly as you wrote the hand answer before the known-answer test. “It does not crash” is not enough. A wrong number in a large font is the failure you are guarding against, and an app that shows one has not survived the input, even though nothing crashed.

Listing 12.4 is the set for the student app, written for the same test runner you have used since build step B-5. It tests a small function, `checkInput`, that the worker now calls before any analysis; the page shows its message in place of the numbers.

**Listing 12.4.** The three required input tests, from `test/inputs.test.js`. (`code/student-app/test/inputs.test.js`)

```javascript
test('normal: the five hand-worked beats pass and give the hand answer', () => {
  const rr = parseRR('rr\n800\n820\n790\n810\n800\n');
  assert.equal(checkInput(rr), null);
  assert.ok(Math.abs(analyze(rr).rmssd - Math.sqrt(450)) <= 0.01); // 21.21 ms
});

test('missing: an empty file, a header alone, no rr column', () => {
  assert.match(checkInput(parseRR('')), /Fewer than three RR/);
  assert.match(checkInput(parseRR('time,rr\n')), /Fewer than three RR/);
  assert.throws(() => parseRR('time,hr\n1,60\n'), /No "rr"/);
});

test('invalid: intervals in seconds are refused, never shown as NaN', () => {
  const rr = parseRR('rr\n0.80\n0.82\n0.79\n0.81\n');
  assert.equal(rr.length, 4); // read, but not usable
  assert.match(checkInput(rr), /in milliseconds\?/);
});
```

**Listing 12.5.** Output of node –test –test-reporter=tap test/inputs.test.js (excerpt).

```text
ok 1 - normal: the five hand-worked beats pass and give the hand answer
ok 2 - missing: an empty file, a header alone, no rr column
ok 3 - invalid: intervals in seconds are refused, never shown as NaN
# tests 3
# pass 3
# fail 0
```

The set earned its place on its first run. Before `checkInput` existed, the worker's only guard was “at least three intervals”. A file of four intervals in seconds passed it. The cleaning rule then removed all four, because each is below 300 ms, and RMSSD and heart rate became `NaN`, JavaScript's “not a number”. The page printed `NaN` where the large numbers belong. None of the five known-answer tests could see this, because each of them feeds the app a good file. The fix counts the intervals inside 300 to 2000 ms and, below three, asks whether the values are in milliseconds.

Looking at the screen found a second fault. When a good file was followed by a bad one, the error message appeared, but the good file's numbers stayed on screen beneath it, where a user would read them as the new file's result. One line now hides the results whenever a file is refused. The browser check (`code/inputs-e2e.mjs`) loads a normal, an empty and a seconds file in turn and confirms the result, the two messages and that no old number is left showing.

Run all eight tests with `npm test` after every change. The five known-answer tests say the number is right when the input is good; the three input tests say the app shows no number when the input is not.

### 12.4.5 How good is the number?

The app computes RMSSD correctly, in the sense that it matches the formula and an independent program. That is not the same as the number being a good measure of the runner. Four sources of error sit outside the code, and the app can only warn about them.

*Table 12.3. Sources of error in a morning RR recording that no code can remove. Sizes are those in this chapter's example or are stated as orders of magnitude.*

| Source | What it does | How to check |
|---|---|---|
| Artifacts (missed or extra beats) | One missed beat in five intervals raised RMSSD from 15.8 to 562 ms; cleaning brings it back | The share removed; the chart's open circles |
| Cleaning choice | Joining across a gap or skipping it: 0.16 ms apart on the example | State the rule; compare with a second tool |
| Conditions | Position, time of day, breathing, a recent meal or coffee all move the value | Record the same way every time |
| Day-to-day variation | One day's value moves a lot even when nothing has changed | Compare a weekly average with the athlete's own baseline (Chapter 11) |

Table 12.3 lists them. The app's summary handles the first by stating the number removed and warning above 5%, and the third by telling the user to compare only with their own recordings made the same way. The fourth is why the spec says “no readiness verdict”: a single morning's value is not enough to tell an athlete to train or rest.

## 12.5 Privacy by Design

Heart data is health data. In European law, data concerning health is one of the special categories that may be processed only under strict conditions, and anyone processing personal data must build data protection into the design and set it as the default . The idea is older than the law: *privacy by design* asks that privacy be built in from the start, as the default setting, rather than repaired after a breach . For a student app the simplest way to honor it is to never hold the data at all.

- **Process on the device.**  The browser reads the file from the phone's storage and the worker computes on it there. Listing 12.6 is the whole worker: it receives text, returns numbers and has no way to send anything else.

- **No accounts.**  An account means a database of people, passwords and a breach to report. The coach's question needs none of it.

- **No upload.**  The page never sends the file anywhere. You can prove it: open the browser's developer tools, choose the Network panel, and load a file. The only requests should be for the app's own files. In the browser check of the student app, the requests were the page, its script, its stylesheet, its worker and the example file, and nothing else, for both the example and a file chosen by the user.

- **Say so, and say the limits.**  The first line under the title reads “Your file stays on this device. Nothing is uploaded.” The footer says what the tool is not (Section 12.10).

**Listing 12.6.** The whole worker, `worker.js`. It receives text and posts back numbers. (`code/student-app/src/worker.js`)

```javascript
import { parseRR, analyze, summaryText, checkInput } from './analysis.js';

self.onmessage = (event) => {
  try {
    const rr = parseRR(event.data.text);
    const problem = checkInput(rr); // missing or invalid input: say why
    if (problem) throw new Error(problem);
    const result = analyze(rr);
    if (!Number.isFinite(result.rmssd)) throw new Error('Too few clean beats in a row.');
    self.postMessage({ ok: true, result, text: summaryText(result) });
  } catch (error) {
    self.postMessage({ ok: false, message: error.message });
  }
};
```

Three smaller choices matter too. The summary does not print the file's name, because files are often named after people. Saved settings go in the browser's local storage on that device, never to a server. And the text export holds results, not raw data.

Check the text you invite people to paste elsewhere. An earlier version of the Heart app's text export repeated the name and age typed on its form near its top: useful when you keep the text yourself, and a leak when you paste it into an outside AI service. The export now carries no name, gives age only as a ten-year band (“20-29”), and tells the AI service that the text is training information. When no measured maximum heart rate is typed, the maximum-heart-rate reference it exports is the estimate for the middle of the age band, not 220 minus the exact age, which would give the age back. One field still needs your eye: any notes typed on the form are copied in. That is the rule of Chapter 4 built into the tool: de-identify before you share, and read what is left.

> **Limits and cautions: The example file is not your data.**
> 
> A built-in example file lets a new user try the app without any data of their own, and it lets you test the deployed app in class without anyone's heart file. Make the example synthetic, as this chapter's is. Never ship a teammate's real recording as the example, even with the name removed.

## 12.6 Basic First

A new user should see one clear result in the first minute. Detail can wait until they ask for it. The movement apps call this Basic and Advanced mode, and their shared code states the rules in a few lines:

- Basic is the default: upload, analyze, results, with only the headline metrics.

- Advanced is the app's full interface, one tick away.

- The choice is remembered per app on that device, and a link can set it for one visit with `?mode=advanced`, for example from a coach's instructions.

- In the movement apps, Basic mode analyzes at most 12 s of a clip: the whole clip if it is shorter, otherwise the middle 12 s.

The student app copies the pattern in fourteen lines (Listing 12.7). In Basic mode the screen shows the two large numbers, the chart and the summary. In Advanced mode it adds the list of removed beats and the cleaning rule in words. The printed report always includes the Advanced section, because a report is read later by someone who cannot click.

**Listing 12.7.** Basic first: the mode comes from the link, then from this device's memory, then defaults to Basic (`main.js`). (`code/student-app/src/main.js`)

```javascript
// Basic first: Advanced is remembered on this device, or set by ?mode=advanced.
const MODE_KEY = 'rr-check-mode';
function startMode() {
  const fromUrl = new URLSearchParams(location.search).get('mode');
  if (fromUrl === 'advanced' || fromUrl === 'basic') return fromUrl;
  try { return localStorage.getItem(MODE_KEY) || 'basic'; } catch { return 'basic'; }
}
function setMode(mode) {
  document.body.dataset.mode = mode;
  $('advanced').checked = mode === 'advanced';
  try { localStorage.setItem(MODE_KEY, mode); } catch { /* private window */ }
}
setMode(startMode());
$('advanced').addEventListener('change', (e) => setMode(e.target.checked ? 'advanced' : 'basic'));
```

How do you decide what goes in Basic? Go back to the spec. The question was “is this file good enough to use, and what is the number?” So Basic shows the number, the heart rate as a sanity check, and the one line that says whether the file is good enough. Everything else is Advanced.

*Figure 12.3. The student app in Basic mode after loading the example file, as captured by the browser check. Two large numbers, the chart with the three removed beats circled, the summary and three ways to keep it.*

## 12.7 Reports People Read

The result on the screen disappears when the page closes. A report is what the athlete keeps. Make two kinds.

\paragraph{A PDF for people.} The Heart app and the movement apps build their PDFs with a library. The student app takes a shortcut: a print stylesheet hides the buttons and shows the Advanced section, and the “Save report (PDF)” button opens the browser's print dialog, which in most browsers can save the page as a PDF. It costs one line of script and no library.

\paragraph{Text for people and for AI assistants.} Plain text pastes into a message, a notebook or an assistant without losing anything. The movement apps write their text result in Markdown with the same layout in every app: a title, the analysis settings (video, view, frame rate, height, model), a summary, focus areas, a table of metrics with value, rating and target, notes, and a closing line, “Measured from a single video in the browser; treat values as estimates, not clinical measurements.” Because the layout is fixed, an AI agent reading a folder of results knows where everything is. The page also publishes the text for software to find: a `data-results-ready` mark on the page and a `window.irsriResults` object. The Heart app's text export uses labeled `key=value` lines for the same reason.

The student app's summary is seven lines:

```text
Resting heart check (RR intervals)
Recording: 5.4 min, 331 beats, 3 removed as artifacts (0.9%).
Average heart rate: 62 beats per minute.
RMSSD: 39.1 ms (lnRMSSD 3.67).
Compare only with your own recordings made the same way: same time of day, same position.
Training information only, not a medical assessment.
Computed on this device. Nothing was uploaded.
```

Each line does a job: what was measured, how clean it was, the two numbers with their units, how to use them, what they are not, and where they were computed. Listing 12.8 builds it.

**Listing 12.8.** The plain-text summary, from `analysis.js`. (`code/student-app/src/analysis.js`)

```javascript
export function summaryText(r) {
  const pct = (100 * r.removed) / r.beats;
  const lines = [
    'Resting heart check (RR intervals)',
    `Recording: ${r.minutes.toFixed(1)} min, ${r.beats} beats, ` +
      `${r.removed} removed as artifacts (${pct.toFixed(1)}%).`,
    `Average heart rate: ${r.meanHr.toFixed(0)} beats per minute.`,
    `RMSSD: ${r.rmssd.toFixed(1)} ms (lnRMSSD ${r.lnRmssd.toFixed(2)}).`,
  ];
  if (r.minutes < 1) lines.push('Under 1 minute: too few beats for a stable value. Record again.');
  else if (pct > 5) lines.push('More than 5% of beats were removed. Check the strap and record again.');
  else lines.push('Compare only with your own recordings made the same way: same time of day, same position.');
  lines.push('Training information only, not a medical assessment.');
  lines.push('Computed on this device. Nothing was uploaded.');
  return lines.join('\n');
}
```

\paragraph{Ratings and words.} If your app rates a number, choose the words with care. The movement apps rate each metric Elite (within the target), Pro (close) or Good (furthest from the target), with three, two and one stars; “Good” is the lowest of the three. An athlete who reads “Good (1/3)” may hear praise. Chapter 13 takes this up. The student app gives no rating, because nothing in the spec asks for a judgment.

## 12.8 Testing with Users

You know too much about your own app to test it. You know where the button is because you put it there. A *usability test* watches real people try to do real tasks with the app, while you keep quiet.

### 12.8.1 Why five users

Nielsen and Landauer counted, across many projects, how many problems each extra test user revealed . If each user meets a given problem with probability $L$, the share of problems found by $n$ users is

$$\text{found}(n) = 1-(1-L)^{n}.$$

With their average $L=0.31$, five users find about 85% of the problems, and the curve flattens after that . Virzi had found the same shape: the first few users reveal most problems, and the most severe ones tend to appear first . The advice that follows is to test with five, fix what you saw, and test again with five more, rather than test once with fifteen .

> **Check it by hand: Five users, by hand.**
> 
> $1-0.69^5$: $0.69^2=0.4761$, $0.69^4=0.2267$, $0.69^5=0.1564$. Found $=1-0.156=84.4%$. *Checkpoint:* {about 84%.} Three users: $1-0.69^3=67.1%$. Fifteen: 99.6%.

*Figure 12.4. The share of problems found by $n$ users, Equation ch12-app:eq:found. Five users find 84% of problems that each user meets with probability 0.31, but only 41% of problems that one user in ten meets.*

Read Figure 12.4 with its limits in mind. The 85% is an average over problems and over groups of users. Faulkner ran many random groups of five from a larger pool and found that some groups revealed far fewer problems than others; larger groups reduced the spread . A simulation in this chapter's `code/sim_users.py` shows the same thing: with ten problems at $L=0.31$, groups of five found 84% on average, but one group in twenty found 60% or fewer. And a problem that only one user in ten meets is found by a group of five only 41% of the time. If your users differ (a coach and a runner, a phone and a laptop, a reader of English as a second language) test some of each.

### 12.8.2 Three tasks, and what to watch

A *task* is something a user really wants to do, stated as a goal, not as a list of clicks. For the student app:

- “Here is the link. Find out what the app says about the example recording.”

- “Here is your own file. What is your RMSSD this morning, and is the file good enough to use?”

- “Save a report you could show your coach tomorrow, and tell me which beats the app removed.”

The third task needs Advanced mode, on purpose: it tests whether a user can find detail when they want it.

Run each session the same way. Get consent first (Appendix E has the form), and tell the user you are testing the app, not them. Ask them to think aloud. Then watch and write down, without helping:

- where they hesitate for more than a few seconds;

- every wrong tap, and what they expected it to do;

- every misreading: a number read with the wrong unit, a warning not seen, “39” taken as a score out of 100;

- whether they finished, and how long it took.

After the three tasks, hand them a short questionnaire. The *System Usability Scale* (SUS) is ten statements, each answered on a five-point scale from strongly disagree to strongly agree . Score it by subtracting 1 from each odd-numbered answer, subtracting each even-numbered answer from 5, adding, and multiplying by 2.5, which gives 0 to 100 . A score is not a percentage. Large collections of published scores average about 68 to 71 , so a score near 70 is ordinary, not a pass.

> **Check it by hand: One user's SUS score.**
> 
> Answers to items 1 to 10: 4, 2, 5, 1, 4, 2, 5, 2, 4, 2. Odd items: $(4-1)+(5-1)+(4-1)+(5-1)+(4-1)=17$. Even items: $(5-2)+(5-1)+(5-2)+(5-2)+(5-2)=16$. Score $=(17+16)\times2.5=82.5$. *Checkpoint:* {82.5.}

*Figure 12.5. A usability test: the user works, the builder watches and writes, and nobody helps.*

*Table 12.4. A problem log after five sessions. The layout is the point; the rows show the kind of entry to make, not results from a real test.*

| Problem seen | Users | Severity | Change |
|---|---|---|---|
| Could not find where to save the report | 2 of 5 | stopped task 3 | Move the save buttons above the summary |
| Read “39.1 ms” as a score out of 100 | 1 of 5 | misreading | Add “RMSSD, compare with your own” under the number |
| Did not notice the Advanced box | 3 of 5 | slowed task 3 | Label it “Show details (Advanced)” |

### 12.8.3 Changing the app

After five sessions, list every problem you saw (Table 12.4), how many users met it, and how bad it was: did it stop the task, slow it, or only annoy? Fix the ones that stopped a task first. A problem that two of five users met is not a minority opinion; by Equation \eqref{ch12-app:eq:found} it is common. Then write down what you changed and why, and test again with new users. In week 13 you will do one more round, with the report itself (Chapter 13).

## 12.9 Putting It Online

Because the app is static files, putting it online is copying a folder. The build command writes it:

```text
npm run build        # runs vite build: writes the dist/ folder
npm test             # runs node --test: the known-answer tests
```

For the student app, `dist/` holds five files: `index.html` (2.1 kB), one script (3.4 kB), one worker (2.3 kB), one stylesheet (0.8 kB) and the example file. Copy the folder's contents to any *static host*: a university web space, a course server, or a free static-site service. Most of these give you an address beginning with `https`, which you need anyway: browsers allow some features, such as Web Bluetooth for a live heart-rate strap, only on secure pages.

One setting saves an afternoon. A host often serves your app from a subfolder, such as `/teamname/rr/`, not from the root of a site. By default Vite writes links that start at the root, and the page loads with no script and no error you can see. The student app's `vite.config.js` sets `base: './'`, which makes every link relative to the page, so the folder works wherever it is copied . The movement apps set the same option.

\paragraph{A link and a QR code.} Your users will open the app on a phone. Print the address as a QR code on the handout for your user test and on the last slide of your showcase demonstration, and test the code with two different phones before class.

\paragraph{When it breaks in class.} It will, so plan for it.

- Keep the last build that worked, in a second folder, ready to copy back.

- Put a version and a date in the footer, so you know which build a user is looking at, and ask users to reload when you update.

- Keep the built-in example file, so a test can go on when the room's network or someone's own file fails.

- Run the tests and look at the page on a phone after every upload, not only on your laptop.

Putting the app online is the last of the nine data-workflow steps, *deploy*
(the workflow page in the front matter). Case
Study ? in Part V moves one
calculation from a notebook into a page an athlete can open.

## 12.10 Responsible Tools

A tool with your name on it carries your responsibility. Four questions belong in every project.

\paragraph{Is it a medical device?} It depends on what you claim it does. Regulators define software as a medical device by its intended purpose: software meant to diagnose, prevent, monitor, treat or ease a disease or injury is a medical device even when it runs on a phone . In the United States, the FDA states that it does not intend to examine low-risk products meant only for general wellness, such as tracking exercise or measuring fitness; its 2026 guidance names estimates such as heart rate variability among them, provided the output is for wellness only and does not prompt clinical action . The same app becomes something else when its words change. “Your RMSSD is 39 ms” is training information. “Your low RMSSD means you are getting sick” is a health claim the app was never tested to make. Keep the spec's “will not do” line, and the page's words, on the training side. When a user's data suggests something medical, the app should say to see a clinician, as the Heart app's pages do, and nothing more.

> **Status: 2026.**
> 
> {Rules change}
> The wellness boundary and its examples are set out in guidance documents that regulators revise. Check the current version of the FDA's general wellness guidance , or your own country's equivalent, before you describe a tool's purpose in public.

\paragraph{Who is accountable?} You are. Not the assistant that wrote the code and not the coach who asked for it. Every number your app shows an athlete is one you have checked (Section 12.4), and every claim on the page is one you can defend.

\paragraph{Can everyone use it?} The Web Content Accessibility Guidelines (WCAG) set testable rules . Four cover most of a small app:

- *Text alternatives.* A chart is a picture; give it a text alternative. The student app sets the canvas's label to the text summary, so a screen reader reads the result.

- *Labels.* Every input has a visible label tied to it, so “Choose a CSV file” is announced with the file button.

- *Contrast.* Ordinary text needs a contrast ratio of at least 4.5 to 1 against its background, and large text 3 to 1.

- *Status messages.* The status line is marked to be announced when it changes, so “Analyzing on this device\ldots” and “Done.” reach a user who cannot see them.

The contrast ratio is computed from each color's relative luminance $L$, a weighted sum of its red, green and blue light after undoing the screen's gamma: $(L_\text{light}+0.05)/(L_\text{dark}+0.05)$ .

> **Check it by hand: Is gray text readable?.**
> 
> White has $L=1$. Gray #777777 has $L=0.1845$ and gray #767676 has $L=0.1812$ (CHECKS.md shows the steps). Ratios: $1.05/0.2345=4.48$ and $1.05/0.2312=4.54$. The first fails 4.5 to 1 and the second passes, though no eye can tell them apart. The student app's gray, #444444, gives 9.74.

\paragraph{Whose code is it?} Code you read on the web belongs to someone. A *license* is the owner's written permission to use it. The Heart app's MIT License lets you use, copy, change and share its code, on one condition: keep the copyright notice and the license text in all copies or substantial portions . So if you copy a function, copy the notice with it. If you take only the design, as the student app does, credit the source anyway; its footer says “Design after the Heart app (MIT License).” Read the license file itself, not a summary: in an earlier release the Heart app's `package.json` said `UNLICENSED` while its `LICENSE` file granted the MIT License; the two now agree. Give your own app a license too, or others cannot legally reuse it. Code an AI assistant wrote for you is your responsibility to check in the same way: ask where a long block came from, and do not paste code whose source you cannot name.

## 12.11 Telling the Athlete

The week's communication task is a 90-second demonstration of your app to a coach. Ninety seconds is about 200 spoken words. Compare two openings.

> **Coach's translation: A poor demonstration.**
> 
> “So this is a Vite app with a Web Worker, and it parses the CSV and runs an artifact filter with a local median, then it computes RMSSD, which is the root mean square of successive differences, and lnRMSSD, and it draws a tachogram on a canvas with device-pixel-ratio scaling, and there's a Basic and an Advanced mode, and you can export to PDF\ldots”

> **Coach's translation: A good demonstration.**
> 
> “You asked whether this morning's heart file is good enough to use, and what the number is. Here it is on my phone. I tap the example file, and in two seconds it says: 39 milliseconds, 62 beats a minute, three beats removed, file is fine. The number only means something next to the same runner's other mornings, recorded lying down at the same time, so that's how to use it. It doesn't diagnose anything and it doesn't tell you to rest someone. The file never leaves the runner's phone. [Your test result, for example:] I tested it with five people; two couldn't find the save button, so I moved it. Would you try it with two runners this week?”

The good one starts from the coach's question, shows the result before explaining anything, states how to use the number and what it does not do, mentions privacy in one sentence, gives evidence that it was tested, and ends with one request. It uses none of the words a coach would have to look up. Use the five-line rubric of the communicate exercises: accurate, plain, one recommendation, uncertainty stated, within scope.

## Going Further

https://apmonitor.com/pds/index.php/Main/AppDevelopment and https://apmonitor.com/pds/index.php/Main/DeployMachineLearning package an analysis as an app and put it online; https://apmonitor.com/pds/index.php/Main/AgenticWorkplan and https://apmonitor.com/pds/index.php/Main/AgenticCoding plan and build with AI agents in the same specify-and-verify style as this chapter.

## Summary

- Start from one decision. A one-page spec names the user, the question, the input, the one screen, the output, a test with a hand-worked answer, and what the tool will not do.

- A browser app is a page, a script, a worker for long calculations, a canvas for drawing, a build tool, and a static host that serves files only.

- Build with an assistant in small, checked steps: plan before code, calculations in their own module, the test written first, every diff read, the screen looked at.

- Test numbers three ways: a hand calculation, synthetic data with a known answer, and an independent program. A correct formula can still give a poor measure; say how the input was recorded and how clean it was.

- Every app must survive three inputs: normal (the hand answer), missing (a message, no number) and invalid (a message that says how to fix it, no number). Test all three, and look at the screen after a bad file.

- Keep data on the device: no accounts, no upload, a synthetic example file, and a line on the page that says so. Check the Network panel.

- Basic first: one clear result by default, detail one tick away, the full detail in the report.

- Reports people read: a printable report and a fixed plain-text summary that people and AI assistants can both use.

- Test with five users and three real tasks, fix what stopped them, and test again. Five users find most common problems, not all problems.

- A responsible tool makes training claims only, is usable by people with disabilities, and respects the licenses of the code it learned from.

| Quantity | Formula |
|---|---|
| RMSSD | $\sqrt{\frac{1}{P}\sum (RR_i-RR_{i-1})^2}$ over $P$ adjacent kept pairs |
| Average heart rate | $60000/\overline{RR}$ (bpm, $RR$ in ms) |
| Clean interval | $300\le RR\le2000$ ms and $\|RR-m\|/m\le0.25$ , $m$ the local median |
| Problems found by $n$ users | $1-(1-L)^n$ |
| SUS score | $2.5\,[\sum_\text{odd}(x-1)+\sum_\text{even}(5-x)]$ |
| Contrast ratio | $(L_\text{light}+0.05)/(L_\text{dark}+0.05)$ |

*New terms:* specification, Web Worker, build tool, static host, known-answer test, diff, synthetic data, normal input, missing input, invalid input, privacy by design, usability test, task, System Usability Scale, license, RR interval, RMSSD.

**Track it:** `app_version` on every row, so an app update shows as a step (Appendix J).

## Exercises

> **Course use: Week 12.**
> 
> **P24** (due Class 24, *Measure*): 12.1, 12.2, 12.5, 12.8, 12.17, 12.22; about 140 minutes.
> 
> **P25** (due Class 25, *Model and tell*): 12.10, 12.19, 12.20, 12.21, 12.23; about 170 minutes. A case-file exercise may be done on your own data instead. The full map is in the Course Guide.

> **Project step: Week 12.**
> 
> The team project: checkpoint 3 is due with P24 (Class 24); checkpoint 4 is due with P25 (Class 25). What to hand in is in Appendix G.

**Exercise 12.1** (Concept check · Foundation · 2 min · CORE)

Your app freezes for three seconds while it analyzes a long file, and the progress bar does not move. Which change fixes the freeze without changing any result?
\choices{Draw the chart with a library instead of on a canvas}
{Move the analysis into a Web Worker and pass the file's text to it as a message}
{Upload the file to a server and analyze it there}
{Switch the page to Advanced mode before analyzing}

**Exercise 12.2** (Concept check · Foundation · 2 min · CORE)

Which design best keeps an athlete's heart file private?
\choices{Upload the file over an encrypted connection and delete it after one day}
{Ask each athlete to create an account with a strong password}
{Store every file in the browser and send a copy to the coach automatically}
{Read the file in the browser, compute on the device, and never send it anywhere}

**Exercise 12.3** (Concept check · Core · 2 min)

A teammate proposes that the Basic screen of your RR app show RMSSD, lnRMSSD, SDNN, pNN50, the full list of removed beats and a frequency spectrum, “so nothing is hidden.” What does the chapter recommend?
\choices{Show the two numbers the spec's question needs and the file-quality line; put the rest in Advanced and in the printed report}
{Show everything, because hiding data from an athlete is dishonest}
{Show only lnRMSSD, because it is the value athletes track}
{Remove Advanced mode, because users never open it}

**Exercise 12.4** (Concept check · Core · 2 min)

You test your app with five users and see eight problems. What is the best conclusion?
\choices{You have found every problem, because five users find 85% of them}
{The test was too small to mean anything; run fifteen users before changing the app}
{You have probably found most of the common problems, but rare ones and those met only by other kinds of user may remain; fix, then test again}
{Problems seen by only one of the five users can be ignored}

**Exercise 12.5** (Hand calculation · Foundation · 10 min · CORE)

Six RR intervals: 1000, 960, 1010, 990, 1040, 1000 ms.

- List the successive differences and the sum of their squares. *Checkpoint:* {8600.}

- Compute RMSSD and lnRMSSD. *Checkpoint:* {41.47 ms; 3.725.}

- Compute the average heart rate. *Checkpoint:* {60.00 bpm.}

- An assistant's function divides by the number of intervals instead of the number of differences. What does it report? *Checkpoint:* {37.86 ms.}

- Confirm (b) and (c) in your app or the student app by loading a file with these six values under the header `rr`.

**Exercise 12.6** (Hand calculation · Core · 10 min)

The strap misses a beat in Exercise 12.5's data, so the fourth interval reads 1980 ms: 1000, 960, 1010, 1980, 1040, 1000.

- Is 1980 ms inside the 300 to 2000 ms range? Find the median of the six values and the interval's relative deviation from it. Is it kept? *Checkpoint:* {median 1005 ms; deviation 0.97; removed.}

- Compute RMSSD with no cleaning. *Checkpoint:* {605.0 ms.}

- Compute RMSSD the student app's way, using only pairs of kept intervals that follow each other. *Checkpoint:* {43.59 ms.}

- Why is a range check alone not enough to catch a missed beat at rest?

**Exercise 12.7** (Hand calculation · Extension · 8 min)

Use the WCAG contrast ratio $(L_\text{light}+0.05)/(L_\text{dark}+0.05)$ with white ($L=1$).

- Gray #595959 has relative luminance $L=0.0999$. Find its contrast ratio on white. Does it pass for normal text? *Checkpoint:* {7.00; passes.}

- Gray #888888 has $L=0.2462$. Find the ratio. For which text does it pass? *Checkpoint:* {3.54.}

- The channel value of #888888 is $136/255=0.5333$. Show that $\left((0.5333+0.055)/1.055\right)^{2.4}=0.246$, and explain why that is also $L$ for a gray.

**Exercise 12.8** (App lab · Foundation · 20 min · CORE)

*Analyze yourself, then read the app as a builder.* Use the jump app, https://apopt.com/jump/jump.php.

- Film one countermovement jump from the side, whole body in frame from start to landing, phone still at about waist height, at 60 fps or more; a clip of 3 to 6 s. If you film in slow motion, set the capture frame rate to the rate you recorded at.

- Run it in Basic mode. Save the PDF and the text result (`.md`).

- Pick the flight-time height shown with the flight time (not the headline jump height, which is the hips' rise from standing and is larger; Chapter 10). Confirm it by hand from the flight time ($g t^2/8$, Chapter 3).

- Open Advanced mode. Name one thing Basic left out and say whether it changes your reading.

- Now read the app as a builder. In the text result, find the analysis settings table, the metrics table and the closing line. Which three settings would you need to repeat the measurement? Which part of the text would an AI assistant need to answer “how high did I jump”?

- Write half a page: what you measured, what it shows, how sure you are, what you would change, when you would retest.

Keep the `.md` file for the build step.

**Exercise 12.9** (App lab · Extension · 25 min)

*One file, two apps.* The Heart app's public repository includes a de-identified resting recording, `examples/subject-a/rest.csv.gz`, 8.2 minutes long, with the ECG and the strap's own RR intervals in a column named `rr`. Unzip it (any archive tool opens `.gz`).

- Load it in the student app (or your own). Record the beats, the number removed, RMSSD and average heart rate.

- Load the same file in the Heart app, https://apopt.com/heart. Record its RMSSD and average heart rate.

- Watch the Heart app while it works. What do the progress messages tell you about where the work happens?

- Find the text export. Which of its lines would identify a person, and what would you delete before pasting it into an outside AI service?

**Exercise 12.10** (Python analysis · Foundation · 20 min · CORE)

Recompute the student app's numbers on the example file, `data/rest-rr.csv`, in a notebook. Write it with an assistant, but specify it first: the cleaning rule (300 to 2000 ms, within 25% of the median of the in-range intervals among the ten on each side and itself) and the RMSSD rule (adjacent kept pairs only).

- Report the number of intervals, the number removed and their positions. *Checkpoint:* {331; 3; beats 81, 201, 202.}

- Report RMSSD and average heart rate. *Checkpoint:* {39.09 ms; 61.54 bpm.}

- Report RMSSD with no cleaning, and with cleaning but pairs joined across gaps. *Checkpoint:* {89.11 ms; 39.25 ms.}

- Before you run anything, test your function on 800, 820, 790, 810, 800 ms. *Checkpoint:* {21.21 ms.}

**Exercise 12.11** (Python analysis · Foundation · 15 min)

Write a function `sus(answers)` that scores the System Usability Scale from a list of ten answers (1 to 5). Write the tests first, from these hand answers, then the function.

- All answers 3. *Checkpoint:* {50.}

- Best possible: 5, 1, 5, 1, 5, 1, 5, 1, 5, 1. *Checkpoint:* {100.}

- 4, 2, 5, 1, 4, 2, 5, 2, 4, 2. *Checkpoint:* {82.5.}

- 5, 1, 4, 2, 4, 1, 5, 1, 3, 2. *Checkpoint:* {85.}

- Add a check that rejects a list that is not ten integers from 1 to 5.

**Exercise 12.12** (Python analysis · Extension · 30 min)

Simulate usability tests. Ten problems; each of $n$ users meets each problem independently with probability $p$.

- With $p=0.31$ for all ten and $n=5$, run 10{,}000 simulated tests. Report the mean share found and the 5th and 95th percentiles. *Checkpoint:* {mean near 84%; 5th percentile near 60%.}

- Make five problems easy ($p=0.5$) and five hard ($p=0.1$). Compare the simulated mean with $\frac{1}{10}\sum[1-(1-p_j)^5]$, and report how often a hard problem is found. *Checkpoint:* {about 69%; about 41%.}

- How many users does case (b) need before the hard problems are found 85% of the time on average?

**Exercise 12.13** (Body science · Foundation · 5 min)

In the synthetic example, the RR intervals rise and fall about every 5 s. Explain to an engineer, in four or five sentences, what in the body makes them do that, and why a missed beat shows up as one interval about twice as long as its neighbors.

**Exercise 12.14** (Body science · Core · 6 min)

The spec tells users to record “the same way: same time of day, same position.” Give two physiological reasons a reading taken standing up after coffee would differ from one taken lying down on waking, and say in which direction each moves RMSSD and heart rate.

**Exercise 12.15** (Science of the sport · Foundation · 6 min)

A rowing coach has 24 athletes and meets them at 6 a.m. for twenty minutes before the boats go out. Write the “User,” “One screen” and “Will not do” lines of a spec for a tool this coach would actually use, and give one reason from the sport's daily routine for each.

**Exercise 12.16** (Science of the sport · Extension · 8 min)

An endurance coach wants to change the day's session whenever an athlete's morning lnRMSSD drops below yesterday's. Using the chapter's “How good is the number?” section, explain why this rule is weak, and propose a better one the app could support.

**Exercise 12.17** (Field collection · Core · 60 min · CORE)

*Run a user test of your app.* Equipment: your deployed app's link as a QR code, a phone for each user (theirs or one you lend), the example file, a timer, a printed note sheet, the consent form (Appendix E), the SUS questionnaire.

- Recruit five people who did not help build the app; include at least one coach or athlete if you can.

- Consent: explain that you are testing the app, not them; that no heart data of theirs will be kept or shown; that they may stop at any time. Get a signature.

- Give the three tasks of Section 12.8 one at a time, as goals. Users who prefer not to use their own heart file use the example file for task 2.

- Ask them to think aloud. Do not help. Record hesitations over five seconds, wrong taps, misreadings, completion and time.

- After the tasks, give the SUS questionnaire and score it.

- Safety: the test involves no exercise. Do not ask anyone to record their heart during the session, and do not look at or write down a user's own results.

- Record: a table of problems (description, users who met it, severity: stopped / slowed / annoyed), the five SUS scores and their mean, and the three changes you will make.

**Exercise 12.18** (Field collection · Foundation · 30 min)

Record yourself at rest on waking on three mornings, with your chest strap and the logger you used in Chapter 5, following that chapter's morning protocol (Exercise 5.18). Load each file in your own app.

- Each morning: wake, empty your bladder, put on the strap, lie or sit in the same position as every other morning, and record three minutes breathing normally. The first minute is discarded; RMSSD comes from the last two minutes (cut the first minute from the file before loading it, or note that your app used the whole file).

- Load the file. Write down the percentage of beats removed and whether the app called the file usable.

- Equipment: strap, phone, a timer. Safety: if you feel unwell, skip the day; this is not a test of your health.

- Record: three files kept on your own device, and the quality line from each summary. Your RMSSD and heart rate stay with you; they are not handed in or graded.

**Exercise 12.19** (Build · Core · 90 min · CORE)

*Build step B-12: consolidate.* Bring your app from B-11 to the shape of this chapter's student app.

- Write the one-page spec (Table 12.1 as a model), including a test with a hand-worked answer and a “will not do” line.

- Keep what B-4 to B-11 built (file loading, the chart, the stored sessions and baseline). Keep every calculation in modules with no page code, as you have since B-2, and call the analysis from a Web Worker. The page must stay responsive while a file is analyzed.

- Add at least three known-answer tests (one hand calculation, one synthetic pattern, one file checked by an independent program) and make them pass with `npm test` (add `"test": "node –test"` to the scripts in `package.json`; your earlier test files from B-5 on run with it too).

- Add Basic and Advanced modes: Basic shows only what the spec's question needs; the choice is remembered on the device.

- Add a plain-text summary (copy and download) and a printable report.

- Add the privacy line under the title and the scope line in the footer, with your license and any attribution.

- Build with `npm run build`, put `dist/` on a static host, open it on a phone, and check the Network panel shows no request carrying a user's file.

- Run the user test of the field exercise, and make at least one change because of it.

**Exercise 12.20** (Communicate · Core · 20 min · CORE)

Write and rehearse a 90-second demonstration of your app to a coach (about 200 spoken words). Start from the coach's question, show the result before explaining, say how to use the number and what it does not do, mention privacy in one sentence, give one piece of evidence that it was tested, and end with one request. Record yourself once and time it.

**Exercise 12.21** (Check the AI · Core · 8 min)

An assistant writes this function and says: “On your six intervals 1000, 960, 1010, 990, 1040, 1000 it returns 37.86 ms, which matches the RMSSD formula.”

(`code/ai_rmssd.js`)

```javascript
export function rmssd(rr) {
  let sum = 0;
  for (let i = 1; i < rr.length; i++) sum += (rr[i] - rr[i - 1]) ** 2;
  return Math.sqrt(sum / rr.length);
}
```

Find the flaw, give the correct value, and write the one-line known-answer test that would have caught it.

**Exercise 12.22** (Build · Core · 45 min)

*Three inputs your app must survive* (Section 12.4.4). Add the required input tests to your app from B-12.

- Before writing any code, write a three-row table: normal, missing and invalid input; one example file for each; and the expected behavior (the number, or the exact message the user should see). Use your hand-worked test as the normal row.

- Write the three tests in a file `test/inputs.test.js` with `node:test`, the runner your tests have used since B-5. Include at least an empty file and a file with no column your app reads (missing), and one file in the wrong units (invalid).

- Run `npm test` *before* you change the app, and record which tests fail and what the app did with each bad file.

- Ask your assistant for the smallest change that makes the failing tests pass. Read the diff. Run `npm test` again. *Checkpoint:* {all your known-answer tests and the three input tests pass.}

- Load a good file, then each bad file, in the browser. Confirm that no number from the good file is left on screen and that no `NaN`, `Infinity` or blank number is ever shown.

**Exercise 12.23** (Python analysis · Core · 30 min)

Case file: Your case-file athlete's chest-strap recordings (see apopt.com/data/athletes) are CSV files with columns `time`, `ecg`, `hr`, `rr` and `marker`; the `rr` column is filled only on rows where a beat was detected. Choose one sleep or resting recording and one workout or interval-session recording.

- Feed each file through the three input checks of Section 12.4.4 (your own app's, or the student app's `checkInput`). Say whether each is normal input. *Checkpoint:* {both should pass; if one does not, report the message and the reason.}

- Compute the number of intervals, the share removed, RMSSD and average heart rate with the chapter's rules in Python (`code/check_rr.py` as a model), then load the same files in the student app or your own. *Checkpoint:* {the two programs agree within 0.01 ms and 0.01 bpm; any larger gap is a bug to find.}

- Load the same files in the Heart app, https://apopt.com/heart, and compare its RMSSD with yours. Give two reasons from the chapter why they may differ.

- Which of the two recordings would the student app's summary warn about, and why?

**Exercise 12.24** (Communicate · Core · 20 min)

Case file: Your case-file athlete's coach sends you two files from the athlete's chest-strap archive (see apopt.com/data/athletes), one overnight sleep recording and one interval session, and asks: “Run both through your app and tell me on which day the athlete was more recovered.” Run both files through your app (or the student app) and write a reply of no more than 120 words.
