diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2284399..7635762 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -27,5 +27,7 @@ jobs:
working-directory: site
- name: Validate Hawk app contract
run: node scripts/deploy-check.mjs --contract >/dev/null
+ - name: Test server progress store
+ run: node --test server/test_progress.mjs
- name: Test Python runner
run: python3 -m unittest discover -t . -s runner -p "test_*.py" -v
diff --git a/.gitignore b/.gitignore
index 41c33c8..5c35259 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
__pycache__/
*.pyc
+.data/
diff --git a/.hawk/app.json b/.hawk/app.json
index 1693419..a92f11e 100644
--- a/.hawk/app.json
+++ b/.hawk/app.json
@@ -5,13 +5,14 @@
"port": 3000,
"health": "/health",
"database": null,
- "data_dir": null,
+ "data_dir": "/data",
"required_env": [
"APP_URL"
],
"optional_env": [
"PORT",
"HOST",
+ "DATA_DIR",
"RUNNER_URL",
"HAWK_SUITE_ISSUER",
"HAWK_SUITE_TRUST_PROXY",
diff --git a/Dockerfile b/Dockerfile
index b2b3fc6..9e1306b 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -16,9 +16,12 @@ ENV APP_REVISION=${APP_REVISION}
LABEL org.opencontainers.image.revision=${APP_REVISION}
ENV NODE_ENV=production PORT=3000 HOST=0.0.0.0
RUN groupadd --system --gid 1001 nodejs \
- && useradd --system --uid 1001 --gid nodejs hawklearn
+ && useradd --system --uid 1001 --gid nodejs hawklearn \
+ && mkdir -p /data \
+ && chown hawklearn:nodejs /data
COPY --from=builder --chown=hawklearn:nodejs /app/site/dist ./site/dist
COPY --chown=hawklearn:nodejs server.mjs ./server.mjs
+COPY --chown=hawklearn:nodejs server ./server
COPY --chown=hawklearn:nodejs .hawk ./.hawk
COPY --chown=hawklearn:nodejs scripts/deploy-check.mjs ./scripts/deploy-check.mjs
USER hawklearn
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 1422a3b..57d9530 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -7,7 +7,10 @@ services:
- "3000:3000"
environment:
APP_URL: http://localhost:3000
+ DATA_DIR: /data
RUNNER_URL: http://hawk-learn-runner:4000
+ volumes:
+ - hawk_learn_data:/data
networks:
- default
- learn_runner
@@ -34,3 +37,6 @@ services:
networks:
learn_runner:
internal: true
+
+volumes:
+ hawk_learn_data:
diff --git a/docs/screenshots/pr-30/after-index.png b/docs/screenshots/pr-30/after-index.png
new file mode 100644
index 0000000..e620f84
Binary files /dev/null and b/docs/screenshots/pr-30/after-index.png differ
diff --git a/docs/screenshots/pr-30/after-lesson1.png b/docs/screenshots/pr-30/after-lesson1.png
new file mode 100644
index 0000000..ab5127d
Binary files /dev/null and b/docs/screenshots/pr-30/after-lesson1.png differ
diff --git a/docs/screenshots/pr-30/after-lesson2.png b/docs/screenshots/pr-30/after-lesson2.png
new file mode 100644
index 0000000..a934f33
Binary files /dev/null and b/docs/screenshots/pr-30/after-lesson2.png differ
diff --git a/docs/screenshots/pr-30/after-lesson3.png b/docs/screenshots/pr-30/after-lesson3.png
new file mode 100644
index 0000000..9fd3fac
Binary files /dev/null and b/docs/screenshots/pr-30/after-lesson3.png differ
diff --git a/docs/screenshots/pr-30/after-lesson4.png b/docs/screenshots/pr-30/after-lesson4.png
new file mode 100644
index 0000000..911578d
Binary files /dev/null and b/docs/screenshots/pr-30/after-lesson4.png differ
diff --git a/docs/screenshots/pr-30/before-index.png b/docs/screenshots/pr-30/before-index.png
new file mode 100644
index 0000000..0afc513
Binary files /dev/null and b/docs/screenshots/pr-30/before-index.png differ
diff --git a/docs/screenshots/pr-30/before-lesson1.png b/docs/screenshots/pr-30/before-lesson1.png
new file mode 100644
index 0000000..5568ba7
Binary files /dev/null and b/docs/screenshots/pr-30/before-lesson1.png differ
diff --git a/docs/screenshots/pr-30/before-lesson2.png b/docs/screenshots/pr-30/before-lesson2.png
new file mode 100644
index 0000000..8a2006b
Binary files /dev/null and b/docs/screenshots/pr-30/before-lesson2.png differ
diff --git a/docs/screenshots/pr-30/before-lesson3.png b/docs/screenshots/pr-30/before-lesson3.png
new file mode 100644
index 0000000..34d6619
Binary files /dev/null and b/docs/screenshots/pr-30/before-lesson3.png differ
diff --git a/docs/screenshots/pr-30/before-lesson4.png b/docs/screenshots/pr-30/before-lesson4.png
new file mode 100644
index 0000000..bb47883
Binary files /dev/null and b/docs/screenshots/pr-30/before-lesson4.png differ
diff --git a/lessons/01-flowcharts/README.md b/lessons/01-flowcharts/README.md
index 2abd87b..baa741c 100644
--- a/lessons/01-flowcharts/README.md
+++ b/lessons/01-flowcharts/README.md
@@ -1,85 +1,81 @@
---
title: "Programs are step-by-step"
-goal: "See a program as a flowchart of blocks and watch the computer evaluate it one step at a time."
+goal: "Follow a robot flowchart from START to END and watch the computer run one instruction at a time."
order: 10
section: "Programming with Blocks"
---
# One step at a time
-Before we write a single line of code, let's get the big idea out of the way:
-**a program is a list of steps, and the computer does them one at a time, in
-order.** It never does two things at once by accident, and it never skips
-ahead. It finishes one step, then moves to the next.
+Before we write a single line of Python, let's get the big idea out of the way:
+**a program is a list of instructions, and the computer runs them one at a time,
+in order.** It never skips ahead, and it never runs two steps at once by
+accident. It finishes one box, updates its memory, and follows the arrow to the
+next box.
-A good way to picture this is a **flowchart** — boxes joined by arrows. Each box
-does one small thing, and the arrows show what feeds into what. The computer
-follows the arrows.
+A **flowchart** shows that exact journey from **START** to **END**:
-The block editor here is exactly that: a little flowchart that does
-math. Read it from top to bottom, the same way you read code:
+- Each **box** is one instruction — like storing a number or doing math.
+- Each **arrow** shows which step runs next.
+- **Robot Memory** at the bottom shows the named values the robot is remembering
+ right now.
-- The **number** blocks hold values.
-- The **+** and **×** blocks each take *two* inputs (the arrows coming in from
- the blocks above them) and produce *one* output.
-- The **result** block at the bottom shows the final answer.
+The flowchart here calculates an FRC robot's **autonomous score**: `3` coral at
+`4` points each, plus a `3`-point bonus for leaving the starting zone.
-Press **▶ Run step by step** and watch. The computer can't multiply until it
-knows what `3 + 4` is, so it works out the inner block first, then feeds that
-answer forward. That order — inputs before the things that use them — is the
-whole game.
+Press **▶ Run** (or click **⏭ Step** to advance one instruction at a time) and
+watch **Robot Memory** update as each box lights up. You can also click
+**Peek at Python** to see the exact same steps written as real Python code.
```blocks
preset: sequence
```
-# Blocks carry values
+# Order matters because steps share memory
-So this flowchart computes `(3 + 4) × 2`. Notice the computer had to figure out
-`3 + 4 = 7` *before* it could do `7 × 2 = 14`. It literally cannot do the
-multiply first — one of its inputs doesn't exist yet. **Every block has to wait
-for its inputs to be ready.**
+Notice how `points` changed twice during the run:
-That waiting is why order matters, and it's the same reason the lines of a real
-program run top to bottom: later steps often depend on what earlier steps
-produced.
+1. First, `points = coral × 4` stored `12` in Robot Memory.
+2. Next, `points = points + 3` read that `12`, added `3`, and updated `points`
+ to `15`.
-Now make it your own. The number blocks in the editor are **editable** this
-time — click into one and change its value. Before you press Run, try to predict
-the new answer in your head. Then run it and check whether the value flowing
-into the result block matches what you expected.
+If you tried to add the bonus *before* calculating `coral × 4`, `points`
+wouldn't even exist yet! **Later steps depend on what earlier steps stored in
+memory** — that's why top-to-bottom order is the foundation of every program.
+
+Now experiment. The `coral` and `leave_bonus` boxes are **editable** — click a
+number to change it, predict the new score in your head, then **Step** through
+to check your prediction.
Some things to try:
-- Set the two top numbers so their sum is `10`. What does the result become?
-- Can you make the result equal `0`? (Hint: what times anything is zero?)
-- Make the result a **negative** number.
+- Score `5` coral with a `3`-point leave bonus. What does `points` reach?
+- What if the robot didn't leave the starting zone (`leave_bonus = 0`)?
+- What if `coral = 0` and `leave_bonus = 0`?
```blocks
preset: edit-values
```
-# Build your own math machine
-
-Time to build a flowchart from scratch. This canvas starts with two number
-blocks and a result block, and a toolbar for adding more.
-
-**How to work the editor:**
-
-- Click a toolbar button — **number**, **+**, **−**, or **×** — to drop a new
- block onto the canvas. Drag blocks around to arrange them.
-- **Connect blocks by dragging** from the little dot on the bottom of one block
- to a dot on the top of another. An operation block has *two* dots on top
- because it needs two inputs; the result block has one.
-- Press **▶ Run step by step** to watch your machine evaluate. **Reset** clears
- the shown values so you can run it again.
-
-A block shows `?` when it doesn't have all of its inputs wired up yet — that's
-the computer telling you a step is missing.
-
-Your challenge: build a machine that computes **`(8 − 3) × 4`** and check that
-the result block lands on `20`. You'll need a subtract block feeding into a
-multiply block, just like the very first example — except now *you* decide the
-order the computer works in.
+# Build your own scoring flowchart
+
+Time to build a flowchart yourself. Suppose our robot took `8` shots
+(`attempts`) and dropped `3` of them (`dropped`), and each scored coral is worth
+`4` points.
+
+**How to build:**
+- **Drag a block** from the palette into the drop slot (or click its **`+`**
+ button to insert it).
+- Use the **↑ / ↓** arrows on any block you added to change the order, or the
+ **trash icon** to remove it.
+- Press **▶ Run** or **⏭ Step** to trace your program. **Clear run** resets only
+ the animation (your blocks stay safe); **Start over** resets the whole canvas.
+
+Your challenge: assemble the steps so the robot computes
+**`(attempts − dropped) × 4`** and outputs `score`. Try putting the multiply
+block *before* the subtract block once just to see what happens when a step
+reads a variable that hasn't been calculated yet — then put them in the right
+order and click **✓ Check** to test your flowchart against three match
+scenarios!
```blocks
preset: build
diff --git a/lessons/02-conditionals/README.md b/lessons/02-conditionals/README.md
index 4485103..85ab887 100644
--- a/lessons/02-conditionals/README.md
+++ b/lessons/02-conditionals/README.md
@@ -1,86 +1,72 @@
---
title: "Making decisions"
-goal: "Use a condition to make a program choose between two paths."
+goal: "Use a condition diamond to make a program choose one path and skip the other."
order: 20
section: "Programming with Blocks"
---
-# When programs choose
+# When a robot has to choose
-So far our flowcharts always did the exact same steps in the exact same order.
-Real programs need to **make decisions**: do one thing when the weather is cold,
-another when it's warm; show "pass" when a score is high enough, "fail" when it
-isn't.
+So far our flowcharts ran every single box from **START** to **END**. Real
+robots have to **make decisions** based on sensors: slow down when the battery
+is low, shoot when the target is in range, or stop when an arm hits its limit
+switch.
-In a flowchart, a decision is a **diamond**. It takes two numbers, `a` and `b`,
-and asks a yes/no question about them — `a > b?` here (the question can also
-use `<`, `=`, or `≠`). Then the program follows **exactly one of the two
-arrows leaving it**: the `true` arrow when the answer is yes, the `false`
-arrow when it's no. Never both, never neither.
+In a flowchart, a decision is a **diamond** (`IF ... ?`). It asks a yes/no
+question about the robot's memory — here, `battery < 10 ?` — and then follows
+**exactly one** of its two outgoing arrows:
-Each arrow leads to an **answer** block — the step that runs on that path. An
-answer block has two inputs: `when` (wired from one of the diamond's arrows)
-and `value` (what to produce if its path is the one taken). The branch the
-program doesn't take simply **never runs**.
+- Follow **YES** when the condition is **True**.
+- Follow **NO** when the condition is **False**.
-The flowchart in the editor finds **the larger of two numbers**. The diamond
-asks `a > b?` — that's `true` here (`7 > 4`) — so the program follows the
-`true` arrow down to the answer wired to `a`, and `7` flows on to the result.
+The other branch **grays out and is completely skipped** — none of the steps on
+that side ever run. After the taken branch finishes, both paths come back
+together and continue to **OUTPUT** and **END**.
-Press **▶ Run step by step**. Watch the diamond answer `true` and the program
-head down the `true` arrow — while the other branch **grays out and gets
-skipped**. Those blocks never run. This fork is exactly what Python writes as
-`if / else`, and you'll type it yourself in [lesson {n}](#/lesson/09-if-statements).
+Press **▶ Run** or **⏭ Step** on this **Battery Brownout Limiter**. With
+`battery = 12`, watch the robot check `12 < 10` (False), follow the **NO**
+arrow to set `mode = "FULL POWER"` and `max_speed = 100`, and skip the entire
+**YES** branch. Click **Peek at Python** to see how this maps directly to
+`if / else` (which you'll write yourself in
+[lesson {n}](#/lesson/09-if-statements)).
```blocks
preset: cond-demo
```
-# The road not taken
+# Testing the boundary
-The key idea: a decision **takes exactly one path, every time.** The other
-branch isn't "a value you don't use" — it's code that **never runs**. Watch it
-gray out during a run: the computer doesn't even look at it.
+A decision **takes exactly one path, every time.** Every step inside the untaken
+branch is skipped — the computer doesn't even touch it.
-The numbers are editable now. Try these and run each time:
+Now both the `battery` voltage and the `IF` condition are editable. Try these
+and **Step** through each one:
-- Make `a` **smaller** than `b`. Which arrow does the program follow now?
- `a > b` is `false`, so it takes the `false` branch — and the answer wired to
- `b` is the one that runs while the other side gets skipped.
-- Make `a` and `b` **equal**. Is `a > b` true or false when they're the same?
- (This is a classic bug source — "greater than" is not the same as "greater
- than or equal to.")
-
-The result always ends up being whichever number is bigger, no matter which one
-you put where. That's the whole point: the program adapts to its inputs instead
-of doing one fixed thing.
+- Set `battery` to **`9`**. Now `9 < 10` is **YES (True)** — watch the **YES**
+ branch run (`mode = "LOW POWER"`, `max_speed = 40`) while the **NO** branch
+ grays out.
+- Set `battery` to **`10`** — right on the boundary! Is `10 < 10` True or False?
+ (This is one of the most common bugs in robotics code: `<` means *strictly
+ less than*, while `≤` includes the boundary itself.)
+- Try switching `<` to `≤` in the diamond and run `battery = 10` again.
```blocks
preset: cond-edit
```
-# Build a decision
-
-Your turn. Build a flowchart that outputs **the smaller of two numbers** and
-check it against a few inputs.
-
-**How:** you have a toolbar with number blocks, four decision diamonds
-(`if >`, `if <`, `if =`, `if ≠`), and an **answer** block. Drag from a block's
-output dot to an input dot on another block to wire things up.
-
-A diamond needs `a` and `b` wired into its top. Each answer block needs two
-wires: `when` (from one of the diamond's `true`/`false` arrows) and `value`
-(the number that path should produce). Wire both answers into the result.
+# Build a shooter range check
-Two ways to get the *smaller* number — see if you can find both:
+Your turn. Our robot has a distance sensor measuring how many meters away the
+target is (`distance`).
-- Use `if <`: ask `a < b`, wire the `true` arrow's answer to `a` and the
- `false` arrow's answer to `b`.
-- Or use `if >` and swap which number each answer is wired to.
+**Your challenge:**
+- If `distance < 3`, the robot should set `action = "SHOOT"`.
+- Otherwise (`NO`), the robot should set `action = "DRIVE CLOSER"`.
-Both work, because a decision is really just "which path do I take?" — and
-each path carries its own answer. Run it with different numbers to convince
-yourself it always picks the smaller one.
+**How:** drag a block from the palette into the **YES** drop slot and another
+into the **NO** drop slot (or click **`+`**). Then click **✓ Check** — it will
+automatically test your flowchart with `distance = 2`, the boundary `distance = 3`,
+and `distance = 5`!
```blocks
preset: cond-build
diff --git a/lessons/03-loops/README.md b/lessons/03-loops/README.md
index 3890fe5..ac73ecf 100644
--- a/lessons/03-loops/README.md
+++ b/lessons/03-loops/README.md
@@ -1,71 +1,70 @@
---
title: "Doing things over and over"
-goal: "Use a loop to repeat a step many times without copying it out by hand."
+goal: "Use a loop with a loop-back arrow to repeat instructions without copying them by hand."
order: 30
section: "Programming with Blocks"
---
# Repeating without copying
-Imagine you want to add `3` to a number five times. You *could* drag out five
-separate `+` blocks and chain them together. But what if it were five hundred
-times? Copying a block out by hand stops working fast.
+If you slam an FRC drive motor straight from `0%` to `100%` speed in one
+instant, the wheels slip and the battery voltage drops. Instead, robot code
+**ramps** the speed up smoothly in small steps: `+20%`, `+20%`, `+20%`, `+20%`,
+`+20%`.
-Programs solve this with a **loop**: one block with its own logic built in,
-that runs that logic over and over. The **repeat** block in the editor takes
-just one thing from outside — **times**, how many passes to run — and it
-carries its own **start** value and **by** step right on the block, editable
-whenever you like.
+You *could* paste five identical `speed = speed + 20` boxes in a row — until you
+need to ramp in 50 steps! Programs solve this with a **loop**:
-This one starts at `0` and adds `3`, five times over. Press **▶ Run step by
-step** and watch the block's value climb — `0`, `3`, `6`, `9`, `12`, `15`.
-Each pass runs the *same* internal logic again, using the result so far.
+1. The **REPEAT** header tracks which pass you're on (`Pass 1 / 5`, `Pass 2 / 5`,
+ …).
+2. The computer runs the step(s) **inside** the loop body.
+3. At the bottom of the body, it follows the curved **loop-back arrow** up to the
+ top to repeat again.
+4. Once all passes finish, it exits through the **DONE** arrow.
+
+Press **▶ Run** or **⏭ Step** and watch the loop-back arrow light up on each
+pass while `speed` in **Robot Memory** climbs: `0 → 20 → 40 → 60 → 80 → 100`.
+Click **Peek at Python** to see how this becomes a `for` loop in Python.
```blocks
preset: loop-demo
```
-# A loop keeps a running total
-
-Notice what the repeat block is really doing: it remembers a value (its
-**start**), and each pass updates that value using its **by** step. That
-"value so far" is the heart of every loop — it's how five identical passes add
-up to something.
+# Loops update memory on every pass
-This one starts at `1` and *multiplies* by `2`, four times. Before you run it,
-predict the sequence in your head — `1`, then… Run it and watch: `1`, `2`,
-`4`, `8`, `16`. Repeated multiplying grows *fast*; that's the same reason
-folding a piece of paper in half again and again gets thick so quickly.
+The reason a loop can accomplish something different on each pass — even though
+it runs the *exact same box* — is that the box reads and updates a variable in
+**Robot Memory** every time around.
-Now experiment. The **times** input is editable, and so are the block's own
-**start** and **by** fields:
+Here, `power` starts at `1` and **doubles** (`power = power × 2`) on each pass,
+four times: `1 → 2 → 4 → 8 → 16`.
-- Change **times** and watch how many passes the loop takes.
-- Set **start** to `10` and **by** to `10` — what running total do you get
- after a few passes?
-- What happens with **times** set to `0`? A loop that repeats zero times just
- hands back its **start** value, untouched.
+Experiment with the editable numbers and step through:
+- Change the repeat count to **`5`** or **`6`** — watch how fast repeated
+ doubling grows!
+- Change the repeat count to **`0`**. What happens? A loop that runs zero times
+ skips its body completely and jumps straight to the **DONE** arrow, leaving
+ `power` untouched at `1`.
+- Change the multiplier from `2` to `3` and predict the result before running.
```blocks
preset: loop-edit
```
-# Build a loop
-
-Build a repeat block that computes **2 to the 5th power** — that's `2`
-multiplied by itself, ending on `32`.
+# Build a flywheel spin-up loop
-**How:** the toolbar has number blocks, a **repeat +**, and a **repeat ×**.
-Drop one in, wire a number into its **times** input, then set its **start**
-and **by** fields directly on the block. Send its output to the result block.
+Your turn. Build a loop that starts with `power = 1` and ends at **`32`** (which
+is 2⁵: `1 → 2 → 4 → 8 → 16 → 32`).
-Think about which pieces you need: to keep multiplying by `2`, what should
-**start** be so the very first multiply gives you `2`? How many **times** do
-you repeat to land on `32`? Run it step by step and check the climb: `2`, `4`,
-`8`, `16`, `32`.
+**How:**
+- Drag the right step from the palette **inside the REPEAT loop body** (or click
+ **`+`**).
+- Set the **REPEAT** count to the right number of passes.
+- Press **▶ Run** or **⏭ Step** to watch each pass climb toward `32`, then click
+ **✓ Check** to verify!
-Once that works, try a **repeat +** that counts to `100` — there's more than
-one combination of **start**, **times**, and **by** that gets there.
+Once that passes, try swapping in `power = power + 10` and adjusting the repeat
+count to see how easy it is to change what a loop does.
```blocks
preset: loop-build
diff --git a/lessons/04-functions/README.md b/lessons/04-functions/README.md
index 55c76d9..b753bb1 100644
--- a/lessons/04-functions/README.md
+++ b/lessons/04-functions/README.md
@@ -1,69 +1,74 @@
---
title: "Reusable blocks"
-goal: "Package a flowchart into a named block you can reuse instead of rebuilding it."
+goal: "Package a flowchart into a named function you can call from anywhere instead of rebuilding it."
order: 40
section: "Programming with Blocks"
---
-# A block with a flowchart inside
+# Jumping into a reusable flowchart
-Look at the top of the block editor. There's a block called **double**,
-and it has its own little flowchart *inside* it: an input `n`, a `× 2`, and an
-output. That's a **function** — a small program you've wrapped up and given a
-name.
+Look to the right of **Main Program**: there is a separate mini-flowchart called
+**`double(n)`**. That's a **function** — a small routine you write once, give a
+name, and call whenever you need it.
-Down in your program, you don't see those inner blocks anymore. You just see one
-tidy **double** block. Feed it a number and it hands back that number times two.
-Here we give it `5`, and out comes `10`.
+- **`n`** is its **parameter** (the input handed in when you call it).
+- Inside, it calculates `result = n × 2` in its own local memory.
+- At the bottom, **`RETURN result`** hands the answer back to wherever it was
+ called from.
-Press **▶ Run step by step**. The `double` block lights up and produces `10` —
-without you ever having to place the `× 2` yourself. The messy details are
-hidden inside; you just *use* the block.
+Press **⏭ Step** (or **▶ Run**) and watch closely! When **Main Program** reaches
+`boosted = double(speed)`:
+
+1. Execution **pauses** in Main Program and **jumps over to `double(n)`**.
+2. `n` receives `5` (the value of `speed`).
+3. `double` runs `result = 5 × 2 = 10` (watch **`double()` Local Memory** at the
+ bottom!) and returns `10`.
+4. Execution **jumps back** to Main Program and stores `10` in `boosted`.
+
+Check the **Call Stack** at the bottom while it's inside `double` — that's how
+the computer remembers where to return!
```blocks
preset: fn-demo
```
-# Define once, use many times
+# Define once, call as many times as you need
-Here's why functions are worth the trouble: **you build the flowchart once, then
-reuse it as many times as you like.**
+Here is why functions are so useful in robot code: **you define the routine
+once, then call it as many times as you want with different inputs — and if you
+ever need to change how it works, you only change it in one place.**
-This program feeds `3` into a `double` block, and then feeds *that* result into
-**another** `double` block. Same block, used twice. `3` becomes `6`, and `6`
-becomes `12`.
+This program calls `boost_speed(speed)` **twice in a row**. Watch the
+**`boost_speed(n)`** card on the right as you step through:
-Press **▶ Run step by step** and watch the value pass through both copies. Each
-`double` block runs the exact same inner flowchart — you defined it a single
-time, but you can drop it in wherever you need it. Imagine the double block
-secretly held fifty inner blocks; you'd still just wire up one tidy "double" and
-move on.
+- On the **1st call**, `n` becomes `3` and `boost_speed` returns `6`.
+- On the **2nd call**, the *exact same* flowchart runs again, except now `n` is
+ `6` and `boost_speed` returns `12`.
-Change the starting number and run again. Whatever you put in, it comes out
-multiplied by four — because doubling twice is the same as ×4.
+Now try editing the **`2`** *inside* the `boost_speed` function on the right
+(for example, change it to `3`) and run again. Notice that changing the function
+**once** automatically updates **both** calls in Main Program (`3 → 9 → 27`)!
```blocks
preset: fn-chain
```
-# Build with reusable blocks
+# Build a match scoring pipeline
-Now you have **two** reusable blocks in the toolbar: **add 1** (which does
-`n + 1`) and **double** (which does `n × 2`). You can see both inner flowcharts
-at the top of the panel.
+Now you have **two** reusable FRC scoring functions defined on the right:
+- **`add_leave_bonus(pts)`** — adds `1` bonus point and returns the new score.
+- **`coop_double(pts)`** — doubles the score and returns it.
-Your challenge: starting from the number `4`, build a program whose result is
-**exactly `10`**, using the `add 1` and `double` blocks.
+**Your challenge:** starting from `score = 4`, drag function calls into **Main
+Program** so that the final match score is **`10`** (and `14` when `score = 6`).
-**Order matters** — and this is the whole lesson. `4` fed through *add 1 then
-double* gives `(4 + 1) × 2 = 10`. But *double then add 1* gives
-`4 × 2 + 1 = 9`. Same two blocks, different order, different answer — just like
-[the very first lesson](#/lesson/01-flowcharts), where the computer had to do the inner step before the
-outer one.
+**Order matters!**
+- `add_leave_bonus` *then* `coop_double`: `(4 + 1) × 2 = 10`
+- `coop_double` *then* `add_leave_bonus`: `(4 × 2) + 1 = 9`
-Wire a block's output into the next block's `n` input to chain them, then send
-the last block into the result. Run it step by step and confirm you land on
-`10`. Then see what *double then add 1* gives you instead.
+Use the **↑ / ↓** arrows on the blocks you add to test both orders, step through
+to watch the values jump into each function on the right, and click **✓ Check**
+to verify your solution against all three match scores!
```blocks
preset: fn-build
diff --git a/scripts/deploy-check.mjs b/scripts/deploy-check.mjs
index ab61cb4..000dc41 100644
--- a/scripts/deploy-check.mjs
+++ b/scripts/deploy-check.mjs
@@ -35,6 +35,9 @@ if (process.argv.includes("--contract")) {
const port = Number(process.env.PORT);
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error();
}
+ if (process.env.DATA_DIR !== undefined && !process.env.DATA_DIR.trim()) {
+ throw new Error();
+ }
console.log(JSON.stringify({ status: "ok", contract: contract.schema }));
} catch {
// Parse errors can contain credentials. Report names, never values.
diff --git a/server.mjs b/server.mjs
index 1231082..777f26c 100644
--- a/server.mjs
+++ b/server.mjs
@@ -2,9 +2,13 @@ import { createReadStream, statSync } from 'node:fs'
import http from 'node:http'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
+import { openProgressDb } from './server/progress-db.mjs'
const rootDir = path.dirname(fileURLToPath(import.meta.url))
const distDir = path.resolve(process.env.DIST_DIR || path.join(rootDir, 'site', 'dist'))
+const dataDir = path.resolve(
+ process.env.DATA_DIR || (process.env.NODE_ENV === 'production' ? '/data' : path.join(rootDir, '.data')),
+)
const host = process.env.HOST || '0.0.0.0'
const port = Number(process.env.PORT || 3000)
const revision = process.env.APP_REVISION || 'development'
@@ -12,6 +16,10 @@ const runnerUrl = (process.env.RUNNER_URL || '').replace(/\/+$/, '')
const trustProxy = process.env.HAWK_SUITE_TRUST_PROXY === 'true'
const expectedTeamId = process.env.HAWK_SUITE_TEAM_ID || ''
+const progressDb = openProgressDb(path.join(dataDir, 'progress.db'))
+
+const LESSON_SLUG_RE = /^[a-z0-9][a-z0-9-]{0,99}$/
+
const MAX_BODY_BYTES = 64 * 1024
const RATE_LIMIT_BURST = 5
const RATE_LIMIT_REFILL_PER_SEC = 0.5 // 30 runs/minute per user
@@ -125,13 +133,87 @@ function readJsonBody(req) {
})
}
+function resolveUser(req) {
+ if (!trustProxy) {
+ return {
+ userKey: 'local-dev',
+ slackUserId: 'local-dev',
+ slackTeamId: 'local',
+ slackName: 'Local Developer',
+ }
+ }
+ const slackUserId = String(req.headers['x-hawk-slack-user'] || '').trim()
+ const slackTeamId = String(req.headers['x-hawk-slack-team'] || '').trim()
+ if (!slackUserId) return null
+ if (expectedTeamId && slackTeamId !== expectedTeamId) return null
+ const slackName =
+ String(
+ req.headers['x-hawk-slack-name'] ||
+ req.headers['x-hawk-user-name'] ||
+ req.headers['x-hawk-slack-display-name'] ||
+ '',
+ ).trim() || slackUserId
+ return {
+ userKey: `${slackTeamId}:${slackUserId}`,
+ slackUserId,
+ slackTeamId,
+ slackName,
+ }
+}
+
function resolveUserKey(req) {
- if (!trustProxy) return 'local-dev'
- const user = String(req.headers['x-hawk-slack-user'] || '').trim()
- const team = String(req.headers['x-hawk-slack-team'] || '').trim()
- if (!user) return null
- if (expectedTeamId && team !== expectedTeamId) return null
- return `${team}:${user}`
+ return resolveUser(req)?.userKey ?? null
+}
+
+async function handleProgressApi(req, res, method) {
+ const user = resolveUser(req)
+ if (!user) {
+ sendJson(res, 401, { error: 'Sign in with Hawk Suite to track progress.' })
+ return
+ }
+
+ if (method === 'GET') {
+ progressDb.upsertUser(user)
+ const completed = progressDb.getCompletedLessons(user.userKey)
+ sendJson(res, 200, {
+ user: { id: user.slackUserId, name: user.slackName },
+ completed,
+ })
+ return
+ }
+
+ if (method === 'POST') {
+ let body
+ try {
+ body = await readJsonBody(req)
+ } catch (err) {
+ sendJson(res, err.status || 400, { error: err.message || 'Bad request' })
+ return
+ }
+
+ if (
+ !body ||
+ typeof body !== 'object' ||
+ typeof body.lessonSlug !== 'string' ||
+ !LESSON_SLUG_RE.test(body.lessonSlug) ||
+ typeof body.completed !== 'boolean'
+ ) {
+ sendJson(res, 400, {
+ error: 'Fields `lessonSlug` (valid slug) and `completed` (boolean) are required.',
+ })
+ return
+ }
+
+ const completed = progressDb.setLessonCompleted(user, body.lessonSlug, body.completed)
+ sendJson(res, 200, {
+ user: { id: user.slackUserId, name: user.slackName },
+ completed,
+ })
+ return
+ }
+
+ res.writeHead(405, { Allow: 'GET, POST', 'Content-Type': 'text/plain; charset=utf-8' })
+ res.end('Method Not Allowed')
}
async function handleRunApi(req, res, isMaze) {
@@ -243,6 +325,11 @@ const server = http.createServer((req, res) => {
return
}
+ if (pathname === '/api/progress') {
+ void handleProgressApi(req, res, method)
+ return
+ }
+
if (pathname === '/api/run' || pathname === '/api/run/maze') {
if (method !== 'POST') {
res.writeHead(405, { Allow: 'POST', 'Content-Type': 'text/plain; charset=utf-8' })
@@ -314,6 +401,9 @@ server.listen(port, host, () => {
for (const signal of ['SIGINT', 'SIGTERM']) {
process.on(signal, () => {
- server.close(() => process.exit(0))
+ server.close(() => {
+ progressDb.close()
+ process.exit(0)
+ })
})
}
diff --git a/server/progress-db.mjs b/server/progress-db.mjs
new file mode 100644
index 0000000..7700669
--- /dev/null
+++ b/server/progress-db.mjs
@@ -0,0 +1,86 @@
+import { mkdirSync } from 'node:fs'
+import path from 'node:path'
+import { DatabaseSync } from 'node:sqlite'
+
+export function openProgressDb(dbPath) {
+ if (dbPath !== ':memory:') {
+ mkdirSync(path.dirname(dbPath), { recursive: true })
+ }
+
+ const db = new DatabaseSync(dbPath)
+ db.exec(`
+ PRAGMA journal_mode = WAL;
+ PRAGMA foreign_keys = ON;
+ PRAGMA busy_timeout = 5000;
+
+ CREATE TABLE IF NOT EXISTS users (
+ user_key TEXT PRIMARY KEY,
+ slack_user_id TEXT NOT NULL,
+ slack_team_id TEXT NOT NULL,
+ slack_name TEXT NOT NULL,
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
+ );
+
+ CREATE TABLE IF NOT EXISTS lesson_completions (
+ user_key TEXT NOT NULL REFERENCES users(user_key) ON DELETE CASCADE,
+ lesson_slug TEXT NOT NULL,
+ completed_at TEXT NOT NULL DEFAULT (datetime('now')),
+ PRIMARY KEY (user_key, lesson_slug)
+ );
+ `)
+
+ const upsertUserStmt = db.prepare(`
+ INSERT INTO users (user_key, slack_user_id, slack_team_id, slack_name, updated_at)
+ VALUES (?, ?, ?, ?, datetime('now'))
+ ON CONFLICT(user_key) DO UPDATE SET
+ slack_name = excluded.slack_name,
+ updated_at = datetime('now')
+ `)
+
+ const listCompletedStmt = db.prepare(`
+ SELECT lesson_slug, completed_at
+ FROM lesson_completions
+ WHERE user_key = ?
+ ORDER BY completed_at ASC
+ `)
+
+ const markCompleteStmt = db.prepare(`
+ INSERT INTO lesson_completions (user_key, lesson_slug, completed_at)
+ VALUES (?, ?, datetime('now'))
+ ON CONFLICT(user_key, lesson_slug) DO NOTHING
+ `)
+
+ const unmarkCompleteStmt = db.prepare(`
+ DELETE FROM lesson_completions
+ WHERE user_key = ? AND lesson_slug = ?
+ `)
+
+ return {
+ upsertUser({ userKey, slackUserId, slackTeamId, slackName }) {
+ upsertUserStmt.run(userKey, slackUserId, slackTeamId, slackName)
+ },
+
+ getCompletedLessons(userKey) {
+ const rows = listCompletedStmt.all(userKey)
+ const completed = {}
+ for (const row of rows) {
+ completed[row.lesson_slug] = row.completed_at
+ }
+ return completed
+ },
+
+ setLessonCompleted(user, lessonSlug, completed) {
+ upsertUserStmt.run(user.userKey, user.slackUserId, user.slackTeamId, user.slackName)
+ if (completed) {
+ markCompleteStmt.run(user.userKey, lessonSlug)
+ } else {
+ unmarkCompleteStmt.run(user.userKey, lessonSlug)
+ }
+ return this.getCompletedLessons(user.userKey)
+ },
+
+ close() {
+ db.close()
+ },
+ }
+}
diff --git a/server/test_progress.mjs b/server/test_progress.mjs
new file mode 100644
index 0000000..231c105
--- /dev/null
+++ b/server/test_progress.mjs
@@ -0,0 +1,67 @@
+import assert from 'node:assert/strict'
+import { mkdtempSync, rmSync } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import test from 'node:test'
+import { openProgressDb } from './progress-db.mjs'
+
+test('records and toggles lesson completions per user', () => {
+ const db = openProgressDb(':memory:')
+ try {
+ const alice = {
+ userKey: 'T2713:U001',
+ slackUserId: 'U001',
+ slackTeamId: 'T2713',
+ slackName: 'Alice',
+ }
+ const bob = {
+ userKey: 'T2713:U002',
+ slackUserId: 'U002',
+ slackTeamId: 'T2713',
+ slackName: 'Bob',
+ }
+
+ assert.deepEqual(db.getCompletedLessons(alice.userKey), {})
+
+ const afterFirst = db.setLessonCompleted(alice, '01-flowcharts', true)
+ assert.ok(afterFirst['01-flowcharts'])
+ assert.deepEqual(db.getCompletedLessons(bob.userKey), {})
+
+ // Marking the same lesson complete twice keeps the original timestamp.
+ const firstTs = afterFirst['01-flowcharts']
+ const afterDup = db.setLessonCompleted(alice, '01-flowcharts', true)
+ assert.equal(afterDup['01-flowcharts'], firstTs)
+
+ // Completing a second lesson and unmarking the first.
+ db.setLessonCompleted(alice, '02-conditionals', true)
+ const afterUnmark = db.setLessonCompleted(alice, '01-flowcharts', false)
+ assert.equal(afterUnmark['01-flowcharts'], undefined)
+ assert.ok(afterUnmark['02-conditionals'])
+ } finally {
+ db.close()
+ }
+})
+
+test('persists completions across reopen on disk', () => {
+ const tmpDir = mkdtempSync(path.join(os.tmpdir(), 'hawk-learn-progress-'))
+ const dbPath = path.join(tmpDir, 'progress.db')
+ const user = {
+ userKey: 'T2713:U009',
+ slackUserId: 'U009',
+ slackTeamId: 'T2713',
+ slackName: 'Maya',
+ }
+
+ try {
+ const db1 = openProgressDb(dbPath)
+ db1.setLessonCompleted(user, '06-hello-world', true)
+ db1.close()
+
+ const db2 = openProgressDb(dbPath)
+ const completed = db2.getCompletedLessons(user.userKey)
+ assert.ok(completed['06-hello-world'])
+ db2.close()
+ } finally {
+ rmSync(tmpDir, { recursive: true, force: true })
+ }
+})
diff --git a/site/src/App.tsx b/site/src/App.tsx
index ad5364f..4afdd1b 100644
--- a/site/src/App.tsx
+++ b/site/src/App.tsx
@@ -1,28 +1,48 @@
import { HashRouter, Route, Routes } from 'react-router-dom'
import { AppSidebar } from './components/AppSidebar'
import { SidebarInset, SidebarProvider, SidebarTrigger } from '@/components/ui/sidebar'
+import { ProgressProvider, useProgress } from '@/lib/progress'
import { LessonIndex } from './routes/LessonIndex'
import { LessonView } from './routes/LessonView'
+function HeaderProgress() {
+ const { user, completedCount, totalLessons, loading } = useProgress()
+ if (loading || !user) return null
+ return (
+
+ {config.targetSlots?.includes('yes') && config.targetSlots?.includes('no')
+ ? 'Drag a block into YES or NO (or click + YES / + NO):'
+ : 'Drag a block into the flowchart (or click + to add):'}
+
@@ -10,20 +13,44 @@ export function LessonIndex() {
Learn the fundamentals of programming, one short lesson at a time. Every lesson is
hands-on — build and run things right in the browser.
+ {user && (
+