---
title: "Gate inference on scenePhase"
lesson_id: "04"
---

# Gate inference on scenePhase

- **Lesson ID:** 04
- **Goal:** Observe `scenePhase`, cancel generate when the scene is not `.active`, and resume only in the foreground.
- **Human lesson:** [04-gate-on-scene-phase.html](04-gate-on-scene-phase.html)

## Prerequisites

- Lesson 03: architecture registered and weights can load.
- SwiftUI `App` with a `WindowGroup`.

## Inputs, outputs, and artifacts

- **Inputs:** A running generate `Task` and `scenePhase` changes.
- **Outputs:** Cancel on not-active. No Metal work while inactive or backgrounded.
- **Artifacts:** Two progressive Mermaid diagrams and a language-tagged Swift sketch.

## Agent build steps

1. Link Apple's [`scenePhase`](https://developer.apple.com/documentation/swiftui/scenephase) documentation. Do not invent a WWDC session.
2. Treat not `.active` as a stop. Include `.inactive`.
3. Hold one generate `Task`. Cancel it on phase change. Check `Task.isCancelled` in the token loop.
4. Mark generate API names as sketches to verify in `MLXLMCommon`.
5. Resume policy: do not auto-start Metal on return to `.active`. User action, saved prompt, new Task.
6. Test on a real device. Link [Stream tokens and measure speed](../on-device-streaming-metrics/) and [The agent harness (and how to improve it)](../agent-harness-improve-loop/).

## Constraints

Keep the language simple, friendly, and literal. No quizzes, no em dashes, no invented WWDC sessions. Brand Edge FDE only. The only Apple video-or-doc link in this lesson is `developer.apple.com` for `scenePhase`.

## Key concepts

- `scenePhase` is `.active`, `.inactive`, or `.background`.
- Cancel generate when the phase is not `.active`. Inactive already lost the GPU path.
- Hold one generate `Task`. Check cancellation inside the token loop.
- Resume only in the foreground, from a saved prompt, after a user action.

## Takeaways

- Never leave Metal work running when the scene is inactive or backgrounded.
- Do not auto-resume generate on the way back to `.active`.
- Prove the gate on a real device with Home or lock during a long run.

## Acceptance checks

- Gate is `scenePhase != .active`, not only `.background`.
- Resume policy is explicit. Swift is language-tagged.
- `scenePhase` docs link is on developer.apple.com. No invented WWDC.
- [ ] Proceed to [lesson 05 brief](05-production-checklist.llms.md).
