Build iOS Apps
OpenAI v0.1.2
Use Build iOS Apps to design App Intents and App Shortcuts, build or refactor SwiftUI UI, render SwiftUI previews in the Codex in-app browser, adopt modern iOS patterns such as Liquid Glass, audit runtime performance, capture ETTrace profiles, investigate memory leaks, and debug apps on simulators with XcodeBuildMCP-backed workflows.
Language: English · Automatically detected from descriptions.
Package details
Publisher declarations from the archived package. These are separate from our research and the live service's terms.
- Package license
- MIT
- Package author
- OpenAI
- Keywords
- ios, swift, swiftui, app-intents, shortcuts, siri, spotlight, xcode, performance, debugging, previews
Declared capabilities
- Interactive
- Read
- Write
Package observed Sep 30, 2026.
Files & skills
File archives
Skill instructions
ios-app-intents4.5 KB
--- name: ios-app-intents description: Design App Intents, app entities, and App Shortcuts for iOS system surfaces. Use when exposing app actions or content to Shortcuts, Siri, Spotlight, widgets, or controls. --- # iOS App Intents ## Overview Expose the smallest useful action and entity surface to the system. Start with the verbs and objects people would actually want outside the app, then implement a narrow App Intents layer that can deep-link or hand off cleanly into the main app when needed. Read these references as needed: - `references/first-pass-checklist.md` for choosing the first intent and entity surface - `references/example-patterns.md` for concrete example shapes to copy and adapt - `references/code-templates.md` for generalized App Intents code templates - `references/system-surfaces.md` for how to think about Shortcuts, Siri, Spotlight, widgets, and other system entry points ## Core workflow ### 1) Start with actions, not screens - Identify the 1-3 highest-value actions that should work outside the app UI. - Prefer verbs like compose, open, find, filter, continue, inspect, or start. - Do not mirror the entire app navigation tree as intents. ### 2) Define a small entity surface - Add `AppEntity` types only for the objects the system needs to understand or route. - Keep the entity shape narrower than the app's persistence model. - Add `EntityQuery` or other query types only where disambiguation or suggestions are genuinely useful. ### 3) Decide whether the action completes in place or opens the app - Use non-opening intents for actions that can complete directly from the system surface. - Use `openAppWhenRun` or open-style intents when the user should land in a specific in-app workflow. - When the app must react inside the main scene, add one clear runtime handoff path instead of scattering ad hoc routing logic. - If the action can work in both modes, consider shipping both an inline version and an open-app version rather than forcing one compromise. ### 4) Make the actions discoverable - Add `AppShortcutsProvider` entries for the first set of high-value intents. - Choose titles, phrases, and symbols that make sense in Shortcuts, Siri, and Spotlight. - Keep shortcut phrases direct and task-oriented. - Reuse the same action model for widgets and controls when a widget configuration or intent-driven control already needs the same parameters. ### 5) Validate the runtime handoff - Build the app and confirm the intents target compiles cleanly. - Verify the app opens or routes to the expected place when an intent runs. - Summarize which actions are now exposed, which entities back them, and how the app handles invocation. ## Strong defaults - Prefer a dedicated intents target or module for the system-facing layer. - Keep intent types thin; business logic should stay in app services or domain models. - Keep app entities small and display-friendly. - Use `AppEnum` for fixed app choices such as tabs, modes, or visibility levels before reaching for a full entity type. - Prefer one predictable app-intent routing surface in the main app scene or root router. - Treat App Intents as system integration infrastructure, not only as a Shortcuts feature. ## Anti-patterns - Exposing every screen or tab as its own intent without a real user value. - Mirroring the entire model graph as `AppEntity` types. - Hiding runtime handoff in global side effects with no clear app entry path. - Adding App Shortcuts with vague phrases or generic titles. - Treating the first App Intents pass as a broad taxonomy project instead of a small useful release. ## Notes - Apple documentation to use as primary references: - `https://developer.apple.com/documentation/appintents/making-actions-and-content-discoverable-and-widely-available` - `https://developer.apple.com/documentation/appintents/creating-your-first-app-intent` - `https://developer.apple.com/documentation/appintents/adopting-app-intents-to-support-system-experiences` - In addition to the links above, use web search to consult current Apple Developer documentation when App Intents APIs or platform behavior may have changed. - A good first pass often includes one open-app intent, one action intent, one or two entity types, and a small `AppShortcutsProvider`. - Good example families to cover are: - open a destination or editor in the app - perform a lightweight action inline without opening the app - choose from a fixed enum such as a tab or mode - resolve one or more entities through `EntityQuery` - power widget configuration or controls from the same entity surface
Referenced files: 5
ios-debugger-agent2.58 KB
--- name: ios-debugger-agent description: Build, run, and debug iOS apps on Simulator with XcodeBuildMCP. Use when launching an app, inspecting simulator UI or logs, or diagnosing runtime behavior. --- # iOS Debugger Agent ## Overview Use XcodeBuildMCP to build and run the current project scheme on a booted iOS simulator, interact with the UI, and capture logs. Prefer the MCP tools for simulator control, logs, and view inspection. ## Core Workflow Follow this sequence unless the user asks for a narrower action. ### 1) Discover the booted simulator - Call `mcp__XcodeBuildMCP__list_sims` and select the simulator with state `Booted`. - If none are booted, ask the user to boot one (do not boot automatically unless asked). ### 2) Set session defaults - Call `mcp__XcodeBuildMCP__session-set-defaults` with: - `projectPath` or `workspacePath` (whichever the repo uses) - `scheme` for the current app - `simulatorId` from the booted device - Optional: `configuration: "Debug"`, `useLatestOS: true` ### 3) Build + run (when requested) - Call `mcp__XcodeBuildMCP__build_run_sim`. - **If the build fails**, check the error output and retry (optionally with `preferXcodebuild: true`) or escalate to the user before attempting any UI interaction. - **After a successful build**, verify the app launched by calling `mcp__XcodeBuildMCP__describe_ui` or `mcp__XcodeBuildMCP__screenshot` before proceeding to UI interaction. - If the app is already built and only launch is requested, use `mcp__XcodeBuildMCP__launch_app_sim`. - If bundle id is unknown: 1) `mcp__XcodeBuildMCP__get_sim_app_path` 2) `mcp__XcodeBuildMCP__get_app_bundle_id` ## UI Interaction & Debugging Use these when asked to inspect or interact with the running app. - **Describe UI**: `mcp__XcodeBuildMCP__describe_ui` before tapping or swiping. - **Tap**: `mcp__XcodeBuildMCP__tap` (prefer `id` or `label`; use coordinates only if needed). - **Type**: `mcp__XcodeBuildMCP__type_text` after focusing a field. - **Gestures**: `mcp__XcodeBuildMCP__gesture` for common scrolls and edge swipes. - **Screenshot**: `mcp__XcodeBuildMCP__screenshot` for visual confirmation. ## Logs & Console Output - Start logs: `mcp__XcodeBuildMCP__start_sim_log_cap` with the app bundle id. - Stop logs: `mcp__XcodeBuildMCP__stop_sim_log_cap` and summarize important lines. - For console output, set `captureConsole: true` and relaunch if required. ## Troubleshooting - If build fails, ask whether to retry with `preferXcodebuild: true`. - If the wrong app launches, confirm the scheme and bundle id. - If UI elements are not hittable, re-run `describe_ui` after layout changes.
Referenced files: 1
ios-ettrace-performance8.63 KB
---
name: ios-ettrace-performance
description: Capture and interpret iOS Simulator ETTrace profiles. Use when profiling launch or runtime latency, comparing traces, or finding CPU-heavy stacks.
---
# iOS ETTrace Performance
Use this skill to capture a focused, symbolicated ETTrace profile from an iOS simulator app. Pair it with `../ios-debugger-agent/SKILL.md` when the task also needs simulator build, install, launch, UI driving, logs, or screenshots.
## Core Workflow
1. Pick one focused flow and write down the expected start and stop points.
2. Build the exact simulator app that will be installed and profiled.
3. Temporarily link ETTrace into that app target for simulator/debug profiling.
4. Collect UUID-matched dSYMs for the app executable and embedded dynamic frameworks.
5. Capture one launch or runtime trace.
6. Preserve the processed flamegraph JSON immediately after the run.
7. Analyze only the processed JSON and report the flow, artifacts, hotspots, and caveats.
Avoid broad "use the app for a while" captures. One trace should correspond to one user-visible flow.
## Setup
Use a writable run folder for each profiling session:
```bash
if [ -z "${RUN_DIR:-}" ]; then
RUN_DIR="$(mktemp -d "${TMPDIR:-/tmp}/codex-ios-ettrace.XXXXXX")"
fi
mkdir -p "$RUN_DIR"
```
Install the ETTrace runner CLI if it is not already available:
```bash
brew install emergetools/homebrew-tap/ettrace
```
`ettrace` is the host-side macOS runner. The app must also link an `ETTrace.xcframework` for the iOS Simulator architecture.
This workflow is validated for ETTrace v1.1.0 processed `output_<thread>.json` files with top-level `nodes`.
## Link ETTrace Into The App
Wire ETTrace into the exact app target being profiled. Keep the integration in a clearly temporary patch and remove it when the profiling task is done unless the user explicitly asks to keep it.
Preferred options:
- Reuse an existing simulator-compatible `ETTrace.xcframework` if the repo already vendors one.
- If none exists, build a simulator-only copy into `RUN_DIR` from the upstream ETTrace package.
- Link the framework directly into the app target, not only into tests, resources, data files, or a nested launcher target.
- Confirm launch logs print `Starting ETTrace`.
- Profile only one ETTrace-instrumented simulator app at a time because simulator mode listens on a fixed localhost port.
Build a simulator framework when needed:
```bash
ETTRACE_TAG="${ETTRACE_TAG:-v1.1.0}" # Override to match the installed runner when Homebrew updates.
ETTRACE_SRC="$RUN_DIR/ETTrace-src"
if [ ! -d "$ETTRACE_SRC" ]; then
git clone --depth 1 --branch "$ETTRACE_TAG" https://github.com/EmergeTools/ETTrace "$ETTRACE_SRC"
fi
rm -rf "$RUN_DIR/ETTrace-iphonesimulator.xcarchive" "$RUN_DIR/ETTrace.xcframework"
pushd "$ETTRACE_SRC" >/dev/null
xcodebuild archive \
-scheme ETTrace \
-archivePath "$RUN_DIR/ETTrace-iphonesimulator.xcarchive" \
-sdk iphonesimulator \
-destination 'generic/platform=iOS Simulator' \
BUILD_LIBRARY_FOR_DISTRIBUTION=YES \
INSTALL_PATH='Library/Frameworks' \
SKIP_INSTALL=NO \
CLANG_CXX_LANGUAGE_STANDARD=c++17
xcodebuild -create-xcframework \
-framework "$RUN_DIR/ETTrace-iphonesimulator.xcarchive/Products/Library/Frameworks/ETTrace.framework" \
-output "$RUN_DIR/ETTrace.xcframework"
popd >/dev/null
```
For Bazel apps, a temporary import usually looks like:
```python
load("@rules_apple//apple:apple.bzl", "apple_dynamic_xcframework_import")
package(default_visibility = ["//visibility:public"])
apple_dynamic_xcframework_import(
name = "ETTrace",
xcframework_imports = glob(["ETTrace.xcframework/**"]),
)
```
For Xcode projects, temporarily add the simulator `ETTrace.xcframework` to the app target's Link Binary With Libraries / Embed Frameworks phases for the debug simulator build you are profiling, then remove that wiring after profiling.
## Symbolication Gate
Do not draw conclusions from an unsymbolicated flamegraph. Before every capture, prepare a dSYM folder that includes the app dSYM and any embedded first-party dynamic framework dSYMs.
Collect dSYMs after the final build that produced the installed app:
```bash
SKILL_DIR="<absolute path to this loaded skill folder>"
APP="<path-to-built-simulator-App.app>"
DSYMS="$RUN_DIR/dsyms"
"$SKILL_DIR/scripts/collect_ios_dsyms.sh" \
--app "$APP" \
--out-dir "$DSYMS" \
--search-root "$(dirname "$APP")" \
--search-root "$PWD" \
--extra-dsym "$RUN_DIR/ETTrace-iphonesimulator.xcarchive/dSYMs/ETTrace.framework.dSYM"
```
Add `--require-framework <FrameworkName>` for app-owned dynamic frameworks that must symbolicate; use `--require-all-frameworks` only when every embedded framework is app-owned or expected to have symbols. If the helper reports a missing required app or framework dSYM, rebuild the exact simulator app with dSYM generation before tracing, or add the build output directory that contains those dSYMs as another `--search-root`.
Verify important UUIDs before tracing when the report looks suspicious:
```bash
dwarfdump --uuid "$APP/$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$APP/Info.plist")"
find "$DSYMS" -maxdepth 1 -type d -name '*.dSYM' -print -exec dwarfdump --uuid {} \;
```
After ETTrace exits, read its symbolication summary. Treat meaningful first-party "have library but no symbol" lines as a failed trace unless they are tiny noise. Unsymbolicated system-framework or ETTrace internal buckets are usually acceptable.
## Capture
For launch traces:
```bash
cd "$RUN_DIR"
CAPTURE_MARKER="$RUN_DIR/.ettrace-capture-start"
: > "$CAPTURE_MARKER"
find "$RUN_DIR" -maxdepth 1 \( -name 'output.json' -o -name 'output_*.json' \) -delete
ettrace --simulator --launch --verbose --dsyms "$DSYMS"
```
Use `--launch` only when measuring startup or first render. The first launch connection can force quit the app; relaunch from the simulator home screen rather than Xcode if prompted. For first-launch-after-install traces, temporarily set `ETTraceRunAtStartup=YES` in the app Info.plist, then run `ettrace --simulator` and launch from the home screen.
For runtime flow traces:
```bash
cd "$RUN_DIR"
CAPTURE_MARKER="$RUN_DIR/.ettrace-capture-start"
: > "$CAPTURE_MARKER"
find "$RUN_DIR" -maxdepth 1 \( -name 'output.json' -o -name 'output_*.json' \) -delete
ettrace --simulator --verbose --dsyms "$DSYMS"
```
Start from a stable screen, start ETTrace, perform exactly one focused flow, wait until visible work is complete, then stop the runner. For wider attribution, add `--multi-thread`; otherwise start with the main thread.
In Codex, run `ettrace` with a TTY and answer prompts with `write_stdin`. Without a TTY, the runner can exit without a useful trace.
## Preserve Outputs
The next ETTrace run can overwrite processed flamegraph files, so preserve fresh `output_<thread-id>.json` files immediately. Do not analyze a saved `output.json`; ETTrace also serves a viewer route with that name, and raw `emerge-output/output.json` files are not the processed flamegraph artifacts this workflow expects.
```bash
PRESERVED_DIR="$(mktemp -d "$RUN_DIR/run-$(date +%Y%m%d-%H%M%S).XXXXXX")"
: > "$PRESERVED_DIR/summary.txt"
if [ ! -e "$CAPTURE_MARKER" ]; then
echo "error: capture marker missing; start a fresh ETTrace capture before preserving outputs" >&2
exit 1
fi
find "$RUN_DIR" -maxdepth 1 -name 'output_*.json' -newer "$CAPTURE_MARKER" -print | while IFS= read -r json; do
preserved="$PRESERVED_DIR/${json##*/}"
cp "$json" "$preserved"
{
echo "## ${preserved##*/}"
python3 "$SKILL_DIR/scripts/analyze_flamegraph_json.py" "$preserved"
} >> "$PRESERVED_DIR/summary.txt"
done
if [ ! -s "$PRESERVED_DIR/summary.txt" ]; then
echo "error: no fresh processed ETTrace output JSON found in $RUN_DIR" >&2
exit 1
fi
```
Analyze only processed `output_*.json` files in `RUN_DIR`. Ignore `output.json` and raw `emerge-output/output.json` files unless debugging ETTrace itself. If the analyzer rejects the JSON shape, capture again with the Homebrew ETTrace runner and matching app-side `ETTrace.xcframework` tag instead of trying to interpret the rejected file.
## Read The Profile
Start from `run-*/summary.txt`, then inspect processed JSON directly if needed.
Report:
- exact flow, app build, simulator model/runtime, and run count
- processed flamegraph JSON paths
- top active leaves and inclusive first-party stacks with sample weights or percentages
- whether symbols were complete for app-owned binaries
- caveats such as first-run setup, simulator-only cost, network variance, or low sample count
- before/after deltas only when the same flow was captured with comparable setup
## Cleanup
Remove temporary ETTrace app wiring when profiling is complete unless the user asked to keep it. Keep or discard run artifacts based on the active task.
Referenced files: 3
ios-memgraph-leaks3.86 KB
---
name: ios-memgraph-leaks
description: Capture and inspect iOS leaks and memgraphs. Use when debugging leaked objects, retain cycles, memory growth, or before/after leak evidence.
---
# iOS Memgraph Leaks
Use this skill to prove iOS leaks from a live simulator process or an existing `.memgraph`. Pair it with `../ios-debugger-agent/SKILL.md` when the task also needs simulator build, install, launch, UI driving, logs, or screenshots.
## Core Workflow
1. Build, launch, and drive the exact flow that should release objects.
2. Capture a memgraph from the running simulator process with `scripts/capture_sim_memgraph.sh`.
3. Summarize leaks with `scripts/summarize_memgraph_leaks.py`.
4. For each app-owned leaked type, inspect ownership with `leaks --traceTree=<address> <file.memgraph>` and grouped leak evidence.
5. Make the smallest root-cause patch, then recapture the same flow on the same simulator when possible.
6. Report proof: before/after leak counts, disappeared root types, remaining leaks, memgraph paths, and test/build results.
Do not claim a leak fix from a smaller memgraph alone. A credible fix explains the ownership path that kept the object alive and shows that the same path or type disappears after the patch.
## Capture
Prefer capturing from the simulator already used for the reproduction. Resolve the simulator UDID and app bundle identifier, then capture the running app:
```bash
SKILL_DIR="<absolute path to this loaded skill folder>"
SIM="<simulator-udid>"
BUNDLE_ID="<app.bundle.identifier>"
MEMGRAPH_DIR="$(mktemp -d "${TMPDIR:-/tmp}/codex-ios-memgraph.XXXXXX")"
"$SKILL_DIR/scripts/capture_sim_memgraph.sh" \
--udid "$SIM" \
--bundle-id "$BUNDLE_ID" \
--out-dir "$MEMGRAPH_DIR"
```
Do not derive `SKILL_DIR` from the target app repo's `pwd`; installed plugins usually live outside the app being debugged. Store captures in a run-specific temp or user-chosen folder, not under `SKILL_DIR`.
If the process cannot be found, confirm the bundle identifier and use `xcrun simctl spawn "$SIM" launchctl list` to inspect running labels.
## Summarize
Summarize an existing memgraph:
```bash
"$SKILL_DIR/scripts/summarize_memgraph_leaks.py" \
/path/to/app.memgraph \
--trace-limit 5 \
--out /path/to/leak-summary.md
```
Use `--trace-limit` sparingly. Trace trees are useful root-cause evidence, but large memgraphs can produce noisy output. If a trace tree says `Found 0 roots referencing`, treat it as an unreachable/self-retained leak candidate and use the summary's grouped leak tree or `leaks --groupByType <file.memgraph>` to identify the retained fields and payload chain.
## Root Cause Rules
- Identify the first app-owned leaked type in the leak output or trace.
- Determine the intended lifetime: process, session, account, view, request, or task.
- Treat lazy or deferred allocation as a scope reduction, not a leak fix, unless the original eager allocation itself violated the intended lifetime.
- Prove retain-cycle claims with either a `traceTree` ownership path or an isolated reproduction.
- For unreachable/self-cycle leaks, `traceTree` may have no root path; use `leaks --groupByType` plus source verification to find the self-retaining edge.
- Do not claim success just because total leak count went down; prove the specific type or path disappeared.
- Separate real root-cause branches from candidate/noise branches.
- Prefer deleting the retaining edge over adding broad cleanup code.
## Report
A useful leak report includes:
- the exact flow and simulator/app build
- the memgraph and summary paths
- app-owned leaked types and counts
- at least one ownership path, or grouped leak tree evidence when the object is unreachable from roots
- the smallest proposed or applied retaining-edge fix
- before/after evidence when a fix was made
If the memgraph shows only framework/runtime noise, say that and recommend the next narrower capture rather than inventing an app leak.
Referenced files: 3
ios-simulator-browser3.17 KB
---
name: ios-simulator-browser
description: Mirror an iOS Simulator into the Codex in-app browser and render SwiftUI previews from importable Swift packages in that simulator with hot reload. Use when a user wants to watch or interact with an iOS app in the browser, see a SwiftUI preview outside Xcode Canvas, iterate live on a preview, or capture browser-visible simulator proof.
---
# iOS Simulator Browser
## Browser Workflow
1. Obtain an explicit Simulator UDID from the existing iOS build/run workflow or from `xcrun simctl list devices available`.
2. Start `serve-sim` in a long-running terminal pinned to that simulator. Clean up any tracked stale helper for this simulator before starting, and install a trap so the helper is cleaned up when this terminal exits:
```bash
SIM="<simulator-udid>"
cleanup_serve_sim() {
npx --yes serve-sim@latest --kill "$SIM" >/dev/null 2>&1 || true
}
trap cleanup_serve_sim EXIT INT TERM HUP
cleanup_serve_sim
npx --yes serve-sim@latest "$SIM"
```
3. Open the exact local preview URL printed by `serve-sim` in the Codex in-app browser.
4. Verify that a real frame is rendering before reporting success. A loaded page alone is not proof that the simulator stream is healthy.
- Keep the terminal alive while the browser mirror is in use. When finished, stop the terminal and wait for it to exit so the trap runs.
- If the terminal disappeared or did not exit cleanly, run `npx --yes serve-sim@latest --kill "$SIM"` before starting another mirror for that simulator.
- Never run an unscoped `serve-sim --kill`; another thread may own a different simulator mirror.
## SwiftUI Preview Workflow
Use the bundled launcher when the requested previews live in an importable Swift package. Point it at the package manifest and select the target whose previews should be displayed. It generates a disposable host project outside the user's source tree, installs and launches that host in Simulator, and watches the package for edits.
```bash
node <skill-root>/scripts/swiftui-preview-browser.mjs \
/absolute/path/to/Package.swift \
--package-target "<target>" \
--device "<simulator-udid>"
```
- Watch mode is enabled by default. On a Swift package source edit, the launcher rebuilds a generated dylib and hot-swaps it into the running host without relaunching the app.
- The generated host shows every preview variant discovered in the selected Swift Package target with in-simulator page controls. To show a subset instead, pass `--preview-filter <regex[, ...]>`; it matches display names and code identifiers such as `StatusRowView_Previews`.
- Once the launcher prints the selected Simulator UDID, start `serve-sim` for that same UDID and open its printed URL in the in-app browser.
## Support Boundary
- Support Swift Package-backed `PreviewProvider` and `#Preview` declarations through the generated host.
- Do not edit the user's `.xcodeproj`, `.xcworkspace`, `Package.swift`, schemes, or build settings to force preview support.
## Proof
For browser or preview QA, capture a browser screenshot showing the simulator frame. For hot reload QA, also report the launcher's `hot reloaded package preview ... in pid ...` output and show the changed frame after editing.
Referenced files: 6
swiftui-liquid-glass3.66 KB
---
name: swiftui-liquid-glass
description: Implement and review iOS 26+ SwiftUI Liquid Glass UI. Use when adopting Liquid Glass or checking its correctness, performance, and design fit.
---
# SwiftUI Liquid Glass
## Overview
Use this skill to build or review SwiftUI features that fully align with the iOS 26+ Liquid Glass API. Prioritize native APIs (`glassEffect`, `GlassEffectContainer`, glass button styles) and Apple design guidance. Keep usage consistent, interactive where needed, and performance aware.
## Workflow Decision Tree
Choose the path that matches the request:
### 1) Review an existing feature
- Inspect where Liquid Glass should be used and where it should not.
- Verify correct modifier order, shape usage, and container placement.
- Check for iOS 26+ availability handling and sensible fallbacks.
### 2) Improve a feature using Liquid Glass
- Identify target components for glass treatment (surfaces, chips, buttons, cards).
- Refactor to use `GlassEffectContainer` where multiple glass elements appear.
- Introduce interactive glass only for tappable or focusable elements.
### 3) Implement a new feature using Liquid Glass
- Design the glass surfaces and interactions first (shape, prominence, grouping).
- Add glass modifiers after layout/appearance modifiers.
- Add morphing transitions only when the view hierarchy changes with animation.
## Core Guidelines
- Prefer native Liquid Glass APIs over custom blurs.
- Use `GlassEffectContainer` when multiple glass elements coexist.
- Apply `.glassEffect(...)` after layout and visual modifiers.
- Use `.interactive()` for elements that respond to touch/pointer.
- Keep shapes consistent across related elements for a cohesive look.
- Gate with `#available(iOS 26, *)` and provide a non-glass fallback.
## Review Checklist
- **Availability**: `#available(iOS 26, *)` present with fallback UI.
- **Composition**: Multiple glass views wrapped in `GlassEffectContainer`.
- **Modifier order**: `glassEffect` applied after layout/appearance modifiers.
- **Interactivity**: `interactive()` only where user interaction exists.
- **Transitions**: `glassEffectID` used with `@Namespace` for morphing.
- **Consistency**: Shapes, tinting, and spacing align across the feature.
## Implementation Checklist
- Define target elements and desired glass prominence.
- Wrap grouped glass elements in `GlassEffectContainer` and tune spacing.
- Use `.glassEffect(.regular.tint(...).interactive(), in: .rect(cornerRadius: ...))` as needed.
- Use `.buttonStyle(.glass)` / `.buttonStyle(.glassProminent)` for actions.
- Add morphing transitions with `glassEffectID` when hierarchy changes.
- Provide fallback materials and visuals for earlier iOS versions.
## Quick Snippets
Use these patterns directly and tailor shapes/tints/spacing.
```swift
if #available(iOS 26, *) {
Text("Hello")
.padding()
.glassEffect(.regular.interactive(), in: .rect(cornerRadius: 16))
} else {
Text("Hello")
.padding()
.background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 16))
}
```
```swift
GlassEffectContainer(spacing: 24) {
HStack(spacing: 24) {
Image(systemName: "scribble.variable")
.frame(width: 72, height: 72)
.font(.system(size: 32))
.glassEffect()
Image(systemName: "eraser.fill")
.frame(width: 72, height: 72)
.font(.system(size: 32))
.glassEffect()
}
}
```
```swift
Button("Confirm") { }
.buttonStyle(.glassProminent)
```
## Resources
- Reference guide: `references/liquid-glass.md`
- Prefer Apple docs for up-to-date API details, and use web search to consult current Apple Developer documentation in addition to the references above.
Referenced files: 2
swiftui-performance-audit4.89 KB
--- name: swiftui-performance-audit description: Audit SwiftUI runtime performance from code first. Use when diagnosing slow rendering, janky scrolling, expensive updates, or profiling needs. --- # SwiftUI Performance Audit ## Quick start Use this skill to diagnose SwiftUI performance issues from code first, then request profiling evidence when code review alone cannot explain the symptoms. ## Workflow 1. Classify the symptom: slow rendering, janky scrolling, high CPU, memory growth, hangs, or excessive view updates. 2. If code is available, start with a code-first review using `references/code-smells.md`. 3. If code is not available, ask for the smallest useful slice: target view, data flow, reproduction steps, and deployment target. 4. If code review is inconclusive or runtime evidence is required, guide the user through profiling with `references/profiling-intake.md`. 5. Summarize likely causes, evidence, remediation, and validation steps using `references/report-template.md`. ## 1. Intake Collect: - Target view or feature code. - Symptoms and exact reproduction steps. - Data flow: `@State`, `@Binding`, environment dependencies, and observable models. - Whether the issue shows up on device or simulator, and whether it was observed in Debug or Release. Ask the user to classify the issue if possible: - CPU spike or battery drain - Janky scrolling or dropped frames - High memory or image pressure - Hangs or unresponsive interactions - Excessive or unexpectedly broad view updates For the full profiling intake checklist, read `references/profiling-intake.md`. ## 2. Code-First Review Focus on: - Invalidation storms from broad observation or environment reads. - Unstable identity in lists and `ForEach`. - Heavy derived work in `body` or view builders. - Layout thrash from complex hierarchies, `GeometryReader`, or preference chains. - Large image decode or resize work on the main thread. - Animation or transition work applied too broadly. Use `references/code-smells.md` for the detailed smell catalog and fix guidance. Provide: - Likely root causes with code references. - Suggested fixes and refactors. - If needed, a minimal repro or instrumentation suggestion. ## 3. Guide the User to Profile If code review does not explain the issue, ask for runtime evidence: - A trace export or screenshots of the SwiftUI timeline and Time Profiler call tree. - Device/OS/build configuration. - The exact interaction being profiled. - Before/after metrics if the user is comparing a change. Use `references/profiling-intake.md` for the exact checklist and collection steps. ## 4. Analyze and Diagnose - Map the evidence to the most likely category: invalidation, identity churn, layout thrash, main-thread work, image cost, or animation cost. - Prioritize problems by impact, not by how easy they are to explain. - Distinguish code-level suspicion from trace-backed evidence. - Call out when profiling is still insufficient and what additional evidence would reduce uncertainty. ## 5. Remediate Apply targeted fixes: - Narrow state scope and reduce broad observation fan-out. - Stabilize identities for `ForEach` and lists. - Move heavy work out of `body` into derived state updated from inputs, model-layer precomputation, memoized helpers, or background preprocessing. Use `@State` only for view-owned state, not as an ad hoc cache for arbitrary computation. - Use `equatable()` only when equality is cheaper than recomputing the subtree and the inputs are truly value-semantic. - Downsample images before rendering. - Reduce layout complexity or use fixed sizing where possible. Use `references/code-smells.md` for examples, Observation-specific fan-out guidance, and remediation patterns. ## 6. Verify Ask the user to re-run the same capture and compare with baseline metrics. Summarize the delta (CPU, frame drops, memory peak) if provided. ## Outputs Provide: - A short metrics table (before/after if available). - Top issues (ordered by impact). - Proposed fixes with estimated effort. Use `references/report-template.md` when formatting the final audit. ## References - Profiling intake and collection checklist: `references/profiling-intake.md` - Common code smells and remediation patterns: `references/code-smells.md` - Audit output template: `references/report-template.md` - Add Apple documentation and WWDC resources under `references/` as they are supplied by the user. - Optimizing SwiftUI performance with Instruments: `references/optimizing-swiftui-performance-instruments.md` - Understanding and improving SwiftUI performance: `references/understanding-improving-swiftui-performance.md` - Understanding hangs in your app: `references/understanding-hangs-in-your-app.md` - Demystify SwiftUI performance (WWDC23): `references/demystify-swiftui-performance-wwdc23.md` - In addition to the references above, use web search to consult current Apple Developer documentation when Instruments workflows or SwiftUI performance guidance may have changed.
Referenced files: 8
swiftui-ui-patterns7.16 KB
---
name: swiftui-ui-patterns
description: Build and refactor SwiftUI UI with component patterns and examples. Use when shaping navigation, state, layouts, controls, or screen composition.
---
# SwiftUI UI Patterns
## Quick start
Choose a track based on your goal:
### Existing project
- Identify the feature or screen and the primary interaction model (list, detail, editor, settings, tabbed).
- Find a nearby example in the repo with `rg "TabView\("` or similar, then read the closest SwiftUI view.
- Apply local conventions: prefer SwiftUI-native state, keep state local when possible, and use environment injection for shared dependencies.
- Choose the relevant component reference from `references/components-index.md` and follow its guidance.
- If the interaction reveals secondary content by dragging or scrolling the primary content away, read `references/scroll-reveal.md` before implementing gestures manually.
- Build the view with small, focused subviews and SwiftUI-native data flow.
### New project scaffolding
- Start with `references/app-wiring.md` to wire TabView + NavigationStack + sheets.
- Add a minimal `AppTab` and `RouterPath` based on the provided skeletons.
- Choose the next component reference based on the UI you need first (TabView, NavigationStack, Sheets).
- Expand the route and sheet enums as new screens are added.
## General rules to follow
- Use modern SwiftUI state (`@State`, `@Binding`, `@Observable`, `@Environment`) and avoid unnecessary view models.
- If the deployment target includes iOS 16 or earlier and cannot use the Observation API introduced in iOS 17, fall back to `ObservableObject` with `@StateObject` for root ownership, `@ObservedObject` for injected observation, and `@EnvironmentObject` only for truly shared app-level state.
- Prefer composition; keep views small and focused.
- Use async/await with `.task` and explicit loading/error states. For restart, cancellation, and debouncing guidance, read `references/async-state.md`.
- Keep shared app services in `@Environment`, but prefer explicit initializer injection for feature-local dependencies and models. For root wiring patterns, read `references/app-wiring.md`.
- Prefer the newest SwiftUI API that fits the deployment target and call out the minimum OS whenever a pattern depends on it.
- Maintain existing legacy patterns only when editing legacy files.
- Follow the project's formatter and style guide.
- **Sheets**: Prefer `.sheet(item:)` over `.sheet(isPresented:)` when state represents a selected model. Avoid `if let` inside a sheet body. Sheets should own their actions and call `dismiss()` internally instead of forwarding `onCancel`/`onConfirm` closures.
- **Scroll-driven reveals**: Prefer deriving a normalized progress value from scroll offset and driving the visual state from that single source of truth. Avoid parallel gesture state machines unless scroll alone cannot express the interaction.
## State ownership summary
Use the narrowest state tool that matches the ownership model:
| Scenario | Preferred pattern |
| --- | --- |
| Local UI state owned by one view | `@State` |
| Child mutates parent-owned value state | `@Binding` |
| Root-owned reference model on iOS 17+ | `@State` with an `@Observable` type |
| Child reads or mutates an injected `@Observable` model on iOS 17+ | Pass it explicitly as a stored property |
| Shared app service or configuration | `@Environment(Type.self)` |
| Legacy reference model on iOS 16 and earlier | `@StateObject` at the root, `@ObservedObject` when injected |
Choose the ownership location first, then pick the wrapper. Do not introduce a reference model when plain value state is enough.
## Cross-cutting references
- In addition to the references below, use web search to consult current Apple Developer documentation when SwiftUI APIs, availability, or platform guidance may have changed.
- `references/navigationstack.md`: navigation ownership, per-tab history, and enum routing.
- `references/sheets.md`: centralized modal presentation and enum-driven sheets.
- `references/deeplinks.md`: URL handling and routing external links into app destinations.
- `references/app-wiring.md`: root dependency graph, environment usage, and app shell wiring.
- `references/async-state.md`: `.task`, `.task(id:)`, cancellation, debouncing, and async UI state.
- `references/previews.md`: `#Preview`, fixtures, mock environments, and isolated preview setup.
- `references/performance.md`: stable identity, observation scope, lazy containers, and render-cost guardrails.
## Anti-patterns
- Giant views that mix layout, business logic, networking, routing, and formatting in one file.
- Multiple boolean flags for mutually exclusive sheets, alerts, or navigation destinations.
- Live service calls directly inside `body`-driven code paths instead of view lifecycle hooks or injected models/services.
- Reaching for `AnyView` to work around type mismatches that should be solved with better composition.
- Defaulting every shared dependency to `@EnvironmentObject` or a global router without a clear ownership reason.
## Workflow for a new SwiftUI view
1. Define the view's state, ownership location, and minimum OS assumptions before writing UI code.
2. Identify which dependencies belong in `@Environment` and which should stay as explicit initializer inputs.
3. Sketch the view hierarchy, routing model, and presentation points; extract repeated parts into subviews. For complex navigation, read `references/navigationstack.md`, `references/sheets.md`, or `references/deeplinks.md`. **Build and verify no compiler errors before proceeding.**
4. Implement async loading with `.task` or `.task(id:)`, plus explicit loading and error states when needed. Read `references/async-state.md` when the work depends on changing inputs or cancellation.
5. Add previews for the primary and secondary states, then add accessibility labels or identifiers when the UI is interactive. Read `references/previews.md` when the view needs fixtures or injected mock dependencies.
6. Validate with a build: confirm no compiler errors, check that previews render without crashing, ensure state changes propagate correctly, and sanity-check that list identity and observation scope will not cause avoidable re-renders. Read `references/performance.md` if the screen is large, scroll-heavy, or frequently updated. For common SwiftUI compilation errors — missing `@State` annotations, ambiguous `ViewBuilder` closures, or mismatched generic types — resolve them before updating callsites. **If the build fails:** read the error message carefully, fix the identified issue, then rebuild before proceeding to the next step. If a preview crashes, isolate the offending subview, confirm its state initialisation is valid, and re-run the preview before continuing.
## Component references
Use `references/components-index.md` as the entry point. Each component reference should include:
- Intent and best-fit scenarios.
- Minimal usage pattern with local conventions.
- Pitfalls and performance notes.
- Paths to existing examples in the current repo.
## Adding a new component reference
- Create `references/<component>.md`.
- Keep it short and actionable; link to concrete files in the current repo.
- Update `references/components-index.md` with the new entry.
Referenced files: 31
swiftui-view-refactor7.7 KB
---
name: swiftui-view-refactor
description: Refactor SwiftUI view files into stable, testable structure. Use when splitting large views, tightening data flow, or cleaning Observation ownership.
---
# SwiftUI View Refactor
## Overview
Refactor SwiftUI views toward small, explicit, stable view types. Default to vanilla SwiftUI: local state in the view, shared dependencies in the environment, business logic in services/models, and view models only when the request or existing code clearly requires one.
## Core Guidelines
### 1) View ordering (top → bottom)
- Enforce this ordering unless the existing file has a stronger local convention you must preserve.
- Environment
- `private`/`public` `let`
- `@State` / other stored properties
- computed `var` (non-view)
- `init`
- `body`
- computed view builders / other view helpers
- helper / async functions
### 2) Default to MV, not MVVM
- Views should be lightweight state expressions and orchestration points, not containers for business logic.
- Favor `@State`, `@Environment`, `@Query`, `.task`, `.task(id:)`, and `onChange` before reaching for a view model.
- Inject services and shared models via `@Environment`; keep domain logic in services/models, not in the view body.
- Do not introduce a view model just to mirror local view state or wrap environment dependencies.
- If a screen is getting large, split the UI into subviews before inventing a new view model layer.
### 3) Strongly prefer dedicated subview types over computed `some View` helpers
- Flag `body` properties that are longer than roughly one screen or contain multiple logical sections.
- Prefer extracting dedicated `View` types for non-trivial sections, especially when they have state, async work, branching, or deserve their own preview.
- Keep computed `some View` helpers rare and small. Do not build an entire screen out of `private var header: some View`-style fragments.
- Pass small, explicit inputs (data, bindings, callbacks) into extracted subviews instead of handing down the entire parent state.
- If an extracted subview becomes reusable or independently meaningful, move it to its own file.
Prefer:
```swift
var body: some View {
List {
HeaderSection(title: title, subtitle: subtitle)
FilterSection(
filterOptions: filterOptions,
selectedFilter: $selectedFilter
)
ResultsSection(items: filteredItems)
FooterSection()
}
}
private struct HeaderSection: View {
let title: String
let subtitle: String
var body: some View {
VStack(alignment: .leading, spacing: 6) {
Text(title).font(.title2)
Text(subtitle).font(.subheadline)
}
}
}
private struct FilterSection: View {
let filterOptions: [FilterOption]
@Binding var selectedFilter: FilterOption
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(filterOptions, id: \.self) { option in
FilterChip(option: option, isSelected: option == selectedFilter)
.onTapGesture { selectedFilter = option }
}
}
}
}
}
```
Avoid:
```swift
var body: some View {
List {
header
filters
results
footer
}
}
private var header: some View {
VStack(alignment: .leading, spacing: 6) {
Text(title).font(.title2)
Text(subtitle).font(.subheadline)
}
}
```
### 3b) Extract actions and side effects out of `body`
- Do not keep non-trivial button actions inline in the view body.
- Do not bury business logic inside `.task`, `.onAppear`, `.onChange`, or `.refreshable`.
- Prefer calling small private methods from the view, and move real business logic into services/models.
- The body should read like UI, not like a view controller.
```swift
Button("Save", action: save)
.disabled(isSaving)
.task(id: searchText) {
await reload(for: searchText)
}
private func save() {
Task { await saveAsync() }
}
private func reload(for searchText: String) async {
guard !searchText.isEmpty else {
results = []
return
}
await searchService.search(searchText)
}
```
### 4) Keep a stable view tree (avoid top-level conditional view swapping)
- Avoid `body` or computed views that return completely different root branches via `if/else`.
- Prefer a single stable base view with conditions inside sections/modifiers (`overlay`, `opacity`, `disabled`, `toolbar`, etc.).
- Root-level branch swapping causes identity churn, broader invalidation, and extra recomputation.
Prefer:
```swift
var body: some View {
List {
documentsListContent
}
.toolbar {
if canEdit {
editToolbar
}
}
}
```
Avoid:
```swift
var documentsListView: some View {
if canEdit {
editableDocumentsList
} else {
readOnlyDocumentsList
}
}
```
### 5) View model handling (only if already present or explicitly requested)
- Treat view models as a legacy or explicit-need pattern, not the default.
- Do not introduce a view model unless the request or existing code clearly calls for one.
- If a view model exists, make it non-optional when possible.
- Pass dependencies to the view via `init`, then create the view model in the view's `init`.
- Avoid `bootstrapIfNeeded` patterns and other delayed setup workarounds.
Example (Observation-based):
```swift
@State private var viewModel: SomeViewModel
init(dependency: Dependency) {
_viewModel = State(initialValue: SomeViewModel(dependency: dependency))
}
```
### 6) Observation usage
- For `@Observable` reference types on iOS 17+, store them as `@State` in the owning view.
- Pass observables down explicitly; avoid optional state unless the UI genuinely needs it.
- If the deployment target includes iOS 16 or earlier, use `@StateObject` at the owner and `@ObservedObject` when injecting legacy observable models.
## Workflow
1. Reorder the view to match the ordering rules.
2. Remove inline actions and side effects from `body`; move business logic into services/models and keep only thin orchestration in the view.
3. Shorten long bodies by extracting dedicated subview types; avoid rebuilding the screen out of many computed `some View` helpers.
4. Ensure stable view structure: avoid top-level `if`-based branch swapping; move conditions to localized sections/modifiers.
5. If a view model exists or is explicitly required, replace optional view models with a non-optional `@State` view model initialized in `init`.
6. Confirm Observation usage: `@State` for root `@Observable` models on iOS 17+, legacy wrappers only when the deployment target requires them.
7. Keep behavior intact: do not change layout or business logic unless requested.
## Notes
- Prefer small, explicit view types over large conditional blocks and large computed `some View` properties.
- Keep computed view builders below `body` and non-view computed vars above `init`.
- A good SwiftUI refactor should make the view read top-to-bottom as data flow plus layout, not as mixed layout and imperative logic.
- For MV-first guidance and rationale, see `references/mv-patterns.md`.
- In addition to the references above, use web search to consult current Apple Developer documentation when SwiftUI APIs, Observation behavior, or platform guidance may have changed.
## Large-view handling
When a SwiftUI view file exceeds ~300 lines, split it aggressively. Extract meaningful sections into dedicated `View` types instead of hiding complexity in many computed properties. Use `private` extensions with `// MARK: -` comments for actions and helpers, but do not treat extensions as a substitute for breaking a giant screen into smaller view types. If an extracted subview is reused or independently meaningful, move it into its own file.
Referenced files: 2
Technical details
- First seen
- Sep 30, 2026 · 22:02 UTC
- Last seen
- Oct 1, 2026 · 12:00 UTC
- Collection status
- Collected
plugins~Plugin_f1b845ac33888191ac156169c58733c2
Download listing JSON