File size: 12,644 Bytes
35e80ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# Frontend guide: showing the coaching result

**For:** the frontend / mobile engineer who builds the result screen.
**Related:** [FRONTEND_INTEGRATION.md](FRONTEND_INTEGRATION.md) (the API contract: request, errors, keys, backend call). This guide is about
**what to put on the screen**. Build against the sample responses in [`examples/responses/`](examples/responses/) before the live API is ready.

## 1. What you are building

One screen (or scroll) per analysed session. The API answers with one JSON object (`response_version: "2.0"`) that already contains
everything the screen shows. **Your job is to render it. Do not calculate, grade, colour-code, reword or translate anything.**

```
┌─────────────────────────────────────────┐
│  Mechanics score        77 / 100        │  score        (always shown; value may be null)
│  Mostly close to typical · medium conf. │  band + confidence
│  Based on 2 of 9 measurements, 6 swings │  basis
├─────────────────────────────────────────┤
│  Here is the one thing to work on …     │  summary      (always shown)
├─────────────────────────────────────────┤
│  What looks good            (0-3 items) │  strengths
│  What to work on  1. … 2. …  (0-2)      │  focus        (first = priority fix)
│  Try this drill: Name – how · "cue"     │  drill        (may be null)
├─────────────────────────────────────────┤
│  Timing                     (may be null)│  timing
│  Arm care                   (pitching)  │  arm_care
│  Keep in mind               (0-3 notes) │  data_quality
└─────────────────────────────────────────┘
```

The app never talks to this API with the secret key in the build; see FRONTEND_INTEGRATION.md section 1 (call it through your backend).

## 2. Field → component

| JSON | Component | Rules |
|---|---|---|
| `score.value` | Big number, "x / 100" | If `null`, **show `score.reason` in its place. Never show 0, "N/A" or an empty ring.** |
| `score.name` | Label above the number | Use as given (currently "Mechanics score"). |
| `score.band` | Caption under the number | Words only. Do not turn it into a grade, star rating or red/amber/green. |
| `score.confidence` | Small tag: High / Medium / Low | Show it. `low` is common for high school levels. Use a neutral style. |
| `score.basis` | Small text near the number | Show it ("2 of 9 measurements, 6 swings"). |
| `score.meaning` | Info icon → sheet/tooltip | Say what the score is and is not. Keep it one tap away. |
| `score.breakdown[]` | Optional "What makes up the score" list | `label`, `score` (0-100) and `weight` (share, adds to 1). Optional for the first release. |
| `summary` | Title | Always present. |
| `strengths[]` | "What looks good" list | Show `text`. Hide the whole block when empty. |
| `focus[]` | "What to work on" numbered list | **Order matters: item 1 is the priority fix.** Show `text`. Hide when empty. |
| `drill` | "Try this drill" card | `name` bold, `how` as body, `cue` as a highlighted quote. Hide when `null`. |
| `timing` | "Timing" card (section 4) | Hide when `null`. |
| `arm_care.lines[]` | "Arm care" list (pitching) | Show the lines exactly as given. Hide when `null`. |
| `data_quality[]` | "Keep in mind" list | **Always show when present.** It is part of the message, not fine print. |
| `request_id` | Hidden; in "Report a problem" and logs | Attach it to support tickets. |
| `meta.*`, `focus[].problem_key`, `strengths[].metric_key`, `evidence` | Not for display | Analytics and logging only. |

Text is plain, short and player-ready. **Render as plain text** (no HTML/Markdown parsing). Do not round, reformat or re-word numbers inside it.
Any block except `summary` and `score` can be empty; design every block so it disappears cleanly with no leftover heading.

## 3. The score

- It is a **0-100 mechanics score**: how close the measured mechanics are to the typical range for the player's level. It is calculated by
  the server from numbers. It is **not** a rating of the player, and typical is not the same as ideal.
- `value` is `null` when the video could not be read (`reason_code: "capture_not_ok"`) or too little could be judged
  (`"not_enough_measurements"`). Show the `reason` text. Do not hide the score card, or the player wonders what happened.
- `confidence`: `high`, `medium` or `low`. Hitting scores currently rest on at most two measurements, so expect `medium` or `low`.
- Use a **neutral colour** for the number. Do not colour by value (no green/red). The scale is not a pass/fail test.
- Do not compare scores across sessions with arrows or "you improved" unless product asks for it later; the score depends on the
  measurements available in that session (`basis` can differ).

## 4. The timing card

`timing` describes **when** movements happened (preparation, front foot down, swing). It is descriptive only.

| Field | Show as |
|---|---|
| `summary` | Card subtitle. |
| `observations[]` | One row each: show `text`. Optionally `value_ms` as a number next to `label` (already rounded to 10 ms). `swings` and `range_ms` are optional detail. |
| `unavailable[]` | A muted row: `label` + `text` ("Actual contact or closest approach was not established."). Do not draw an empty chart for these. |
| `consistency` | Optional line: "Across {swings} {practice_type} swings:" then `notes[]`. Only present with 5+ swings of the same practice type. |
| `data_quality[]` | Small text under the card. **Always show it.** It says what the numbers cannot show. |

Rules:
- **No good/bad styling and no early/late/rushed wording of your own.** Every number is an estimate; the response never says a player was early or late.
- `value_ms` is for display and simple charts only. Do not threshold it.
- A missing measurement is `unavailable`, never 0.
- When a timing-only request was sent, `score.value` is `null`, `focus`/`strengths`/`drill` are empty and `meta.fallback_reason` is `"timing_only"`. Show the timing card as the main content and skip the empty blocks.

## 5. Screen states (sample file for each)

Build and test every state with the file in [`examples/responses/`](examples/responses/). They are real outputs of the API code.

| State | How to recognise it | Sample file | Show |
|---|---|---|---|
| Normal, with problems | `focus` not empty | `hitting_with_timing.json` | Everything above. |
| Nothing to work on | `focus` empty, `strengths` not, score high | `hitting_clean.json` | Positive result; no "work on" block. |
| Pitching | `arm_care` not null | `pitching_arm_care.json` | Arm-care list; keep the lines verbatim. |
| **Record again** | `score.reason_code == "capture_not_ok"` | `record_again.json` | A dedicated screen: `summary` + the first `data_quality` line + a "Record again" button. No score number, no drill. |
| Score withheld, video fine | `score.value == null` and reason `not_enough_measurements` | `score_withheld_low_fps.json` | Score card with the reason text, the rest as normal. |
| Timing only | `meta.fallback_reason == "timing_only"` | `timing_only.json` | Timing card as the main content. |

Also handle: the first request taking up to ~3 s (show a progress state, timeout at 30 s), and the error cases below.

## 6. Loading, errors and retries

| Situation | What the screen does |
|---|---|
| Waiting | Progress indicator; keep the video/session context visible. Typical 1.5-3 s, cached repeats are instant. Client timeout 30 s. |
| `200` | Render. `meta.source` can be `llm` or `rules`; both are valid and safe, **do not label or hide either**. |
| `401` / `413` / `422` | A bug on your side or the backend's. Show a generic "Something went wrong" and log `detail`. Do not retry. |
| `500` / timeout / no network | Retry once after 1 s, then "Try again" button. Repeating is safe and free (identical sessions are cached). |

## 7. TypeScript types

Field names are `snake_case` in the JSON. Keep them as is, or map them in one place.

```ts
export interface CoachResponse {
  response_version: "2.0";
  request_id: string;
  session_id: string | null;
  discipline: "hitting" | "pitching";
  level: string | null;
  level_assumed: boolean;
  score: Score;
  summary: string;
  strengths: { metric_key: string; text: string }[];
  focus: { problem_key: string; evidence: string[]; text: string }[];
  drill: { name: string; how: string; cue: string | null } | null;
  timing: Timing | null;
  data_quality: string[];
  arm_care: ArmCare | null;
  meta: { source: "llm" | "rules"; model: string | null; prompt_version: string; cache_hit: boolean;
          fallback_reason: string | null; latency_ms: number | null };
}

export interface Score {
  name: string;
  meaning: string;
  value: number | null;              // 0-100, or null
  band: string | null;
  confidence: "high" | "medium" | "low" | null;
  basis: string | null;
  in_range: number;
  checked: number;
  breakdown: { metric_key: string; label: string; score: number; weight: number; zone: string }[];
  reason_code: "capture_not_ok" | "not_enough_measurements" | null;
  reason: string | null;
}

export interface Timing {
  summary: string;
  observations: { metric_key: string; label: string; value_ms: number; swings: number;
                  range_ms: [number, number] | null; status: "estimated"; text: string }[];
  unavailable: { metric_key: string; label: string; reason_codes: string[]; text: string }[];
  data_quality: string[];
  consistency: { practice_type: string; swings: number; notes: string[] } | null;
}

export interface ArmCare {
  pitch_count_today: number | null; daily_max: number | null; next_eligible_date: string | null;
  alerts: string[]; mechanics_drift: string | null;
  lines: string[];                    // show these
}
```

Treat unknown extra fields as ignorable: the API may add fields without changing `response_version`. A different `response_version` means the contract changed; show a generic error and log it.

## 8. Rendering skeleton (framework-neutral)

```tsx
function ResultScreen({ r }: { r: CoachResponse }) {
  if (r.score.reason_code === "capture_not_ok") return <RecordAgain text={r.summary} note={r.data_quality[0]} />;
  return (
    <Screen>
      <ScoreCard score={r.score} />                      {/* value null -> shows score.reason */}
      <Title>{r.summary}</Title>
      {r.strengths.length > 0 && <List title="What looks good" items={r.strengths.map(s => s.text)} />}
      {r.focus.length > 0 && <NumberedList title="What to work on" items={r.focus.map(f => f.text)} />}
      {r.drill && <DrillCard drill={r.drill} />}
      {r.timing && <TimingCard timing={r.timing} />}
      {r.arm_care && r.arm_care.lines.length > 0 && <List title="Arm care" items={r.arm_care.lines} />}
      {r.data_quality.length > 0 && <List title="Keep in mind" items={r.data_quality} />}
      <ReportProblem requestId={r.request_id} />
    </Screen>
  );
}
```

## 9. Accessibility and copy

- Reading level is about grade 9; keep the font size comfortable. Don't truncate `text`; let it wrap.
- Don't convey the score by colour alone; the number and `band` words carry the meaning.
- Support dynamic type / large fonts without clipping the score card.
- All text comes from the server in English. Don't machine-translate numbers or coaching text on the client.

## 10. Checklist before release

- [ ] Every sample in `examples/responses/` renders without layout breaks or empty headings.
- [ ] `score.value == null` shows `score.reason`, never 0 or a blank ring.
- [ ] `data_quality` (response and timing) is always visible when present.
- [ ] "Record again" is its own screen with a button back to the camera.
- [ ] No colour grading, no pass/fail wording, no client-side re-wording of coaching text or numbers.
- [ ] `focus` order is preserved (priority fix first).
- [ ] Pitching shows `arm_care.lines` exactly as sent.
- [ ] 30 s timeout, one retry on timeout/500, no retry on 401/413/422.
- [ ] `request_id` is attached to "Report a problem" and logs.
- [ ] The secret API key is not in the app build (call through your backend; see FRONTEND_INTEGRATION.md).

If the samples ever drift from the live API, regenerate them with `python tools/build_response_examples.py` (a test fails when they are stale).