diff --git a/.cursor-plugin/marketplace.json b/.cursor-plugin/marketplace.json index 2035d5d..5b9f867 100644 --- a/.cursor-plugin/marketplace.json +++ b/.cursor-plugin/marketplace.json @@ -6,7 +6,7 @@ }, "metadata": { "description": "Professional Cursor plugins with APEX workflow, SOLID principles, and expert development agents for Next.js, Laravel, Swift, Tailwind CSS, and more", - "version": "0.1.13" + "version": "0.1.14" }, "plugins": [ { @@ -145,7 +145,7 @@ "name": "fuse-design", "source": ".cursor-plugin/plugins/fuse-design", "description": "Design Director for websites, web apps, iOS, and Android. Generates HTML/CSS directly (Gemini Design MCP, Magic/21st.dev, and shadcn MCP are optional). iOS/Android produce tokens + a device-framed mockup + a handoff spec, never SwiftUI/Compose. Design method, design system tokens, motion, UX copy, and a deterministic design-review gate. Anti-AI-Slop, WCAG 2.2.", - "version": "2.2.13", + "version": "2.2.14", "author": { "name": "Fusengine", "email": "hello@fusengine.ch" @@ -534,8 +534,8 @@ { "name": "fuse-swift-apple-expert", "source": ".cursor-plugin/plugins/fuse-swift-apple-expert", - "description": "Expert Swift 6.2 + SwiftUI for iOS 26, macOS 26, iPadOS 26, watchOS 26, visionOS 26, tvOS 26 with Liquid Glass, @Observable, actors, SwiftData inheritance", - "version": "1.1.24", + "description": "Expert Swift 6.4.2 + SwiftUI (Xcode 27.2) for iOS 27.2, macOS 27.2, iPadOS 27.2, watchOS 27.2, visionOS 27.2, tvOS 27.2 with Liquid Glass, @Observable, actors, SwiftData inheritance", + "version": "1.1.25", "author": { "name": "Fusengine", "email": "hello@fusengine.ch" diff --git a/.cursor-plugin/plugins/fuse-design/.cursor-plugin/plugin.json b/.cursor-plugin/plugins/fuse-design/.cursor-plugin/plugin.json index 65b9335..f293a23 100644 --- a/.cursor-plugin/plugins/fuse-design/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugins/fuse-design/.cursor-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "fuse-design", - "version": "2.2.13", + "version": "2.2.14", "description": "Design Director for websites, web apps, iOS, and Android. Generates HTML/CSS directly (Gemini Design MCP, Magic/21st.dev, and shadcn MCP are optional). iOS/Android produce tokens + a device-framed mockup + a handoff spec, never SwiftUI/Compose. Design method, design system tokens, motion, UX copy, and a deterministic design-review gate. Anti-AI-Slop, WCAG 2.2.", "author": { "name": "Fusengine", diff --git a/.cursor-plugin/plugins/fuse-design/README.md b/.cursor-plugin/plugins/fuse-design/README.md index 0ae3afc..f51713e 100644 --- a/.cursor-plugin/plugins/fuse-design/README.md +++ b/.cursor-plugin/plugins/fuse-design/README.md @@ -9,10 +9,16 @@ Compose code: they produce tokens, an HTML device-framed mockup, and a handoff s **Zero tolerance for generic "AI slop" aesthetics** — see the anti-slop clusters in `skills/design-method/SKILL.md`. -Ported from the Claude Code plugin `fuse-design` v2.2.7 (source folder `plugins/design-expert/`). +Ported from the Claude Code plugin `fuse-design` v2.3.0 (source folder `plugins/design-expert/`). The plugin name is deliberately identical across both ecosystems so cross-plugin references (`fuse-design:`, and the agent's own `fuse-ai-pilot:fuse-browser-usage`) keep resolving. +Port note 2026-11-14: the source change `fd4f8c5e..a6a25857` was ported for `design-ios` only: six new +references (`app-icons`, `app-store-assets`, `apple-design-tools`, `bars-menus-scroll`, +`generative-ai`, `system-surfaces`) plus the updated `SKILL.md`, `dynamic-type`, `ipados-iphone-duo`, +`macos` and `watch-tv-vision` references, all byte-identical to the source, and the README's +`design-ios` row now reads "Apple-platform mockup + handoff". + ## Contents | Component | Count | Cursor discovery | @@ -48,7 +54,7 @@ All design work starts in `skills/design-method/SKILL.md`: | `design-system` | OKLCH tokens, typography, spacing, motion profile, the canonical forbidden-fonts list, the mechanical contrast-check step | | `design-web` | Marketing sites and landing pages — inspiration browsing (FULL/PAGE scope only), component generation, premium layout patterns, hard layout-discipline rules | | `design-webapp` | Dashboards, auth, settings, onboarding, data tables, command palettes — density and state coverage over marketing polish | -| `design-ios` | iOS mockup + handoff — Dynamic Type, semantic colors, device viewports, Liquid Glass, SwiftUI-ready spec | +| `design-ios` | Apple-platform mockup + handoff — Dynamic Type, semantic colors, device viewports, Liquid Glass, touch on Mac, bars/menus/scroll, system surfaces, app icons, App Store assets, generative AI, Apple design tools, SwiftUI-ready spec | | `design-android` | Android mockup + handoff — Material 3 Expressive type/shape/color scales, window size classes, Compose-ready spec | | `design-motion` | Motion gated by the `MOTION_INTENSITY` dial — most animation ideas die at the gate; mandatory hover/focus/disabled states and `prefers-reduced-motion` regardless | | `ux-copy` | Voice/tone, CTAs, error messages, empty states, the copy self-audit (em-dash crutch check, production-tell catalogue) | diff --git a/.cursor-plugin/plugins/fuse-design/skills/design-ios/SKILL.md b/.cursor-plugin/plugins/fuse-design/skills/design-ios/SKILL.md index 1744fe0..2b39279 100644 --- a/.cursor-plugin/plugins/fuse-design/skills/design-ios/SKILL.md +++ b/.cursor-plugin/plugins/fuse-design/skills/design-ios/SKILL.md @@ -2,7 +2,7 @@ name: design-ios description: "Use when designing a screen or flow for any Apple platform — iPhone (incl. iPhone Duo), iPad, Mac, Apple Watch, Apple TV or Vision Pro — deliverable is a device/window-framed HTML mockup and a handoff spec, never SwiftUI code." when-to-use: "Designing an iOS, iPadOS, macOS, watchOS, tvOS or visionOS screen or flow — the deliverable is a framed HTML mockup and a handoff spec for swift-expert or an Apple-platform developer to implement, not working SwiftUI." -keywords: ios, ipados, macos, watchos, tvos, visionos, iphone-duo, hig, dynamic-type, liquid-glass, contrast, handoff, mockup +keywords: ios, ipados, macos, watchos, tvos, visionos, iphone-duo, hig, dynamic-type, liquid-glass, contrast, handoff, mockup, app-icon, app-store, screenshots, sf-symbols, generative-ai priority: critical related: design-method, design-system, design-review --- @@ -32,8 +32,13 @@ After `design-system` tokens exist. |---|---| | iPhone | steps below + `references/dynamic-type.md` | | iPad, resizable window, iPhone Duo | + `references/ipados-iphone-duo.md` | -| Mac | + `references/macos.md`, `references/type-scales-other.md` | +| Mac (incl. touch display) | + `references/macos.md`, `references/type-scales-other.md` | | Apple Watch, Apple TV, Vision Pro | + `references/watch-tv-vision.md`, `references/type-scales-other.md` | +| Any bar, sidebar, menu, scroll view | + `references/bars-menus-scroll.md` | +| Live Activity, widget | + `references/system-surfaces.md` | +| AI / generated content, Writing Tools, Genmoji, Image Playground | + `references/generative-ai.md` | +| App icon | + `references/app-icons.md`, `references/apple-design-tools.md` | +| App Store screenshots, previews, product page, creative assets | + `references/app-store-assets.md` | ### Steps 1. **Map tokens to platform roles.** Typography → the platform's HIG text styles by name @@ -62,14 +67,22 @@ After `design-system` tokens exist. first on iPad. Source: https://developer.apple.com/design/human-interface-guidelines/sidebars. 7. **Platform pass** — apply the platform reference picked above (macOS desktop tinting - only under the graphite accent; tvOS 60/80 pt safe area and focus growth; visionOS - ornaments for controls only; watchOS ≤3 glyph buttons per row; iPhone Duo controls on - the side and the fold reserved region). + only under the graphite accent, touch secondary: same control size, larger tap + targets, touch-revealed states for hover controls; tvOS 60/80 pt safe area and focus + growth; visionOS ornaments for controls only; watchOS ≤3 glyph buttons per row; iPhone + Duo controls on the side and the fold reserved region). Bars and menus follow + `bars-menus-scroll.md`: tab bar for navigation only, no manual toolbar overflow menu, + one prominent action, menu icons for all items of a group or none. 8. **Look at the render** — screenshot each canvas (light, dark, AX5) and Read the PNGs before calling the mockup done; fix what you see, then hand off to `design-review`. 9. **Write the handoff spec** per `handoff-swiftui.md`: named tokens only, text styles by name, semantic colors, sizing (fixed/hug/fill), all states (disabled/pressed/focused, plus pointer style on macOS and focus on tvOS), spacing in pt, canvas sources. +10. **Distribution assets (when asked)** — app icon as a layered Icon Composer file in + all appearances (`app-icons.md`); App Store screenshots at accepted pixel sizes, no + alpha, required classes plus iPhone Duo; previews, product page, custom product pages + and creative assets per `app-store-assets.md`. Name tool versions from + `apple-design-tools.md`, never from memory. ### Failure Handling - Screenshot tooling unavailable → say so in the report (`visual check: not run`) and @@ -97,5 +110,11 @@ After `design-system` tokens exist. | `references/macos.md` | Window frame, fixed type, desktop tinting, pointer, sidebars — HIG | | `references/ipados-iphone-duo.md` | iPadOS + iPhone Duo poses, reserved regions, vertical controls — HIG | | `references/watch-tv-vision.md` | watchOS, tvOS, visionOS basics — HIG | +| `references/bars-menus-scroll.md` | Tab bars, sidebars, toolbars, menus, scroll edge effects, Look to Scroll — HIG | +| `references/system-surfaces.md` | Live Activities (limited width), widgets (Apple HomeView), design principles, emphasized weights — HIG | +| `references/generative-ai.md` | Generative AI rules (refine/revert, generation feedback); Writing Tools / Genmoji / Image Playground — HIG | +| `references/app-icons.md` | App icon format (Icon Composer layered preferred), appearances, specs — HIG | +| `references/apple-design-tools.md` | SF Symbols 27 (announced as SF Symbols 8 beta), Icon Composer 2, Pass Designer, UI kits, bezels — Design Resources | +| `references/app-store-assets.md` | Screenshots (incl. iPhone Duo), previews, product pages, creative assets, guideline 2.3.14 | | `references/mockup.md` | Device-frame HTML/CSS technique (safe areas, viewport-fit) | | `references/handoff-swiftui.md` | SwiftUI-ready handoff spec format | diff --git a/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/app-icons.md b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/app-icons.md new file mode 100644 index 0000000..51c7e6e --- /dev/null +++ b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/app-icons.md @@ -0,0 +1,70 @@ +--- +name: app-icons +description: "Apple app icon rules from the HIG App icons page (format options 2026-10-28) — layered Icon Composer file preferred over a bitmap, appearances default/dark/clear/tinted, per-platform layout sizes, layer rules." +when-to-use: "Designing or specifying an app icon (or its alternate icons) for iOS, iPadOS, macOS, watchOS, tvOS or visionOS, including the App Store marketing icon." +keywords: app-icon, icon-composer, liquid-glass, layers, dark, tinted, clear, appearances +priority: high +related: ../SKILL.md, apple-design-tools.md, app-store-assets.md, liquid-glass.md +--- + +# App Icons + +Source: https://developer.apple.com/design/human-interface-guidelines/app-icons — change +log 2026-10-28 "Added guidance for app icon format options" (also 2026-06-08 "refined for +Liquid Glass"). Read 2026-11-13 via the page's JSON endpoint. + +## Format — layered Icon Composer file is the stated preference +- iOS, iPadOS, macOS and watchOS accept "nonlayered bitmap images (such as PNG) or + layered Icon Composer files". The HIG: "Provide your icon in the Icon Composer format + for more flexibility and control." +- A bitmap is segmented by the system into two layers; Liquid Glass is applied only to + large, simple foreground shapes, **not** to text and thin lines. To control which + elements get Liquid Glass, ship a layered Icon Composer file. +- tvOS and visionOS icons are built as an image stack in Xcode (tvOS 2–5 layers with + parallax; visionOS background + one or two layers, 3D). + +## Layers +- Background layer + one or more foreground layers; the system adds specular highlights, + refraction, translucency, shadows — **don't paint them in** (no baked highlights, drop + shadows, bevels, blurs, glows). +- Clearly defined edges (no feathering); vary opacity across foreground layers for depth; + prefer vector (SVG/PDF) layers, PNG for mesh gradients and raster art; outline text. +- Icon Composer backgrounds: solid colors or gradients; an imported background must be + full-bleed and opaque. +- Provide **square, unmasked** layers (iOS/iPadOS/macOS rounded rectangle, watchOS and + visionOS circle are applied by the system; tvOS rectangular). Pre-masked layers break + specular highlights. +- Text only when essential; prefer illustrations to photos; never replicate UI or a + screenshot. + +## Appearances +- iOS, iPadOS, macOS: people choose **default, dark, clear or tinted** Home Screen icons; + the system generates the variants you don't provide. Spec table lists six: + default, dark, clear light, clear dark, tinted light, tinted dark. +- Keep the same core features in every appearance; base the dark icon on the light one; + dark is more subdued, clear and tinted even more so. +- Alternate app icons (iOS/iPadOS) need their own dark, clear and tinted variants and go + through App Review. +- Icon Composer annotates **Default, Dark and Mono** rendering modes in one file + (https://developer.apple.com/icon-composer/). + +## Specifications (HIG table) + +| Platform | Layout size | Masked shape | Style | Appearances | +|---|---|---|---|---| +| iOS, iPadOS, macOS | 1024×1024 px | rounded rectangle | layered | default, dark, clear light/dark, tinted light/dark | +| tvOS | 800×480 px | rounded rectangle (landscape) | layered (parallax) | n/a | +| visionOS | 1024×1024 px | circle | layered (3D) | n/a | +| watchOS | 1088×1088 px | circle | layered | n/a | + +Color spaces: sRGB (color), Gray Gamma 2.2 (grayscale). The system scales smaller +variants automatically. + +## Marketing icon +Icon Composer "provides the option to export a flattened version of your icon for +marketing and communication needs" (https://developer.apple.com/icon-composer/) — use that +export for App Store and marketing surfaces (`app-store-assets.md`), never a re-drawn copy. + +## Mockup deliverable +Show the icon in all four appearances at Home Screen size, on a light and a dark +wallpaper, and state the source file format (layered Icon Composer file vs bitmap) in the spec. diff --git a/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/app-store-assets.md b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/app-store-assets.md new file mode 100644 index 0000000..4f606a9 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/app-store-assets.md @@ -0,0 +1,120 @@ +--- +name: app-store-assets +description: "Design side of App Store distribution (state 2026-11-13) — screenshot specifications incl. iPhone Duo, app previews, product page, custom product pages (up to 70), creative assets and Asset Library (2026-10-05), App Review 2.3.x incl. 2.3.14 creative assets (2026-10-16), marketing icon." +when-to-use: "Designing App Store screenshots, app previews, product page headers, search-result or In-App Event creative assets, or custom product pages for an Apple-platform app." +keywords: app-store, screenshots, app-previews, product-page, custom-product-pages, creative-assets, asset-library, iphone-duo, review-guidelines +priority: high +related: ../SKILL.md, app-icons.md, apple-design-tools.md, ipados-iphone-duo.md +--- + +# App Store Assets — Design Side + +All facts read 2026-11-13. Submission mechanics (binaries, signing, review flow) belong +to swift-expert's `build-distribution` skill, not here. Pixel values below are **asset +sizes in pixels**, not mockup canvas sizes in points (`viewports.md`). + +## Screenshots +Source: https://developer.apple.com/help/app-store-connect/reference/app-information/screenshot-specifications +- 1 to 10 screenshots per device size; `.jpeg`, `.jpg` or `.png`; **"Images can't + include alpha channels or transparencies."** Must follow the App Review Guidelines. +- **Required sizes**: iPhone with Dynamic Island (**medium display**) — at least one; + **iPad 13-inch** — at least one, if the app runs on iPadOS. Mac (16:10), Apple TV, + Apple Vision Pro and Apple Watch are required for apps on those platforms. +- One UI across sizes → provide the highest required resolution; App Store Connect + scales down. Otherwise upload per size and per localization. + +| Class | Accepted sizes (portrait; landscape is the swap) | +|---|---| +| iPhone Duo outer display | 1398 × 2034 | +| iPhone Duo inner display | 2007 × 2853 | +| iPhone, Dynamic Island, large | 1260 × 2736 · 1290 × 2796 · 1320 × 2868 | +| iPhone, Dynamic Island, medium (required) | 1179 × 2556 · 1206 × 2622 | +| iPad 13" (required for iPad apps) | 2064 × 2752 · 2048 × 2732 | +| Mac (16:10) | 1280 × 800 · 1440 × 900 · 2560 × 1600 · 2880 × 1800 (landscape) | +| Apple TV | 1920 × 1080 · 3840 × 2160 | +| Apple Vision Pro | 3840 × 2160 | +| Apple Watch (one size, same across localizations) | 422 × 514 (Ultra 4/3) · 410 × 502 · 416 × 496 · 396 × 484 · 368 × 448 · 312 × 390 | + +Older iPhone/iPad classes and their fallbacks are listed on the page — read them there. + +**iPhone Duo screenshots.** The spec page: "Starting in April 2027, screenshots will be +required for any app using the iOS 27.1 SDK or later." The news post of 2026-10-05 +(https://developer.apple.com/news/?id=kkphp5qo) words it: "Starting April 2027, any apps +or games submitted will need to include screenshots for iPhone Duo." Submitting them +adds a "made for iPhone Duo" badge to the product page. Plan both displays; the two +Apple sources differ on scope, so quote both until Apple aligns them. + +## App previews +Source: https://developer.apple.com/help/app-store-connect/reference/app-information/app-preview-specifications +- Optional; up to **3** per device size and language (iOS, macOS, tvOS, visionOS). + 15–30 s, ≤500 MB, ≤30 fps, H.264 or ProRes 422 (HQ); poster frame defaults to 5 s. +- Shown **before** screenshots; a different aspect ratio than the screenshots moves it to + "A Closer Look". macOS/tvOS/visionOS landscape only. +- iPhone Duo previews use the standard iPhone 19.5:9 dimensions (886 × 1920 portrait). +- Guideline 2.3.4: "previews may only use video screen captures of the app itself" + (narration and overlays allowed). Autoplay is muted — the first seconds must work + without sound (https://developer.apple.com/app-store/product-page/). + +## Product page — https://developer.apple.com/app-store/product-page/ +- Name ≤30 characters; subtitle ≤30 characters (no generic claims). +- Up to 10 screenshots; with no preview, the **first one to three** appear in search + results — they carry the essence. One screenshot in Dark Mode if supported. +- Guideline 2.3.3: screenshots show the app in use, not only title art, login or splash; + overlays allowed to explain input. + +## Custom product pages — https://developer.apple.com/app-store/custom-product-pages/ +- Up to **70** additional product pages (iPhone, iPad), each varying screenshots, + promotional text and/or app previews; unique URL, usable in Apple Ads, can appear in + search for assigned keywords; optional deep link (iOS/iPadOS 18+); reviewed + independently of an app update. Design them as a set from one visual system. + +## Creative assets and Asset Library (2026-10-05) +Sources: https://developer.apple.com/news/?id=ljpl7kyn · +https://developer.apple.com/app-store/asset-best-practices/ · +https://developer.apple.com/help/app-store-connect/reference/app-information/creative-assets-specifications · +https://developer.apple.com/help/app-store-connect/manage-app-information/manage-your-app-store-assets +- New image/video assets beyond in-use visuals: **product page header**, **search + results**, **In-App Event** cards; shown in iOS 27 / iPadOS 27 and later. +- Image specs (creative-assets spec page, Last-Modified 2026-11-12, read 2026-11-13; no + alpha or transparency): + +| Placement | Ratio | Resolution (px) | Art safe area (px) | Formats | +|---|---|---|---|---| +| Product page header | 21:9 | 3840 × 1646 | 1646 × 661 at x 1097, y 493 | jpeg, jpg, png | +| Search results | 3:2 | 1920 × 1280 → 3840 × 2560 | max 2168 × 1030 at x 836, y 765 | jpeg, jpg, png | +| Universal asset (header + search) | 16:9 | 5244 × 2950 | 1402 × 962 at x 1921, y 660 | png only | +| In-App Event card | 16:9 | 1920 × 1080 → 3840 × 2160 | — | jpeg, jpg, png (≤500 MB) | +| In-App Event details page | 9:16 | 1080 × 1920 → 2160 × 3840 | — | jpeg, jpg, png (≤500 MB) | + +- Composition: key characters and talent inside the **Art Safe Area**; atmospheric art + across the full canvas (**Auxiliary Art Area**). Start from Apple's Figma / Photoshop / + Pixelmator / Sketch templates. +- Video (header, search, events): same ratios and resolutions, 30 or 60 fps, 5–30 s, + `.mov`/`.m4v`/`.mp4`; muted by default (cannot be unmuted in search), looping. +- Best practices: one clear idea per header; search asset makes the purpose obvious; no + pricing, discounts, URLs, copyright symbols, other platforms' logos, Apple + recognitions or unverifiable awards; 4+ imagery; videos loop seamlessly and work muted; + a universal asset can serve both header and search results. +- **Asset Library** in App Store Connect stores creative assets, screenshots and previews + and lets creative assets be approved ahead of use; a **preview tool** shows them on the + product page and in search, including Dark Mode, devices and orientations. + +## App Review guidelines on metadata — https://developer.apple.com/app-store/review/guidelines/ (last updated 2026-10-16) +- **2.3.14 (new 2026-10-16, https://developer.apple.com/news/?id=92th7e5i)**: creative + assets "must pertain to your app's content and functionality or overarching brand, + follow standard metadata guidelines, and be appropriate for all audiences. They should + not include inappropriate content, references to other apps with an intent to mislead, + unverifiable product claims, or specific or discounted pricing information." +- 2.3.7: no prices or irrelevant terms in names, subtitles, screenshots, previews. +- 2.3.8: icons, screenshots, previews meet **4+**; keep app name and icons consistent + across sizes and alternate icons. +- 2.3.9: secure rights to all materials; show **fictional account data**, never a real + person's. + +## Marketing icon +Export the flattened icon from Icon Composer (`app-icons.md`); 2.3.8 asks that app name +and icons (small, large, Apple Watch, alternate) stay similar to avoid confusion. + +## Deliverable +A screenshot set per required class (plus iPhone Duo outer + inner), opaque PNG/JPEG at +an accepted size, light and dark variants where relevant, text localized, no alpha. diff --git a/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/apple-design-tools.md b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/apple-design-tools.md new file mode 100644 index 0000000..c8a54ab --- /dev/null +++ b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/apple-design-tools.md @@ -0,0 +1,57 @@ +--- +name: apple-design-tools +description: "Current official Apple design tools and kits (state 2026-11-14) — SF Symbols 27 (announced as SF Symbols 8 beta), Icon Composer 2, Pass Designer, UI kits per platform, product bezels — with the version each one targets." +when-to-use: "Choosing which Apple UI kit, symbol library, icon tool or bezel to build a mockup, icon or marketing frame with, or checking that a cited version is current." +keywords: sf-symbols, icon-composer, pass-designer, ui-kit, figma, sketch, bezels, design-resources +priority: high +related: ../SKILL.md, app-icons.md, app-store-assets.md +--- + +# Apple Design Tools and Kits + +All facts read 2026-11-13. Dated entries come from +https://developer.apple.com/design/whats-new/ (page meta 2026-11-06). Versions change +each WWDC — re-read these pages before quoting a version in a deliverable. + +## Tools + +| Tool | Current state | Use in this skill | Source | +|---|---|---|---| +| **SF Symbols 27** (announced at WWDC26 as "SF Symbols 8 beta", 2026-06-08) | "over 7,000 symbols", 9 weights × 3 scales; new symbols for iOS/iPadOS/macOS/watchOS/tvOS/visionOS 27; Enhanced Search (semantic); Draw On/Off presets; Annotation (guide points for custom-symbol Draw); Variable Rendering (Variable Color, Variable Draw); 4 rendering modes + optional gradient rendering. Download `SF-Symbols-27.dmg`, requires macOS Sonoma or later. | Name symbols by their SF Symbols name in the spec; prefer them over custom icons in tab bars, sidebars, toolbars. | https://developer.apple.com/sf-symbols/ · https://developer.apple.com/design/resources/ ("Download SF Symbols 27", read 2026-11-14) · What's new 2026-06-08 ("SF Symbols 8 beta") | +| **Icon Composer 2** (beta at WWDC26, 2026-06-08) | Layered Liquid Glass icons from one design for iPhone, iPad, Mac, Apple Watch; Refraction (per-layer strength); new specular highlights (inside/outside/automatic, vertical light angle); updated annotation; Default / Dark / Mono rendering modes in one file; Xcode integration; flattened export "for marketing and communication needs". Requires macOS Tahoe 26.4 or later. | App icon production — see `app-icons.md`. | https://developer.apple.com/icon-composer/ · What's new 2026-06-08 ("Icon Composer 2 beta") | +| **Pass Designer** (new, WWDC26, 2026-06-08; beta) | Build Wallet passes from Apple or own templates; live preview for iPhone and Apple Watch using the system renderer; colors (background/foreground/label), adaptable layouts, standard fields, validation, semantic tags with backward-compatible output. Beta requires macOS 27 or later. | Wallet pass mockups: design images (logo, background, strip) in a design tool, finish and preview in Pass Designer instead of hand-drawing a pass frame. | https://developer.apple.com/pass-designer/ · HIG /wallet updated 2026-06-08 | +| **Parallax Previewer** | Preview parallax effects for tvOS and visionOS images/icons. | tvOS/visionOS layered icons. | https://developer.apple.com/design/resources/ | + +## UI kits (Design Resources page, read 2026-11-13) + +| Platform | Kit version | Formats | +|---|---|---| +| iOS + iPadOS | **27** (Figma kit 2026-09-17: components, system colors, app icons) | Figma, Sketch; App Icon Template | +| macOS | **27** (Figma kit 2026-09-17) | Figma, Sketch | +| watchOS | **26** | Figma, Sketch | +| tvOS | **18** | UI kit, Sketch design templates, production templates | +| visionOS | **26** (also a legacy visionOS 2 kit) | Figma, Sketch (visionOS 2: Sketch) | +| Live Activities | template updated for iOS 27, with macOS components (2026-11-06) | Figma, Sketch | + +Source: https://developer.apple.com/design/resources/. A watchOS or tvOS mockup built on +a newer-numbered kit does not exist — use the listed version and say so in the spec. + +## Product bezels (marketing frames) +Current set includes iPhone Duo and iPhone 18 (added 2026-09-18), iPad mini (A20 Pro), +Apple Watch Ultra 4 and MacBook Pro PROLED XDR Display bezels (2026-11-06), plus iPhone 16/17, iPad (A16), +iPad Air (M4), iPad Pro (M5), iMac, Studio Displays, Apple TV, Watch Series 11. Use them +only for marketing frames, under Apple's Marketing Resources and Identity Guidelines +(https://developer.apple.com/app-store/marketing/guidelines/). A design mockup itself +uses the plain frame from `mockup.md`, not a photographic bezel. + +## Fonts +SF Pro (iOS, iPadOS, macOS, tvOS), SF Compact (watchOS), SF Mono, New York, plus SF +Arabic/Armenian/Georgian/Hebrew — downloads on the Design Resources page. + +Known inconsistency (2026-11-13): the Design Resources page still says Icon Composer +"Requires macOS Sequoia or later"; the Icon Composer page (Icon Composer 2) says macOS +Tahoe 26.4 or later. Quote the Icon Composer page for version 2. + +## Rule +Cite the tool and its version as read on the page above, with the read date. Never write +"latest" without a version, and never carry a version from memory. diff --git a/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/bars-menus-scroll.md b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/bars-menus-scroll.md new file mode 100644 index 0000000..15ecdae --- /dev/null +++ b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/bars-menus-scroll.md @@ -0,0 +1,75 @@ +--- +name: bars-menus-scroll +description: "HIG rules for the functional layer of an Apple-platform mockup — tab bars (navigation only, search tab), sidebars (adaptable style, icon colors, two levels), toolbars (Liquid Glass, no manual overflow, one prominent action), menus (item icons), scroll edge effects and visionOS Look to Scroll." +when-to-use: "Placing or reviewing a tab bar, sidebar, toolbar, menu or scroll view in any Apple-platform mockup or handoff spec." +keywords: tab-bars, sidebars, toolbars, menus, scroll-views, scroll-edge-effect, look-to-scroll, search-tab, liquid-glass +priority: high +related: ../SKILL.md, liquid-glass.md, macos.md, ipados-iphone-duo.md +--- + +# Bars, Menus, Scroll Views + +Read 2026-11-13 from the HIG JSON endpoints. `/slug` = +`https://developer.apple.com/design/human-interface-guidelines/`; the date after +each heading is that page's latest change-log entry. + +## Tab bars — /tab-bars (2026-06-08, terminology and art) +- **Navigation, not actions**: actions on the current view go in a toolbar. +- Keep it visible across sections (a modal may cover it); avoid overflow (the trailing + tab becomes **More** on iOS/iPadOS); never disable or hide a tab — explain an empty + section instead. +- Labels: single words where possible; SF Symbols, **filled** preferred; icons above + labels in compact, side by side in regular. Badges only for critical information. +- On colorful content, prefer a monochromatic tab bar or a well-differentiated accent. +- iOS: floats at the bottom on Liquid Glass; can **minimize** with an attached accessory + (Music MiniPlayer) on scroll; can hold a **dedicated search tab at the trailing end**. +- iPadOS: near the top, fixed or convertible to a sidebar; default customizable list of + five or fewer. Not on watchOS. +- Search as a tab — /search-fields (2026-06-08): two styles, a standard tab that opens a + search landing page, or a separate button that focuses the field and shows the keyboard. + +## Sidebars — /sidebars (2026-06-08, icon colors + adaptable style) +- **No more than two levels**; deeper → split view with a content list. Title groups + with short labels. +- **Adaptable style** (iOS/iPadOS `sidebarAdaptable`): you choose sidebar or tab bar at + launch; both include a switch button; adapts to rotation and window width. Consider a + tab bar first. +- **Icon colors**: accent color by default; on macOS they must follow the user's system + accent; fixed colors only sparingly for meaning (Mail VIP yellow). +- Extend rich content beneath the floating sidebar (horizontal scroll or background + extension effect); let people hide it, never hidden by default. + +## Toolbars — /toolbars (2025-12-16, Liquid Glass) +- Choose items deliberately; define which items overflow as width shrinks. The system adds + the overflow menu on macOS/iPadOS — **don't add one manually**, and avoid layouts that + overflow by default. A More menu only if really needed. +- **Reduce toolbar backgrounds and tinted controls**; let the content layer inform the + color, use a scroll edge effect to separate bar from content. Monochrome default over + colorful content. +- Standard components have radii **concentric** with the bar; custom ones must match. +- Titles under 15 characters, never the app name; standard Back/Close symbols, no "Back" + text; system symbols without borders. +- **One** `.prominent` primary action (Done, Submit), on the trailing side. + +## Menus — /menus (2026-06-08, menu item icons) +- Icons **sparingly and with purpose**: common actions, key features, locations, devices, + visual concepts, user content; none if no icon clearly fits. +- Standard icons for common actions (Share, Print, Search); **all items in a group get an + icon, or none**. +- iOS/iPadOS small layout (4 symbol-only items on top) for closely related actions; + medium (3 items, symbol + short label) for three frequent actions. + +## Scroll edge effects — /scroll-views (2026-06-08) +- iOS, iPadOS, macOS: separates floating elements (toolbars) from scrolling content. + Prefer the **automatic** style (more opaque behind dense top toolbars, text outside + glass controls, pinned headers); **soft** requires legibility testing; **hard** is the + other manual style. +- Only behind floating UI — not decorative, it doesn't darken like an overlay. One per + view; in iPad/Mac split views each pane may have one, kept the same height. + +## Look to Scroll (visionOS) — /scroll-views (2026-03-24) +- Scrolling by looking near the scroll view's edge; opt-in per scroll view. +- Support it in reading and browsing views; not in dense or control-heavy views; be + consistent across similar views; prefer full-width/height scroll areas or clear + boundaries; remove scroll-position effects (parallax) first. Mark which views support it + in the spec. diff --git a/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/dynamic-type.md b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/dynamic-type.md index 53dfaac..5acee9d 100644 --- a/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/dynamic-type.md +++ b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/dynamic-type.md @@ -39,6 +39,10 @@ Fetched 2026-10-12. Other platforms: `type-scales-other.md`. | Caption 1 | Regular | 12 | 16 | Semibold | | Caption 2 | Regular | 11 | 13 | Semibold | +The **Emphasized** column is the weight the system applies with the bold trait (HIG +change 2025-12-16 "Added emphasized weights to the Dynamic Type style specifications for +each platform", re-checked 2026-11-13). Spec emphasis as "`Body`, emphasized". + ## AX5 (largest accessibility size) — stress-test at this size | Style | Size (pt) | Leading (pt) | diff --git a/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/generative-ai.md b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/generative-ai.md new file mode 100644 index 0000000..38e94d2 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/generative-ai.md @@ -0,0 +1,59 @@ +--- +name: generative-ai +description: "HIG Generative AI rules for mocking up AI features (update 2026-06-08: refine/revert results, specific feedback during generation, model choice) and what Apple publishes on Writing Tools, Genmoji and Image Playground surfaces." +when-to-use: "Mocking up any screen that generates or transforms content with a model, or that hosts Writing Tools, Genmoji or Image Playground." +keywords: generative-ai, apple-intelligence, writing-tools, genmoji, image-playground, foundation-models, transparency, feedback +priority: medium +related: ../SKILL.md, system-surfaces.md, handoff-swiftui.md +--- + +# Generative AI Surfaces + +Source: https://developer.apple.com/design/human-interface-guidelines/generative-ai — +change log 2026-06-08 "Added guidance for letting people refine results and providing +feedback during content generation, and updated guidance for choosing a model type" +(page new 2025-06-09). Read 2026-11-13 via its JSON endpoint. No platform-specific +considerations on any Apple platform. + +## What the mockup must show +| HIG rule | Mockup obligation | +|---|---| +| Communicate where your app uses AI; never pass AI output off as human | A visible AI indicator or label on the feature and its output | +| Set clear expectations of capabilities and limits | Onboarding hint or example inputs for open-ended prompts | +| Keep people in control; let them dismiss new content | Dismiss/discard affordance on every generated result | +| **Refine or revert results, and acknowledge corrections** (2026-06-08) | Controls such as **Edit, Undo, Retry, Adjust next to the generated content**, plus a confirmation state when a correction takes effect | +| **Specific, reassuring feedback during generation** (2026-06-08) | A progress state with a concrete message ("Summarizing key themes from your notes"), never a bare "Processing…" | +| Factor processing time into the design | Loading / partial-result state for slow generation | +| Help people improve blocked or undesirable requests | A blocked-request state that coaches (Image Playground: "Unable to use that description") with example requests | +| Consider offering alternate versions | A choice of meaningfully different results where it fits | +| Get permission before irreversible tasks; don't automate destructive actions | A confirmation step before any destructive or hard-to-undo action | +| Ask permission before using personal data; disclose use | Permission and disclosure screens, with an opt-out | +| Let people share feedback on outputs | A feedback control on results | +| Raise awareness of hallucinations | A notice where output may be factually wrong | +| Great experience when AI is unavailable or declined | A non-AI path or state for the same screen | + +Model choice (on-device vs server, privacy and latency) is an implementation decision — +record the assumption in the handoff, don't design around a guess. + +## Writing Tools, Genmoji, Image Playground +- The HIG has **no dedicated pages** for these surfaces (JSON slugs `writing-tools`, + `genmoji`, `image-playground` return 404, checked 2026-11-13). They appear only as + examples: on the Generative AI page (Genmoji as an optional addition beside regular + emoji; Image Playground's blocked-request message and multiple-image choice) and on + /machine-learning ("Image Playground lets people describe an image, adjust it + visually, or remix results through quick edits"). +- Apple Intelligence "Get started" + (https://developer.apple.com/apple-intelligence/get-started/, read 2026-11-13): Writing + Tools (rewrite, proofread, summarize) work automatically in standard text views; + Genmoji work in standard text fields and are **inline images**, not text; Image + Playground provides a system experience parallel to the Image Playground app. That + page says images are generated on device, but Apple's pages disagree: the + /apple-intelligence/ overview says "Images are generated on Private Cloud Compute, so + photos are never stored or shared" and /apple-intelligence/whats-new/ says the new + model runs on Private Cloud Compute (both read 2026-11-14). Treat generation as Private + Cloud Compute and show a disclosure in the mockup (same rule as + swift-apple-expert `apple-intelligence/references/system-features.md`). +- Mockup rule: these are **system UI** — don't redraw their panels. Use standard text + views/fields in the mockup, mark where the system Writing Tools / Genmoji / Image + Playground entry points appear, and size text layouts to accept an inline Genmoji + glyph. Implementation belongs to swift-expert. diff --git a/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/ipados-iphone-duo.md b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/ipados-iphone-duo.md index 8c8e670..398e2c5 100644 --- a/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/ipados-iphone-duo.md +++ b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/ipados-iphone-duo.md @@ -55,6 +55,19 @@ designing for iPhone, so iOS rules apply. - Space-limited: navigation-focused → toolbar items overflow, tab bar stays; task-focused → minimize the tab bar, keep toolbar actions. - Use the system overflow menu; reserve the ellipsis symbol for it. + - **Asymmetry** (re-checked 2026-11-13): controls sit along one edge, so content space + is asymmetrical — use safe areas so controls (including the opposite edge's, when + two apps share the inner display) never cover content. + - Keep controls' **relative positions** as similar as possible across poses (not every + pose puts them on the side). + - Controls that belong to another content area stay **next to that area**, not moved to + the side bar. + - Text-labelled buttons stay in a horizontal bar — that is why symbols are preferred. +- The outer camera is in a corner, vertically aligned with the side controls; when the + inner camera activates, the UI moves aside. Split views expand on the inner display and + collapse to one pane on the outer display, as between regular and compact elsewhere. +- Maintain the same functionality in every pose: controls may overflow and content may + move, but stay reachable. - Full-width layouts are allowed for bar-less, non-scrolling views (Calculator) if nothing collides with the Dynamic Island or status bar. - Games: playable in every pose; prefer changing aspect ratio over letter/pillarboxing. @@ -62,3 +75,6 @@ designing for iPhone, so iOS rules apply. ## Not published — do not invent The HIG gives no point dimensions for either iPhone Duo display or the fold region. Take canvas sizes from Xcode Device Hub (`viewports.md`) and state that source in the spec. +App Store screenshot pixel sizes (outer 1398×2034, inner 2007×2853) are marketing +assets, not canvas sizes — `app-store-assets.md`. The iPhone Duo product bezel +(Design Resources, 2026-09-18) is for marketing frames only — `apple-design-tools.md`. diff --git a/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/macos.md b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/macos.md index fac5e43..e5c4069 100644 --- a/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/macos.md +++ b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/macos.md @@ -1,8 +1,8 @@ --- name: macos -description: "macOS mockup rules from the HIG — system window frame, fixed text styles (no Dynamic Type), desktop tinting under the graphite accent, pointer styles, window layout and sidebar rules." +description: "macOS mockup rules from the HIG — system window frame, fixed text styles (no Dynamic Type), desktop tinting under the graphite accent, pointer styles, touch as a secondary input (2026-10-28), window layout and sidebar rules." when-to-use: "Designing a macOS window, sidebar or toolbar mockup and its handoff spec." -keywords: macos, window, desktop-tinting, graphite, pointer, sidebar, typography +keywords: macos, window, desktop-tinting, graphite, pointer, touch, sidebar, typography priority: high related: ../SKILL.md, type-scales-other.md, semantic-colors.md, liquid-glass.md --- @@ -39,7 +39,7 @@ color doesn't drift. Show it in the mockup as a variant, not as the default. — - Sidebar icons use the accent color by default and must follow the accent the user picks; fixed colors only sparingly to carry meaning (e.g. Mail's yellow VIP). — /sidebars -## Pointer, not touch +## Pointer first - macOS communicates interactivity through **standard pointer styles** and shows a **tooltip** after hovering a button; secondary click reveals context menus. — /pointing-devices, /buttons @@ -48,9 +48,40 @@ color doesn't drift. Show it in the mockup as a variant, not as the default. — labeled as such. - Default control size 28×28 pt, minimum 20×20 pt (`touch-targets.md`). +## Touch on Mac — secondary input (HIG change 2026-10-28, read 2026-11-13) +Sources: /designing-for-macos, /gestures (macOS), /pointing-devices ("Touch support for +hidden controls") — all three carry the 2026-10-28 change-log entry. +- "In macOS, touch is secondary to keyboard and pointing device input." On a Mac with a + touch display, people "tend to use touch for brief, intentional interactions rather + than sustained work." The mockup stays a pointer-and-keyboard layout. — /gestures, + /designing-for-macos +- **Same layout, same control size** when touch is supported; "Make tap targets bigger, + not the controls themselves" (the hit area may extend past the visual bounds). Standard + controls get an optimal tap target automatically. The HIG states **no numeric Mac tap + target** — write the hit-area size in the spec as a project token. — /gestures +- **Expandable controls**: small or dense controls may show a temporary touch-sized + variant on tap (steppers, sliders, dials do it automatically). Show it as a state, not + as the default. — /gestures +- **Touch never the only way in**; conversely give touch equivalents for pointer-only + actions (shift-drag, hover menus). — /gestures +- **Hover-revealed controls**: decide which need touch (essential ones only — not + tooltips, not what a swipe already covers); a tap on their general location reveals + only the relevant ones, which hide again after use or a few seconds; keep the current + selection; put essential hidden controls in a context menu (touch and hold). Never keep + them visible permanently just for touch. Exceptions to the auto-hide: **sidebar** — a + tap on a header or row performs the same action as a click (expand/collapse, select) + and reveals only that item's controls, which stay visible until touch moves outside + the sidebar or a pointing device is used again; a tap on a hidden control's area + reveals it without activating it (it acts on the next tap). **Tabbed window** — a tap + anywhere shows the selected tab's close button until the pointer is used again. Spec + each as a "touch-revealed" state. — /pointing-devices + ## Sidebars (also iPadOS) — /sidebars - Show **no more than two levels** of hierarchy. Deeper data → a **split view with a content list between the sidebar and the detail view**, not a third disclosure level. - With two levels, title each group with a short descriptive label. - Let people hide the sidebar (View menu Show/Hide Sidebar or a button); don't hide it by default. Sidebars float in the Liquid Glass layer; content can extend beneath them. +- macOS sidebar row height, text and glyph size follow the small/medium/large sidebar + size people pick in General settings — state which size the mockup shows; no critical actions + at the bottom of a sidebar. (Read 2026-11-13; page change 2026-06-08.) diff --git a/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/system-surfaces.md b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/system-surfaces.md new file mode 100644 index 0000000..adf725f --- /dev/null +++ b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/system-surfaces.md @@ -0,0 +1,57 @@ +--- +name: system-surfaces +description: "HIG rules for system surfaces an app designs for — Live Activities (limited width, 2026-10-13), widgets (Apple HomeView, appearances, 2026-10-13), plus the reintroduced HIG design principles (2026-06-08) and emphasized Dynamic Type weights (2025-12-16)." +when-to-use: "Mocking up a Live Activity, a widget, or checking a design against Apple's design principles or emphasized text weights." +keywords: live-activities, dynamic-island, widgets, apple-homeview, design-principles, typography, emphasized +priority: medium +related: ../SKILL.md, dynamic-type.md, type-scales-other.md, apple-design-tools.md +--- + +# System Surfaces and Principles + +Read 2026-11-13 from the HIG JSON endpoints. `/slug` = +`https://developer.apple.com/design/human-interface-guidelines/`. + +## Design principles — /design-principles (reintroduced 2026-06-08) +Eight principles, each a one-line test for a critique pass: +Purpose (make something meaningful) · Agency (let people do things their own way) · +Responsibility (act in people's best interest) · Familiarity (build on what people know) · +Flexibility (adapt to diverse contexts and needs) · Simplicity (be clear and direct) · +Craft (care about every detail) · Delight (make it human). +Use them as named lenses in `design-review`; quote the principle, not a paraphrase. + +## Emphasized text weights — /typography (2025-12-16) +The Dynamic Type specifications now list an **emphasized weight** per text style +(medium, semibold, bold or heavy), applied through the bold symbolic trait. The tables in +`dynamic-type.md` and `type-scales-other.md` carry that column — spec emphasis as +"`Body`, emphasized", never as a hand-picked weight. + +## Live Activities — /live-activities (2026-10-13) +- Platforms: iOS, iPadOS, macOS (appears in the menu bar of a paired Mac; click opens + iPhone Mirroring), watchOS, CarPlay; not tvOS or visionOS. macOS uses the iOS + dimensions. All spec values are in points. +- **Limited width** (new): where width is limited, e.g. the Dynamic Island on iPhone in + landscape, compact and minimal presentations must fit **inside a 28 pt-diameter + circle** — short abbreviation or graphic, not a full string. If a limited-width + trailing view makes no sense, ship the leading view only; the system hides the + trailing one. Specs list limited width as 28×28 pt. +- Compact: narrow, snug against the TrueDepth camera, no padding toward it, leading and + trailing balanced. +- Prefer one Live Activity with a rotating dynamic layout over several. +- Mock up every presentation (compact, minimal, expanded, Lock Screen, StandBy, limited + width) at the HIG's point sizes; read the per-device rows on the page — don't copy one + device's values to another. + +## Widgets — /widgets (2026-10-13) +- Contexts now include **Apple HomeView**: widgets from the small system family, sharing + the iPhone widget appearance; the **Modular face** holds up to four widgets (one per + household, possibly from different members' iPhones); each enrolled member has a + personal Home Screen. +- Home Screen appearances on iPhone, iPad and HomeView: **light, dark, clear, tinted** + (clear = desaturated + translucency + Liquid Glass; tinted = desaturated + the user's + tint). StandBy and the HomeView Modular face scale the widget up with the background + removed and turn monochromatic red in low ambient light. +- visionOS widgets are 3D objects placed on surfaces, full-color by default, accented + when tinted; test every system palette and lighting condition. +- Mockup deliverable: the widget in each appearance it supports, plus StandBy/Modular + face if supported. diff --git a/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/watch-tv-vision.md b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/watch-tv-vision.md index 9b89a78..c849d17 100644 --- a/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/watch-tv-vision.md +++ b/.cursor-plugin/plugins/fuse-design/skills/design-ios/references/watch-tv-vision.md @@ -54,6 +54,9 @@ Fetched 2026-10-12. `/slug` = `https://developer.apple.com/design/human-interfac (reserved for toggled state). — /buttons - Controls 60×60 pt default, 28×28 minimum. — /accessibility - Text: prefer 2D, white default, billboard spatial labels. — /typography +- **Look to Scroll** (scroll by gaze, opt-in per scroll view; HIG 2026-03-24): reading + and browsing views only, not dense/control-heavy ones — `bars-menus-scroll.md`. + — /scroll-views ## Rule A watchOS/tvOS/visionOS value not on these pages is marked "to reconfirm on diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/.cursor-plugin/plugin.json b/.cursor-plugin/plugins/fuse-swift-apple-expert/.cursor-plugin/plugin.json index aa18634..67fcc13 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/.cursor-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "fuse-swift-apple-expert", - "version": "1.1.24", + "version": "1.1.25", "description": "Expert Swift 6.4.2 + SwiftUI (Xcode 27.2) for iOS 27.2, macOS 27.2, iPadOS 27.2, watchOS 27.2, visionOS 27.2, tvOS 27.2 with Liquid Glass, @Observable, actors, SwiftData inheritance", "author": { "name": "Fusengine", diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/README.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/README.md index d9d46b9..8a2041a 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/README.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/README.md @@ -1,9 +1,9 @@ # fuse-swift-apple-expert (Cursor Plugin) -Expert Swift 6.2 + SwiftUI for iOS 26, macOS 26, iPadOS 26, watchOS 26, visionOS 26 and tvOS 26 — +Expert Swift 6.4.2 + SwiftUI (Xcode 27.2) for iOS 27.2, macOS 27.2, iPadOS 27.2, watchOS 27.2, visionOS 27.2 and tvOS 27.2 — Liquid Glass, `@Observable`, actors, SwiftData inheritance. -Ported from the Claude Code plugin `fuse-swift-apple-expert` v1.1.17 (source folder +Ported from the Claude Code plugin `fuse-swift-apple-expert` v1.2.0 (source folder `plugins/swift-apple-expert`). The plugin name is deliberately identical across both ecosystems so cross-plugin references (`fuse-swift-apple-expert:`) keep resolving. @@ -12,7 +12,7 @@ cross-plugin references (`fuse-swift-apple-expert:`) keep resolving. | Component | Count | Cursor discovery | | :-- | :-- | :-- | | Agents (subagents) | 1 | `agents/*.md` | -| Skills | 11 | `skills//SKILL.md` | +| Skills | 15 | `skills//SKILL.md` | | Hooks | 2 events | `hooks/hooks.json` | No `commands/` and no `docs/` folder: the source plugin has neither. An empty component folder @@ -22,16 +22,20 @@ would be a divergence, not a precaution (R4–R6 / R8–R10 preamble). | Skill | Description | | :-- | :-- | -| `swift-core` | Swift 6 fundamentals — concurrency, architecture, testing, i18n, performance — across any Apple platform | -| `swiftui-core` | SwiftUI views, navigation, persistence, state management, Liquid Glass, and HIG rules (accessibility, RTL, modality, widgets/Live Activities/notifications/Siri, iPhone Duo) — shared across iOS, macOS, watchOS, visionOS | -| `ios` | iPhone apps — simulator/device testing, UI automation, debugging — with XcodeBuildMCP tools | -| `ipados` | iPad apps — split views, external keyboard support, multitasking, Stage Manager, adaptive layouts | -| `macos` | Mac apps — menu bar extras, window management, AppKit integration, notarized distribution | +| `swift-core` | Swift Testing first, Swift 6.2 concurrency defaults, architecture, i18n, performance, Xcode 27 agents and `xcrun mcpbridge` — across any Apple platform | +| `swiftui-core` | SwiftUI views, navigation, SwiftData 27, WebView, state, Liquid Glass, App Intents runtime, WidgetKit/ActivityKit, and HIG rules (accessibility, RTL, modality, notifications/Siri, iPhone Duo) — shared across iOS, macOS, watchOS, visionOS | +| `ios` | iPhone apps — simulator/device testing, UI automation, debugging — with XcodeBuildMCP tools; UIKit 26-27 | +| `ipados` | iPad apps — split views, external keyboard support, multitasking, Stage Manager, menu bar, toolbars, adaptive layouts | +| `macos` | Mac apps — menu bar extras, window management, toolbars, touch on Mac, AppKit integration, notarized distribution | | `watchos` | Apple Watch apps — complications, workouts, HealthKit, iPhone-Watch connectivity | -| `visionos` | Vision Pro apps — spatial computing, RealityKit 3D content, immersive spaces, volumes | +| `visionos` | Vision Pro apps — spatial computing, RealityKit 27, ARKit, spatial web, ornaments, immersive spaces, volumes (no eye-tracking API) | | `tvos` | Apple TV apps — focus-based navigation, Siri Remote interactions, media/video streaming UI | -| `mcp-tools` | Xcode build automation and Apple API/WWDC documentation lookup via XcodeBuildMCP and apple-docs MCP servers; UI verification on simulator | -| `build-distribution` | Apple releases — code signing, TestFlight upload, App Store submission, Icon Composer app icons, CI | +| `apple-intelligence` | Foundation Models (on-device and Private Cloud Compute), Writing Tools, Genmoji, Image Playground, Visual Intelligence | +| `apple-frameworks` | Passkeys, MapKit, CloudKit, Core Data, TipKit, background tasks, MetricKit, App Attest, HealthKit, CarPlay, Chart3D | +| `graphics-games` | Metal 4, MetalFX, GameKit, Game Controller, Game Porting Toolkit 4; Metal vs RealityKit vs SpriteKit vs SceneKit | +| `media-vision` | AVFoundation, Now Playing, PhotoKit, Vision, Speech, translation, Core ML, Core Location, WeatherKit, EventKit | +| `mcp-tools` | Xcode build automation and Apple API/WWDC documentation lookup via XcodeBuildMCP and apple-docs MCP servers; UI verification on simulator; Xcode 27 agents and Xcode's MCP server | +| `build-distribution` | Apple releases — code signing, TestFlight upload, App Store submission, Icon Composer app icons, StoreKit 2, CI; deadlines: Developer ID G2 2027-02-01, age-rating declarations 2027-01-12, April 2027 SDK 27 / iOS 15 / iPhone Duo screenshots | | `solid-swift` | SOLID for Swift 6/SwiftUI — hook size ceiling (`FUSE_SOLID_MAX_LINES`), protocol separation, `@Observable`, actors, feature-modular architecture | SOLID guidance is **local** here (`solid-swift`), not delegated to `fuse-solid`. @@ -42,6 +46,8 @@ The agent activates when `Package.swift` or an `*.xcodeproj` is detected — iOS visionOS/tvOS apps, SwiftUI views, Swift concurrency, XcodeBuildMCP automation. Not for web frontend, Laravel/PHP, or non-Apple platforms. +Routing examples: "Add a Foundation Models summary feature" -> `apple-intelligence`; "Render with Metal 4 and MetalFX upscaling" -> `graphics-games`; passkeys, MapKit, CloudKit, TipKit, background tasks, HealthKit, CarPlay -> `apple-frameworks`; camera capture, Now Playing, PhotoKit, Vision, Speech, Core Location -> `media-vision`. + For UI changes the agent runs a 10-item HIG gate on the simulator (Dynamic Type AX5, dark mode + Increase Contrast, VoiceOver labels, hit targets, RTL, Reduce Motion/Transparency, Liquid Glass, screen sizes, modality/order), each reported `pass` / `fail` / `not verified`, before `sniper`. ## Configuration @@ -83,17 +89,26 @@ declares no `mcpServers` of its own; it did not in the source either. ### Skills -All 11 satisfy Cursor's hard rule that `name:` equals the parent folder name (R9). `references/` and +All 15 satisfy Cursor's hard rule that `name:` equals the parent folder name (R9). `references/` and nested `references/templates/` folders are natively supported and were copied verbatim in the initial port. On 2026-10-12 the source's uncommitted working-tree improvements were ported on top (HIG references, mcp-tools workflows, tvOS/watchOS/visionOS/build-distribution updates), so -`diff -rq` against the source is no longer empty. Target-only deviations kept on purpose: the +`diff -rq` against the source is no longer empty. On 2026-11-14 the source change `fd4f8c5e..a6a25857` +(v1.2.0) was ported: four new skills (`apple-intelligence`, `apple-frameworks`, `graphics-games`, +`media-vision`), 49 other new reference files, and updated SKILL.md/references; every reference file +changed in source range `fd4f8c5e..a6a25857` is byte-identical to the source except +`mcp-tools/references/xcode-agents.md`, the one adapted reference (Cursor `mcp.json` registration +first, Apple's `claude mcp add` / `codex mcp add` kept on one line, `AGENTS.md` / `.cursor/rules` +instead of `CLAUDE.md`). Target-only deviations kept on purpose: in `mcp-tools/SKILL.md` and +the agent body, the Xcode +MCP connection line says "register a stdio MCP server `xcode` in Cursor's MCP settings" instead of +Claude's `claude mcp add` command; the `Task`-based wording (instead of Claude's `Agent`-with-`name`) in the SKILL.md "Agent Workflow" sections, the `FUSE_SOLID_MAX_LINES` rewrite of `solid-swift`, the same ceiling wording in `swiftui-core` (no "30+ lines" view cap), this README's port notes, and the Cursor frontmatter of the agent. Frontmatter keys preserved verbatim, absent from Cursor's documented skill schema and **not verified against the binary**, so their status is unknown rather than unsupported (R7/R19): -`references` (11), `related-skills` (11), `user-invocable` (11), `versions` (10). +`references` (15), `related-skills` (15), `user-invocable` (15), `versions` (14). `user-invocable` was **not** translated to `disable-model-invocation` (R8). They are near-opposites: Cursor's `disable-model-invocation: true` means "only reachable via `/skill-name`", whereas Claude @@ -154,7 +169,7 @@ declares **no scope argument**, and that absence is preserved exactly: nothing i ## Runtime paths This plugin references no `.claude/…` runtime state path in the body of any skill or agent (0 -occurrences across 11 skills and 1 agent). There is nothing for the harness to resolve, so R21's +occurrences across 15 skills and 1 agent). There is nothing for the harness to resolve, so R21's clause is deliberately not reproduced here: on a plugin with zero occurrences it would assert something false. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/agents/swift-expert.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/agents/swift-expert.md index 92da7c2..0007929 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/agents/swift-expert.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/agents/swift-expert.md @@ -4,7 +4,7 @@ description: "Use when: Package.swift or *.xcodeproj detected, iOS/macOS/watchOS model: grok-4.6 color: red tools: mcp__context7__resolve-library-id, mcp__context7__query-docs, mcp__exa__web_search_exa, mcp__exa__get_code_context_exa, mcp__XcodeBuildMCP__*, mcp__apple-docs__*, Read, Glob, Grep, Edit, Write, Bash, Task, Skill, mcp__fuse-browser__browser_navigate, mcp__fuse-browser__browser_console, mcp__fuse-browser__browser_inspect, mcp__fuse-browser__browser_snapshot, mcp__fuse-browser__browser_fetch, mcp__fuse-browser__browser_fetch_batch, mcp__sequential-thinking__sequentialthinking -skills: swift-core, swiftui-core, ios, macos, ipados, watchos, visionos, tvos, mcp-tools, build-distribution, solid-swift, elicitation, fuse-ai-pilot:fuse-browser-usage +skills: swift-core, swiftui-core, ios, macos, ipados, watchos, visionos, tvos, apple-intelligence, apple-frameworks, graphics-games, media-vision, mcp-tools, build-distribution, solid-swift, elicitation, fuse-ai-pilot:fuse-browser-usage --- ## Allowed tools @@ -94,6 +94,15 @@ Then implement using the platform-specific skill(s) (see Coding Standards below) **Priority**: Use Apple Docs MCP FIRST before Context7 for Apple-specific queries. +### Xcode 27 agents and Xcode's MCP server +**Source**: Apple (https://developer.apple.com/documentation/xcode/giving-external-agents-access-to-xcode) — details in `mcp-tools` skill (`xcode-agents.md`) + +- **Connect to Xcode**: allow external agents in Xcode > Settings > Intelligence, then register a stdio MCP server named `xcode` in Cursor's MCP settings (`"type": "stdio"`, command `xcrun`, args `["mcpbridge"]`); open the project in Xcode first +- **Xcode MCP tools**: RenderPreview (SwiftUI preview images with variants), String Catalog read/plan/edit, debugger and run-state control, schemes/destinations, build settings, entitlements; `lldb-mcp` ships with LLDB +- **Workspace-less preview**: `sudo xcrun mcp-server enable` (beta 5 preview, caveats in the reference) +- **Inside Xcode**: coding intelligence with plan mode (`/plan`, `/exit-plan`), plug-ins (skills, MCP servers, ACP agents), Agent Client Protocol, Gemini, Antigravity, GitHub Copilot (27.3 beta) +- XcodeBuildMCP stays the default for build, test and UI evidence (the project is being renamed MobileBuildMCP, see `xcodebuild-mcp.md`) + --- ## SOLID Rules (MANDATORY) @@ -113,12 +122,17 @@ Then implement using the platform-specific skill(s) (see Coding Standards below) ## Core Rule - **Verify Before Writing**: Use Context7/Exa to confirm APIs/patterns are correct and up-to-date before writing any code +- **Complete reference**: verify an Apple API (name, signature, availability) on `developer.apple.com/tutorials/data/documentation/.json` (lowercase path, e.g. `swiftui/toolbarspacer.json`; HIG: `.../tutorials/data/design/human-interface-guidelines/.json`) via `browser_fetch`; never conclude an API is absent from the apple-docs MCP search alone ## Coding Standards - **@Observable** over ObservableObject, **structured concurrency** (async/await), **value types** (structs over classes) - **Protocol-oriented** design, **cohesive views** (extract subviews when responsibilities diverge), **accessibility** mandatory - **i18n** — ALL user-facing text must use String Catalogs - See platform-specific skills (`ios`, `macos`, `watchos`, `visionos`, `tvos`, `ipados`) for platform targeting +- **Routing**: Foundation Models / Writing Tools / Image Playground / Genmoji / Visual Intelligence / Apple Intelligence -> `apple-intelligence` skill +- **Routing**: passkeys / credential exchange, MapKit, CloudKit, Core Data, TipKit, notifications, background tasks, MetricKit, App Attest, HealthKit, CarPlay, Chart3D -> `apple-frameworks` skill +- **Routing**: Metal 4, MetalFX, GameKit, Game Controller, Game Porting Toolkit, Metal vs RealityKit/SpriteKit/SceneKit -> `graphics-games` skill +- **Routing**: camera capture, media playback, Now Playing / MediaDevice / AVSystemRouting, PhotoKit, Vision, Speech, Core ML / Translation / Natural Language / MusicUnderstanding, Core Location / WeatherKit / EventKit -> `media-vision` skill - **HIG** — for any UI work load the `swiftui-core` HIG references (`hig-accessibility.md`, `hig-rtl.md`, `hig-modality.md`, `hig-system-surfaces.md`, `hig-iphone-duo.md`, `liquid-glass.md`). Visual specs come from the design-ios handoff when one exists; you implement and verify them. ## fuse-browser (ZERO TOLERANCE) diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/SKILL.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/SKILL.md new file mode 100644 index 0000000..a315b4b --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/SKILL.md @@ -0,0 +1,87 @@ +--- +name: apple-frameworks +description: Use when adding an Apple system framework to an app - passkeys and credential exchange, MapKit geocoding, CloudKit, Core Data, TipKit, local notifications, continued background tasks, MetricKit state reporting, App Attest, HealthKit workout zones, CarPlay map panels, or Chart3D. +versions: + ios: 27.2 + xcode: 27.2 +user-invocable: false +references: references/authentication-services.md, references/mapkit.md, references/cloudkit.md, references/core-data.md, references/tipkit.md, references/user-notifications.md, references/background-tasks.md, references/metrickit.md, references/app-attest.md, references/healthkit.md, references/carplay.md, references/charts-3d.md +related-skills: swift-core, swiftui-core, ios, macos, ipados, watchos, build-distribution +--- + + +Reference skill for Apple system frameworks outside SwiftUI, UIKit and AppKit. Each reference holds the symbols verified on Apple's documentation JSON (availability, deprecations), the current-year changes (2025-2026 updates pages and iOS 27 release notes) and a minimal Swift 6 sample. + +Covers AuthenticationServices (passkeys, account creation, Credential Exchange, `ASCredentialDataManager`), MapKit (geocoding, `MKAddress`), CloudKit, Core Data (current role next to SwiftData), TipKit, UserNotifications, `BGContinuedProcessingTask`, MetricKit and StateReporting, App Attest, HealthKit (iOS workout sessions, medications, workout zones, limited-history permission), CarPlay (`CPMapPanel`) and Chart3D. + +Every fact carries its Apple URL and the date it was read; a symbol that could not be verified is not written. + + +# Apple Frameworks + +System frameworks an app adopts next to its UI layer. + +## Agent Workflow (MANDATORY) + +Before ANY implementation, delegate via `Task` — spawn 3 agents in parallel (single message, 3 `Task` calls): + +1. **fuse-ai-pilot:explore-codebase** - Find existing framework usage, entitlements, Info.plist keys +2. **fuse-ai-pilot:research-expert** - Verify the symbol and its availability on `developer.apple.com/tutorials/data/documentation//.json` +3. **mcp__apple-docs__search_apple_docs** - Cross-check (search is unreliable: confirm on the JSON page) + +After implementation, run **fuse-ai-pilot:sniper** for validation. + +--- + +## Overview + +### When to Use + +- Passwordless sign-in, passkey sign-up, moving credentials between password managers +- Address lookup or place names from text or coordinates +- Syncing app data through iCloud, or maintaining an existing Core Data stack +- Teaching features with tips, scheduling or showing notifications +- Finishing a user-started job after the app leaves the foreground +- Collecting performance data per feature, proving app integrity to a server +- Workout zones, medications, or limited-history permission in HealthKit +- A navigation overlay in CarPlay, a 3D chart + +### Why this skill + +| Problem | What this skill gives | +|---------|-----------------------| +| Deprecated or renamed APIs in samples and videos (`ASCredentialUpdater`) | Current symbol with the deprecation date | +| Capability and entitlement gaps | Required Info.plist keys and entitlements per framework | +| Platform gaps (App Attest, `HKLiveWorkoutBuilder` on iOS) | Availability copied from Apple's pages, not memory | + +--- + +## Reference Guide + +| Need | Reference | +|------|-----------| +| Passkeys, account creation, Credential Exchange, `ASCredentialDataManager` | [authentication-services.md](references/authentication-services.md) | +| Geocoding, reverse geocoding, `MKAddress`, SwiftUI `Map` | [mapkit.md](references/mapkit.md) | +| `CKSyncEngine`, share access requests | [cloudkit.md](references/cloudkit.md) | +| Core Data stack, history, staged migrations, vs SwiftData | [core-data.md](references/core-data.md) | +| Tips, rules, groups, CloudKit sync of tips | [tipkit.md](references/tipkit.md) | +| Authorization, scheduling, delegate, interruption levels | [user-notifications.md](references/user-notifications.md) | +| `BGContinuedProcessingTask` | [background-tasks.md](references/background-tasks.md) | +| `MetricManager`, `StateReporter` | [metrickit.md](references/metrickit.md) | +| `DCAppAttestService` | [app-attest.md](references/app-attest.md) | +| Workout sessions on iOS, medications, zones, history permission | [healthkit.md](references/healthkit.md) | +| `CPMapPanel`, map template panels | [carplay.md](references/carplay.md) | +| `Chart3D`, `SurfacePlot` | [charts-3d.md](references/charts-3d.md) | + +Related: SwiftData and `@Query` in [data-swiftdata.md](../swiftui-core/references/data-swiftdata.md); App Intents in [app-intents.md](../swiftui-core/references/app-intents.md); widgets and Live Activities HIG in [hig-system-surfaces.md](../swiftui-core/references/hig-system-surfaces.md); App Store privacy manifests in [privacy-manifest.md](../build-distribution/references/privacy-manifest.md). + +--- + +## Best Practices + +1. **Verify before writing** - Check the symbol on Apple's JSON page; read `introducedAt`, `deprecatedAt` and the `beta` flag +2. **Prefer async variants** - HealthKit, UserNotifications, App Attest, MapKit and CloudKit expose `async throws` forms of the callback methods +3. **Declare capabilities first** - Entitlement, Info.plist key or Associated Domains before the first call +4. **Gate by deployment target** - A 27.x symbol needs `#available`; the 27.3 items in these references are beta +5. **Never trust the client alone** - App Attest and passkey results are verified on your server +6. **Privacy by design** - Ask for the least data (HealthKit limited history, notification provisional authorization) diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/app-attest.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/app-attest.md new file mode 100644 index 0000000..bb9c7a9 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/app-attest.md @@ -0,0 +1,61 @@ +--- +name: app-attest +description: App Attest (DeviceCheck) - key generation, attestation, assertions, the iOS 27 authenticator-data extensions, macOS 27 support, and the fraud metric +when-to-use: proving to your server that requests come from a genuine, unmodified copy of your app, on iOS or on macOS 27 and later +keywords: DCAppAttestService, generateKey, attestKey, generateAssertion, isSupported, fraud metric, launch validation category, ACL blob, relying party identifier +priority: medium +related: ../SKILL.md, authentication-services.md +--- + +# App Attest + +Sources, read 2026-11-13: WWDC26 session 201 "Secure your apps with App Attest" (https://developer.apple.com/videos/play/wwdc2026/201/; transcript and code read on the page), article https://developer.apple.com/documentation/devicecheck/establishing-your-app-s-integrity, symbol pages `.../tutorials/data/documentation/devicecheck/dcappattestservice/.json`, Apple's June 2026 updates index ("The DeviceCheck framework brings App Attest to macOS with additional device information"). + +## Platform availability + +- Session 201: App Attest "is supported on all Apple platforms, including macOS 27 and higher, which was previously not supported". Not every app type or extension is eligible (it works in Action and SSO app extensions, not other extension types): gate with `DCAppAttestService.shared.isSupported`. +- The symbol pages show `DCAppAttestService` and `isSupported` with `introducedAt` iOS 14.0, macOS 11.0, tvOS 15.0, visionOS 1.0, watchOS 9.0. Treat the session as the statement of macOS behavior: keep the macOS code path behind `if #available(macOS 27, *)`. +- An unexpected `isSupported == false` on a platform where you ship is a fraud signal worth logging server-side (session 201); decide deliberately whether to let the person continue. + +## Symbols (DeviceCheck) + +| Need | Symbol | +|------|--------| +| Support check | `DCAppAttestService.shared.isSupported` | +| Create key | `generateKey()` `async throws -> String` (key ID, hash of the public key; private key stays in the Secure Enclave) | +| Attest | `attestKey(_ keyId: String, clientDataHash: Data)` `async throws -> Data` | +| Assert | `generateAssertion(_ keyId: String, clientDataHash: Data)` `async throws -> Data` | +| Capability | `com.apple.developer.devicecheck.appattest-environment` entitlement (named on the DeviceCheck landing page) | + +The session's slide code writes `attestKey(keyId:clientDataHash:)`; the symbol page declares `attestKey(_:clientDataHash:)` (unlabeled key ID). Use the symbol page form. Callback variants exist for all three methods. + +## Flow and rules (session 201) + +1. **Key**: one key per user for account-based apps, or one for the whole app; never share keys across users. Store the key ID in the Keychain. Key IDs survive app updates; reinstalling or restoring the device (including from iCloud backup) invalidates the key; keys never sync across devices. +2. **Attest**: your server starts it and vends a challenge (keeps request rates bounded); the app calls `attestKey` with the key ID and the hash of the challenge, sends the attestation to the server, which validates it and associates it with the user. Retry failures later with exponential back-off, no hard-coded retry loops; run it outside user flows (background task). Never validate in the app. +3. **Attestation contents** (server side): a fixed format string, attestation statement (certificate chain proving genuine Apple hardware, nonce, key ID and relying party identifier in the leaf certificate, plus a receipt) and authenticator data. The relying party identifier is Team ID + bundle ID. New in iOS 27: extensions appended to the authenticator data: **launch validation category** (App Store vs TestFlight and others) and **bundle version**. New in macOS 27: the key access control property (ACL Blob OID) in the leaf certificate; on macOS App Attest keys require full security mode and System Integrity Protection. +4. **Assert**: per sensitive request, server vends a challenge, app calls `generateAssertion`, embeds the result in the payload. Assertions are generated locally (no Apple round trip) but cost CPU: do not generate them in tight loops. The server verifies the signature and requires the assertion **counter to be strictly increasing**; the same iOS 27 extensions appear in assertion authenticator data. +5. **Server reactions**: do not reject a new key for an existing user outright (reinstall and restore rotate keys) and do not instantly invalidate older keys; on rejection degrade features rather than block, after a risk assessment. +6. **Fraud metric**: your server POSTs a stored attestation receipt to the App Attest data server and receives a receipt whose risk metric is an approximate count of unique attested keys for your app on one device over the past 30 days. Key rotation (reinstall, restore) raises it. Use it as an investigation signal and baseline, never to block users outright. Refresh receipts after their not-before time; they expire. + +```swift +import DeviceCheck + +struct AttestationClient { + private let service = DCAppAttestService.shared + + func attest(challengeHash: Data, existingKeyID: String?) async throws -> (keyID: String, attestation: Data)? { + guard service.isSupported else { return nil } // treat as a risk signal on the server + let keyID: String + if let existingKeyID { keyID = existingKeyID } else { keyID = try await service.generateKey() } + let attestation = try await service.attestKey(keyID, clientDataHash: challengeHash) + return (keyID, attestation) // send to your server; it validates + } + + func assertion(keyID: String, requestHash: Data) async throws -> Data { + try await service.generateAssertion(keyID, clientDataHash: requestHash) + } +} +``` + +Persist `keyID` in the Keychain yourself. `clientDataHash` is the SHA-256 of your server challenge (and request payload for assertions): the article builds it with `SHA256` from CryptoKit. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/authentication-services.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/authentication-services.md new file mode 100644 index 0000000..d62fd74 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/authentication-services.md @@ -0,0 +1,105 @@ +--- +name: authentication-services +description: AuthenticationServices - passkey sign-in and fast account creation, ASAuthorizationController options, Credential Exchange between password managers, and ASCredentialDataManager (replacing the deprecated ASCredentialUpdater) +when-to-use: adding passkey sign-up or sign-in, upgrading password accounts to passkeys, exporting or importing credentials, telling credential managers about renamed, revoked or unused credentials +keywords: passkey, ASAuthorizationController, ASAuthorizationAccountCreationProvider, ASCredentialExportManager, ASCredentialImportManager, ASCredentialDataManager, ASCredentialUpdater, preferImmediatelyAvailableCredentials, conditional registration +priority: high +related: ../SKILL.md, app-attest.md +--- + +# AuthenticationServices + +Sources, read 2026-11-13: symbol pages `developer.apple.com/tutorials/data/documentation/authenticationservices/.json`; framework page https://developer.apple.com/documentation/authenticationservices; WWDC25 session 279 "What's new in passkeys" (code via https://developer.apple.com/videos/play/wwdc2025/279/). The framework updates page has no entry after June 2024: the 2025-2026 items below come from symbol pages and release notes. + +## Setup + +Associated Domains capability with `webcredentials:` and an `apple-app-site-association` file at `/.well-known/` listing the app ID for `webcredentials` (Apple's passkey samples, `performing-fast-account-creation-with-passkeys`). + +## Symbols + +| Need | Symbol | Availability | +|------|--------|--------------| +| Run requests (UIKit/AppKit) | `ASAuthorizationController(authorizationRequests:)`, `performRequests(options:)`, `performAutoFillAssistedRequests()` | 13.0 / 16.0 | +| Run requests (SwiftUI) | `@Environment(\.authorizationController)` -> `AuthorizationController.performRequest(_:)`, `performAutoFillAssistedRequest(_:)`; result `ASAuthorizationResult` | 16.4 | +| Prefer a credential on this device | `ASAuthorizationController.RequestOptions.preferImmediatelyAvailableCredentials` | 16.0. iOS 26 notes: now also works for passkey registration | +| Passkey sign-in / sign-up | `ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier:)` -> `createCredentialAssertionRequest(challenge:)`, `createCredentialRegistrationRequest(challenge:name:userID:)` | 15.0 | +| Silent passkey upgrade after a password sign-in | `createCredentialRegistrationRequest(challenge:name:userID:requestStyle:)` with `RequestStyle.conditional` | 18.0 | +| Fast account creation | `ASAuthorizationAccountCreationProvider().createPlatformPublicKeyCredentialRegistrationRequest(acceptedContactIdentifiers:shouldRequestName:relyingPartyIdentifier:challenge:userID:)`; request `ASAuthorizationAccountCreationPlatformPublicKeyCredentialRequest`; result case `ASAuthorizationResult.passkeyAccountCreation(_:)` with `credentialRegistration`, `name`, `contactIdentifier` | 26.0 | +| Account-creation errors | `ASAuthorizationError.deviceNotConfiguredForPasskeyCreation`, `.preferSignInWithApple`, `.matchedExcludedCredential` (18.0), `.canceled` | 26.0 for the first two | +| Export credentials | `ASCredentialExportManager(presentationAnchor:)`, `requestExport(for:)` -> `ExportOptions`, `exportCredentials(_:)`; SwiftUI `@Environment(\.credentialExportManager)` | 26.0 | +| Import credentials | `ASCredentialImportManager()`, `importCredentials(token:)` -> `ASExportedCredentialData`; token from `ASCredentialImportToken` in the user activity | 26.0 | +| Tell credential managers about changes | `ASCredentialDataManager`: `reportPublicKeyCredentialUpdate(relyingPartyIdentifier:userHandle:newName:)`, `reportAllAcceptedPublicKeyCredentials(relyingPartyIdentifier:userHandle:acceptedCredentialIDs:)`, `reportUnusedPasswordCredential(domain:userName:)`, `reportUnknownPublicKeyCredential(relyingPartyIdentifier:credentialID:)`, `save(password:for:title:anchor:)` | 26.2, all `async throws` | +| **Deprecated** | `ASCredentialUpdater` (same four report methods) | introduced 26.0, deprecated 26.2: use `ASCredentialDataManager` | + +`ASCredentialDataManager` does not say whether the operation succeeded (privacy): a return only means the parameters were well formed. + +## Fast account creation (WWDC25 session 279, 6:33) + +```swift +import AuthenticationServices +import SwiftUI + +struct SignUpView: View { + @Environment(\.authorizationController) private var authorizationController + @State private var showPasswordForm = false + + func signUp() async { + let provider = ASAuthorizationAccountCreationProvider() + let request = provider.createPlatformPublicKeyCredentialRegistrationRequest( + acceptedContactIdentifiers: [.email, .phoneNumber], + shouldRequestName: true, + relyingPartyIdentifier: "example.com", + challenge: await fetchChallenge(), // your server + userID: await fetchUserID() // your server + ) + do { + let result = try await authorizationController.performRequest(request) + if case .passkeyAccountCreation(let account) = result { + // Send account.credentialRegistration to the server to create the account. + _ = account + } + } catch ASAuthorizationError.deviceNotConfiguredForPasskeyCreation { + showPasswordForm = true + } catch ASAuthorizationError.canceled { + showPasswordForm = true + } catch ASAuthorizationError.preferSignInWithApple { + // Offer Sign in with Apple instead. + } catch { + // Surface the error. + } + } + + var body: some View { Button("Create account") { Task { await signUp() } } } +} +``` + +`fetchChallenge()` and `fetchUserID()` are your server calls (`async -> Data`). Challenges are single-use and server-generated; verify the registration and assertion on the server. + +## Credential Exchange (iOS 26) + +Credential provider extension Info.plist: `NSExtension > NSExtensionAttributes > ASCredentialProviderExtensionCapabilities > SupportsCredentialExchange = YES` and `SupportedCredentialExchangeVersions` (only `1.0` exists). The importing app lists the activity type in `NSUserActivityTypes` (Apple's prose says `ASCredentialExchangeActivityType`; the declared constant is `ASCredentialExchangeActivity`, iOS 26.0, and Apple's sample uses the non-existent name: use the declared one), then receives the token: + +```swift +.onContinueUserActivity(ASCredentialExchangeActivity) { activity in + Task { + guard let token = activity.userInfo?[ASCredentialImportToken] as? UUID else { return } + let data = try await credentialImportManager.importCredentials(token: token) + _ = data // store through your own vault + } +} +``` + +Export: `let options = try await credentialExportManager.requestExport()`, build `ASExportedCredentialData` in the format version `options` reports, then `try await credentialExportManager.exportCredentials(data)`. The system shows its own UI explaining the risks and choosing the importer; nothing is written to disk (Apple's `ASCredentialExportManager` page). + +## Report credential changes + +```swift +let manager = ASCredentialDataManager() +try await manager.reportPublicKeyCredentialUpdate( + relyingPartyIdentifier: "example.com", + userHandle: userHandle, // Data + newName: "andrew@example.com" +) +``` + +WWDC25 session 279 shows the same calls on `ASCredentialUpdater` (session predates the 26.2 deprecation): use the `ASCredentialDataManager` form above. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/background-tasks.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/background-tasks.md new file mode 100644 index 0000000..36a2966 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/background-tasks.md @@ -0,0 +1,71 @@ +--- +name: background-tasks +description: BGContinuedProcessingTask (iOS 26) - user-started long-running work that keeps running after the app is backgrounded, with system progress UI, GPU option and submission strategy +when-to-use: exporting video or audio, batch image processing, or any user-initiated job that can take minutes and must survive backgrounding +keywords: BGContinuedProcessingTask, BGContinuedProcessingTaskRequest, BGTaskScheduler, requiredResources, supportedResources, SubmissionStrategy, Live Activity progress +priority: medium +related: ../SKILL.md, metrickit.md +--- + +# Continued processing tasks + +Sources, read 2026-11-13: BackgroundTasks updates page (June 2025 entry "Continuous Background Tasks"), article https://developer.apple.com/documentation/backgroundtasks/performing-long-running-tasks-on-ios-and-ipados, symbol pages `.../tutorials/data/documentation/backgroundtasks/.json`. iOS and iPadOS 26.0 and Mac Catalyst 26.0 only: no macOS, watchOS, tvOS or visionOS. + +## Symbols + +| Need | Symbol | Availability | +|------|--------|--------------| +| Request | `BGContinuedProcessingTaskRequest(identifier:title:subtitle:)`; `requiredResources` (`Resources`, e.g. `.gpu`), `strategy` (`SubmissionStrategy`: `queue` default, `fail`) | 26.0 | +| Running task | `BGContinuedProcessingTask`: `title`, `subtitle`, `updateTitle(_:subtitle:)`, `progress` (`ProgressReporting`), `expirationHandler`, `setTaskCompleted(success:)` (from `BGTask`, 13.0) | 26.0 | +| GPU check | `BGTaskScheduler.supportedResources.contains(.gpu)` | 26.0 | +| Register and submit | `BGTaskScheduler.shared.register(forTaskWithIdentifier:using:launchHandler:)`, `submit(_:)` | | + +## Rules (Apple's article) + +- Start it only in response to a person's action (a button tap). Unlike other `BGTask` subclasses it starts in the foreground. +- The identifier is prefixed with your bundle ID plus a unique task name per job. +- The system shows title, subtitle and progress in a **Live Activity**; the person can cancel. Report accurate progress: tasks with minimal progress are terminated first under resource pressure, and a stuck-looking task invites cancellation. +- Cancellation (from the UI) calls the `expirationHandler`; check it in your loop. The system cancels running tasks silently when the person closes the app in the app switcher. +- Background GPU: set `requiredResources = .gpu` only after `supportedResources` contains `.gpu`, enable the Background GPU Access capability (entitlement `com.apple.developer.background-tasks.continued-processing.gpu` = true). +- `strategy = .fail` makes submission fail at once if the system cannot start the task immediately; the default queues it. +- Info.plist (WWDC25 session 227 "Finish tasks in the background", https://developer.apple.com/videos/play/wwdc2025/227/): add the identifier to the permitted background task scheduler identifiers array, prefixed with your bundle ID. A wildcard form ends in `.*` and the dynamic suffix is appended at registration and submission. +- Unlike the other `BGTask` types, the launch handler does **not** have to be registered before launch finishes: register it when the person's intent is expressed (session 227), right before `submit(_:)`. +- A task that reports no progress is expired; slow progress prompts the person to decide whether to continue. You must call `setTaskCompleted(success:)` when the work ends (session 227). +- Do not use it for automatic work (maintenance, backups, photo sync): such tasks may be cancelled (session 227). + +```swift +import BackgroundTasks + +@MainActor +final class ExportJob { + private let taskIdentifier = "com.example.app.export" // bundle ID + task name + + /// Call from the button action that starts the export. + func start() throws { + // Register when the intent is expressed, then submit (WWDC25 session 227). + BGTaskScheduler.shared.register(forTaskWithIdentifier: taskIdentifier, using: nil) { task in + guard let task = task as? BGContinuedProcessingTask else { return } + Self.run(task) + } + let request = BGContinuedProcessingTaskRequest( + identifier: taskIdentifier, title: "Video export", subtitle: "About to start...") + request.strategy = .fail + try BGTaskScheduler.shared.submit(request) + } + + nonisolated static func run(_ task: BGContinuedProcessingTask) { + nonisolated(unsafe) var expired = false + task.expirationHandler = { expired = true } + let progress = task.progress + progress.totalUnitCount = 100 + while !progress.isFinished && !expired { + progress.completedUnitCount += 1 + task.updateTitle(task.title, subtitle: "\(Int(progress.fractionCompleted * 100))%") + Thread.sleep(forTimeInterval: 1) + } + task.setTaskCompleted(success: progress.isFinished) + } +} +``` + +The register-then-submit flow, the progress loop, `updateTitle(_:subtitle:)` and `setTaskCompleted(success:)` follow Apple's article and session 227; the `nonisolated(unsafe)` flag and `Thread.sleep` stand in for your real work (not compiled against the SDK here). Add the Background GPU Access capability and a `.gpu` check only if the job uses the GPU. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/carplay.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/carplay.md new file mode 100644 index 0000000..30c5590 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/carplay.md @@ -0,0 +1,58 @@ +--- +name: carplay +description: CarPlay framework for iOS 26.4 and 27 - map panels (CPMapPanel), video browsing, thumbnails and details headers, MiniPlayer, voice control overlay, route sharing +when-to-use: building or extending a CarPlay navigation, audio, video or voice app; adding panels to the map template +keywords: CPMapPanel, CPMapPanelItem, CPMapPanelButtonConfiguration, CPMapTemplate, pushPanel, CPPlaybackConfiguration, CPListTemplateDetailsHeader, allowsMiniPlayer, showOverlayTemplate, route sharing, supportsVideoPlayback +priority: medium +related: ../SKILL.md, ../../swiftui-core/references/hig-system-surfaces.md +--- + +# CarPlay + +Sources, read 2026-11-13: WWDC26 session 212 "Rev up your CarPlay app" (https://developer.apple.com/videos/play/wwdc2026/212/, transcript and code read on the page); CarPlay landing page https://developer.apple.com/documentation/carplay (no framework updates page: 404); symbol pages `.../tutorials/data/documentation/carplay/.json`. CarPlay apps need a CarPlay entitlement per category (https://developer.apple.com/documentation/carplay/requesting-carplay-entitlements, not read in detail). Widgets and Live Activities appear in CarPlay for any app: [hig-system-surfaces.md](../../swiftui-core/references/hig-system-surfaces.md). + +## Symbols + +| Need | Symbol | Availability | +|------|--------|--------------| +| Map panel | `CPMapPanel(title:sections:buttonConfiguration:)`, `CPMapPanelSection(title:items:)`, `CPMapPanelItem` (inits for `trip`, `routeChoice`, `routeDetails`, `mapTemplateWaypoint`, `travelEstimates`, `chargingStationConnection`), `CPMapPanelButtonConfiguration(primaryAction:secondaryButton:travelEstimates:)`, delegate `panelDidShow(_:)` / `panelDidHide(_:)` | iOS 27.0 | +| Show panels | `CPMapTemplate.showPanel(_:)`, `pushPanel(_:)`, `popPanel`, `hidePanel` (all with `async throws -> Bool` forms) | 27.0 | +| EV charging | `CPChargingStationConnection(connector:voltage:power:)` | 27.0 | +| Overlay template | `CPInterfaceController.showOverlayTemplate(_:animated:)` / `hideOverlayTemplate` | 27.0 | +| MiniPlayer | `CPNowPlayingTemplate.allowsMiniPlayer` (default on; set `false` to show the now-playing icon in the navigation bar) | 27.0 | +| Video support | `CPSessionConfiguration.supportsVideoPlayback` | 26.4 | +| Rich lists | `CPPlaybackConfiguration`, `CPListTemplateDetailsHeader`, `CPThumbnailImage`, `CPImageOverlay`, `CPSportsOverlay` | 26.4 | +| Route sharing | `CPMapTemplateDelegate.mapTemplateShouldProvideRouteSharing(_:)` (return `true`), `CPTrip.routeSegmentsAvailableForRegion = false` to opt a trip out | 26.4 | +| 3D coordinates | `CPLocationCoordinate3D` | 26.4 | + +## Rules (session 212) + +- **Panels** let a navigation app build its own primary area of the map template independently of trip and route-choice presentation; combine trips, grids, route choices, route details, waypoints and list items; the button configuration adds the actions at the bottom (Go, End). Build and push panels while the map stays visible. +- **Route sharing** (iOS 26.4 and a supported vehicle): the app sends route segments (geographic coordinates) to the vehicle whenever the trip changes; the vehicle may propose a charging waypoint through the map template. Return updated travel estimates to prompt the driver, or manage confirmation yourself. +- **Video**: needs the CarPlay video entitlement and AirPlay video streaming support; apps with only the video entitlement appear on the home screen only in cars with the video-in-car feature; the car can switch to audio-only at any time. If content suits both, hold the audio and video entitlements. Add the videos tab only when `supportsVideoPlayback` is true. Provide subtitles and audio languages. +- **Lists**: thumbnails accept portrait or landscape images, overlays (title text, image badge, sports teams and score), playback progress through `CPPlaybackConfiguration` (preferred presentation video or audio, elapsed time, duration, play/pause/replay action). Update the thumbnail's and details header's playback configuration on every playback state change. +- **Voice control**: the template is available to all categories in iOS 27; optional prompt and animated icon, up to two action buttons plus leading and trailing navigation bar buttons; present it as an overlay over another template and give shorter text for the overlay. For feedback sounds set `AVAudioSession` to the play-and-record category, default mode, mixing disabled. To start navigation or a call from it, open the URL through `CPTemplateApplicationScene`. +- The CarPlay Simulator can be configured as a video-capable vehicle (session 212). Xcode 27 notes list as fixed: "Cannot start a CarPlay connection with CarPlay Simulator when accessed via Device Hub" (radar 179523697). + +```swift +import CarPlay + +// Keep the MiniPlayer unless your design needs the icon in the bar. +CPNowPlayingTemplate.shared.allowsMiniPlayer = false + +// Route sharing: opt in for the map template. +func mapTemplateShouldProvideRouteSharing(_ mapTemplate: CPMapTemplate) -> Bool { true } + +// Panels (iOS 27): build sections from items you already use, then push. +func showTripPanel(on mapTemplate: CPMapTemplate, trip: CPTrip, + go: CPTextButton, estimates: CPTravelEstimates) async throws { + let item = CPMapPanelItem(trip: trip) + let section = CPMapPanelSection(title: "Route", items: [item]) + let buttons = CPMapPanelButtonConfiguration( + primaryAction: go, secondaryButton: nil, travelEstimates: estimates) + let panel = CPMapPanel(title: "Trip", sections: [section], buttonConfiguration: buttons) + _ = try await mapTemplate.pushPanel(panel) +} +``` + +The first two snippets are Apple's session code; the panel function composes the initializers verified on their symbol pages and is not compiled against the SDK here. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/charts-3d.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/charts-3d.md new file mode 100644 index 0000000..7ef40a9 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/charts-3d.md @@ -0,0 +1,65 @@ +--- +name: charts-3d +description: Chart3D and SurfacePlot in Swift Charts (iOS 26) - 3D point, rule and rectangle marks, surfaces from functions, pose and camera projection, and the iOS 27 conditional-content crash fix +when-to-use: visualizing three variables or a function of two variables, letting people rotate a chart, deploying Swift Charts below iOS 27 +keywords: Chart3D, SurfacePlot, Chart3DPose, chart3DPose, chart3DCameraProjection, Chart3DContent, PointMark, chartZAxisLabel +priority: low +related: ../SKILL.md +--- + +# Chart3D + +Sources, read 2026-11-13: Swift Charts updates page https://developer.apple.com/documentation/updates/swiftcharts (June 2025 entry), symbol pages `.../tutorials/data/documentation/charts/.json` and `.../documentation/swiftui/view/.json`, iOS 27 release notes (Swift Charts). + +## Symbols + +| Need | Symbol | Availability | +|------|--------|--------------| +| 3D chart view | `Chart3D` (`@MainActor struct`, content conforms to `Chart3DContent`): `init(content:)`, `init(_:content:)` for a data collection | iOS, iPadOS, Mac Catalyst, macOS, visionOS 26.0 (not tvOS or watchOS) | +| Surface of a function | `SurfacePlot(x:y:z:function:)` | 26.0 | +| 3D marks | 3D initializers of `PointMark`, `RuleMark`, `RectangleMark` (take `x:`, `y:` and `z:` values) | 26.0 | +| Viewpoint | `View.chart3DPose(_:)` (takes `Binding`), `Chart3DPose(azimuth:inclination:)` and presets `front`, `back`, `left`, `right`, `top`, `bottom`, `default` | 26.0 (`chart3DPose` also visionOS) | +| Projection | `View.chart3DCameraProjection(_:)` with `Chart3DCameraProjection` (default `.automatic`) | 26.0 (not visionOS) | +| Styling | `Chart3DSymbolShape` / `BasicChart3DSymbolShape`, `Chart3DSurfaceStyle` / `BasicChart3DSurfaceStyle` | 26.0 | +| Z axis | `View.chartZAxisLabel(_:position:alignment:spacing:)` | 26.0 | + +iOS 27 fix (release notes, radar 174168981): with a deployment target below 27.0, conditionals inside a `Chart` closure warned that `_ConditionalContent` conformance to `ChartContent` is only available in 27.0 and "the app might crash at runtime when that content is loaded". With such a target, test any `if`/`else` inside a chart builder on an older OS before shipping. + +```swift +import Charts +import SwiftUI + +struct Penguin: Identifiable { + let id: Int + let flipperLength: Double + let weight: Double + let beakLength: Double +} + +struct PenguinChart: View { + let penguins: [Penguin] + @State private var pose = Chart3DPose.default + + var body: some View { + Chart3D(penguins) { + PointMark( + x: .value("Flipper Length (mm)", $0.flipperLength), + y: .value("Weight (kg)", $0.weight), + z: .value("Beak Length (mm)", $0.beakLength)) + } + .chart3DPose($pose) + } +} + +struct WaveSurface: View { + var body: some View { + Chart3D { + SurfacePlot(x: "x", y: "y", z: "z") { x, z in + sin(2 * x) * cos(2 * z) + } + } + } +} +``` + +The `Chart3D { SurfacePlot ... }` and `Chart3D(penguins) { PointMark ... }` shapes are Apple's own examples on the `Chart3D` page; `chart3DPose($pose)` follows the verified modifier signature. Add an accessibility label and a non-visual summary of the data: [hig-accessibility.md](../../swiftui-core/references/hig-accessibility.md). diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/cloudkit.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/cloudkit.md new file mode 100644 index 0000000..988cfab --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/cloudkit.md @@ -0,0 +1,78 @@ +--- +name: cloudkit +description: CloudKit sync with CKSyncEngine and share access requests (CKShareRequestAccessOperation), plus how CloudKit relates to SwiftData and Core Data mirroring +when-to-use: building custom iCloud sync, handling shared records, deciding between CKSyncEngine, SwiftData CloudKit sync and NSPersistentCloudKitContainer +keywords: CKSyncEngine, CKSyncEngineDelegate, CKShareRequestAccessOperation, CKShare, CKRecordZone, stateSerialization, iCloud +priority: medium +related: ../SKILL.md, core-data.md, ../../swiftui-core/references/data-swiftdata.md +--- + +# CloudKit + +Sources, read 2026-11-13: CloudKit landing page https://developer.apple.com/documentation/cloudkit (JSON `.../tutorials/data/documentation/cloudkit.json`); CloudKit has no framework updates page (404); symbol pages `.../documentation/cloudkit/.json`; iOS 27 release notes (CloudKit "Resolved Issues"). + +## Choose the route + +| Route | Use when | +|-------|----------| +| SwiftData with CloudKit | New app on SwiftData: [data-swiftdata.md](../../swiftui-core/references/data-swiftdata.md) | +| `NSPersistentCloudKitContainer` | Existing Core Data store: [core-data.md](core-data.md) | +| `CKSyncEngine` | Own persistence layer, custom record mapping | +| Raw `CKContainer` / `CKDatabase` operations | One-off reads, sharing flows | + +Apple's landing page lists "Deciding whether CloudKit is right for your app" and "Enabling CloudKit in your app" as the starting articles: read them for the iCloud capability and container setup. + +## Symbols + +| Need | Symbol | Availability | +|------|--------|--------------| +| Sync engine | `CKSyncEngine(_:)` with `CKSyncEngine.Configuration(database:stateSerialization:delegate:)` | 17.0, macOS 14.0 | +| Delegate | `CKSyncEngineDelegate`: `handleEvent(_:syncEngine:)`, `nextRecordZoneChangeBatch(_:syncEngine:)`, `nextFetchChangesOptions(_:syncEngine:)` | 17.0 | +| Queue local changes | `engine.state.add(pendingRecordZoneChanges:)`, `add(pendingDatabaseChanges:)` | 17.0 | +| Manual sync | `fetchChanges(_:)`, `sendChanges(_:)`, `cancelOperations()` | 17.0 | +| Events | `CKSyncEngine.Event`: `stateUpdate`, `accountChange`, `fetchedDatabaseChanges`, `fetchedRecordZoneChanges`, `sentDatabaseChanges`, `sentRecordZoneChanges` | 17.0 | +| Ask the owner for access to a share | `CKShareRequestAccessOperation(shareURLs:)` with `perShareAccessRequestResultBlock` (`(URL, Result) -> Void`) and `shareAccessRequestResultBlock` | 26.0, all platforms | + +`CKShareRequestAccessOperation` is a new operation class listed under "Classes" on the CloudKit landing page; the symbol page has no abstract, so confirm behavior with a two-account test before shipping. + +## CKSyncEngine rules + +- Persist the engine state: on the `stateUpdate` event, write `CKSyncEngine.State.Serialization` to disk and pass it back as `stateSerialization` at the next launch. Without it the engine refetches everything. +- You own the local store: the engine tells you what changed (`fetchedRecordZoneChanges`) and asks for what to send (`nextRecordZoneChangeBatch`); it does not persist records. +- Handle `accountChange` (sign-out, account switch): clear or re-associate local data deliberately. +- iOS 27 fix (release notes): saving a `CKShare` where an administrator participant demotes themselves to `CKShareParticipantRole.privateUser` previously had no effect (radar 177621316). + +```swift +import CloudKit + +final class SyncCoordinator: CKSyncEngineDelegate, @unchecked Sendable { + private(set) var engine: CKSyncEngine! + + init(database: CKDatabase, savedState: CKSyncEngine.State.Serialization?) { + let configuration = CKSyncEngine.Configuration( + database: database, stateSerialization: savedState, delegate: self) + engine = CKSyncEngine(configuration) + } + + func handleEvent(_ event: CKSyncEngine.Event, syncEngine: CKSyncEngine) async { + switch event { + case .stateUpdate(let update): + save(update.stateSerialization) // persist to disk + case .fetchedRecordZoneChanges(let changes): + apply(changes) // write to your local store + default: + break + } + } + + func nextRecordZoneChangeBatch(_ context: CKSyncEngine.SendChangesContext, + syncEngine: CKSyncEngine) async -> CKSyncEngine.RecordZoneChangeBatch? { + nil // build a batch from pending changes + } + + private func save(_ state: CKSyncEngine.State.Serialization) {} + private func apply(_ changes: CKSyncEngine.Event.FetchedRecordZoneChanges) {} +} +``` + +`CKSyncEngine.Event.StateUpdate.stateSerialization` (17.0), `FetchedRecordZoneChanges.modifications` / `deletions`, `RecordZoneChangeBatch(pendingChanges:recordProvider:)` and `SendChangesContext.reason` / `options` were read on their symbol pages. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/core-data.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/core-data.md new file mode 100644 index 0000000..c2eef04 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/core-data.md @@ -0,0 +1,60 @@ +--- +name: core-data +description: Core Data today - when to keep it next to SwiftData, CloudKit mirroring with NSPersistentCloudKitContainer, persistent history, staged migrations, and async contexts +when-to-use: maintaining an existing Core Data store, deciding whether to migrate to SwiftData, adding CloudKit sync or history tracking to Core Data, migrating a model that lightweight migration cannot handle +keywords: NSPersistentContainer, NSPersistentCloudKitContainer, NSStagedMigrationManager, persistent history, NSPersistentHistoryTrackingKey, perform(schedule:), SwiftData coexistence +priority: medium +related: ../SKILL.md, cloudkit.md, ../../swiftui-core/references/data-swiftdata.md +--- + +# Core Data + +Sources, read 2026-11-13: Core Data landing page https://developer.apple.com/documentation/coredata (JSON `.../tutorials/data/documentation/coredata.json`); Core Data has no framework updates page (404) and no new API in the 2025-2026 notes read; the article "Adopting SwiftData for a Core Data app" is dated iOS 27.0 / Xcode 27.0. + +## Decision + +| Situation | Choice | +|-----------|--------| +| New app | SwiftData ([data-swiftdata.md](../../swiftui-core/references/data-swiftdata.md)) | +| Existing Core Data app, no pressing need | Stay on Core Data | +| Moving gradually | Coexist: Apple's sample "Adopting SwiftData for a Core Data app" has three versions (Core Data, full SwiftData conversion, and a Core Data app with a widget extension that uses SwiftData over a shared App Group container) | +| Full conversion | Mirror entity names, properties and relationships one model file per entity; the sample uses `@Model`, `#Index`, `#Unique`, `ModelContainer` | + +## Symbols (read on `documentation/coredata/.json`) + +| Need | Symbol | Availability | +|------|--------|--------------| +| Stack | `NSPersistentContainer` | 10.0 | +| CloudKit mirroring | `NSPersistentCloudKitContainer` (articles: mirroring a store with CloudKit, sharing objects between iCloud users) | 13.0 | +| Track changes across processes | store option `NSPersistentHistoryTrackingKey`, `NSPersistentStoreRemoteChangeNotificationPostOptionKey` set through `NSPersistentStoreDescription.setOption(_:forKey:)`; `NSPersistentHistoryChangeRequest` | 11.0 / 13.0 | +| Migrations beyond lightweight | `NSStagedMigrationManager` (article "staged-migrations": splits an incompatible migration into ordered compatible stages, with hooks before and after each stage) | 17.0 | +| Async context work | `NSManagedObjectContext.perform(schedule:_:)` (`async rethrows`, `ScheduledTaskType` default `.immediate`) | 15.0 | + +## Rules + +- Not every Core Data object is thread safe: a private queue context is reached only through `perform` / `performAndWait`; hand a managed object to another queue as its `NSManagedObjectID` (Apple, "Using Core Data in the background"). `NSManagedObjectContext` conforms to `Sendable`; `NSManagedObject` does not (its page lists no `Sendable`). +- Heavy imports (JSON to Core Data) go to a private queue context, never the main queue (same article). +- Enable history tracking and remote-change notifications on the store description before `loadPersistentStores`; the "persistent-history" and "consuming-relevant-store-changes" articles on the landing page cover consuming the transactions. +- Optional-to-required attribute changes need a staged migration (Apple's example: lightweight migration cannot infer the default for existing `nil` values). +- For CloudKit use one route per store: `NSPersistentCloudKitContainer` mirroring or your own `CKSyncEngine` mapping ([cloudkit.md](cloudkit.md)). + +```swift +import CoreData + +let container = NSPersistentContainer(name: "Model") +if let description = container.persistentStoreDescriptions.first { + description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) + description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) +} +container.loadPersistentStores { _, error in + if let error { assertionFailure("Store failed: \(error)") } +} + +func count(in context: NSManagedObjectContext) async throws -> Int { + try await context.perform { + try context.count(for: NSFetchRequest(entityName: "Trip")) + } +} +``` + +`context.perform { }` returning a value with `try` is the async form of `perform(schedule:_:)`; `Trip` is your entity name. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/healthkit.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/healthkit.md new file mode 100644 index 0000000..dca0be5 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/healthkit.md @@ -0,0 +1,59 @@ +--- +name: healthkit +description: HealthKit on iOS - workout sessions on iPhone and iPad, medications and dose events, workout zones (heart rate and cycling power, iOS 27), and the limited-history permission flow +when-to-use: building a workout app on iPhone, reading medications and doses, showing time-in-zone or live zone changes, handling a person who granted only recent history +keywords: HKWorkoutSession, HKLiveWorkoutBuilder, HKUserAnnotatedMedicationQueryDescriptor, HKMedicationDoseEvent, HKWorkoutZoneGroup, HKWorkoutZoneConfiguration, preferredWorkoutZoneConfiguration, getEarliestAuthorizedSampleDate, requestPerObjectReadAuthorization +priority: medium +related: ../SKILL.md, ../../watchos/references/workouts.md +--- + +# HealthKit (iOS) + +Sources, read 2026-11-13: HealthKit updates page https://developer.apple.com/documentation/updates/healthkit (June 2025, June 2026); WWDC25 sessions 322 "Track workouts with HealthKit on iOS and iPadOS" and 321 "Meet the HealthKit Medications API"; WWDC26 session 207 "Deliver workout insights with HealthKit workout zones" (https://developer.apple.com/videos/play/wwdc2026/207/); article https://developer.apple.com/documentation/healthkit/authorizing-access-to-health-data; symbol pages `.../tutorials/data/documentation/healthkit/.json`. Watch-side workouts: [workouts.md](../../watchos/references/workouts.md). + +## Workout sessions on iOS and iPadOS (iOS 26.0) + +`HKLiveWorkoutBuilder` and `HKLiveWorkoutBuilderDelegate` are iOS/iPadOS/Mac Catalyst 26.0 (watchOS 5.0); `HKHealthStore.recoverActiveWorkoutSession` iOS 26.0; `HKWorkoutSession` iOS 17.0. Apple's sample guides: "Building a workout app for iPhone and iPad", "Building a multidevice workout app". + +Session 322 flow: configure `HKWorkoutConfiguration` (`activityType`, `locationType`), create `HKWorkoutSession(healthStore:configuration:)`, take `associatedWorkoutBuilder()`, set `builder.dataSource = HKLiveWorkoutDataSource(...)`, `session.prepare()`, then `session.startActivity(with:)` and `try await builder.beginCollection(at:)`. Read live values in `workoutBuilder(_:didCollectDataOf:)` through `builder.statistics(for:)`. End: `session.stopActivity(with:)`, wait for `.stopped` in the session delegate, `endCollection(at:)`, `finishWorkout()`, `session.end()`. + +**Crash recovery** (session 322): in `application(_:configurationForConnecting:options:)`, if `options.shouldHandleActiveWorkoutRecovery` (iOS 26.0) call `store.recoverActiveWorkoutSession()` (`async throws -> HKWorkoutSession?`), then rebuild delegates, builder and data source from the recovered session. Siri workout intents (`INStartWorkoutIntent` handlers) are covered in the session. + +## Medications (iOS 26.0; the per-object authorization calls date from iOS 16.0) + +| Need | Symbol | +|------|--------| +| Medication object | `HKUserAnnotatedMedication` (`isArchived`, `hasSchedule`, `nickname`, `medication`) with `HKMedicationConcept` (`identifier`, display text, general form, `relatedCodings` such as RxNorm) | +| Dose | `HKMedicationDoseEvent`, an `HKSample` tied to a concept identifier; log status taken, skipped, snoozed or not interacted; scheduled date and quantity | +| Fetch medications | `HKUserAnnotatedMedicationQueryDescriptor(predicate:limit:)` (predicates for archived and scheduled) | +| Fetch doses | any sample query with the `HKMedicationDoseEvent` sample type, including `HKAnchoredObjectQuery` and its async stream | +| Authorize | per-object: `HKUserAnnotatedMedicationType` via `HKObjectType.userAnnotatedMedicationType()`, `requiresPerObjectAuthorization()`, `requestPerObjectReadAuthorization(for:predicate:)` (`async throws`) | + +Session 321 rules: authorizing a medication also grants its dose events, no separate request; people can add a newly created medication to your app from inside Health; with anchored queries expect backdated, deleted and re-persisted dose events and unattended scheduled doses (handle deletions, keep the returned anchor). Available on iOS, iPadOS, visionOS, per the session intro. + +## Workout zones (iOS 27.0, iPadOS, watchOS 27.0; macOS and visionOS symbols exist) + +| Need | Symbol | +|------|--------| +| Zones of a finished workout | `HKWorkout.zoneGroupsByType` / `HKWorkoutActivity.zoneGroupsByType` (`[HKQuantityType : HKWorkoutZoneGroup]?`), key `HKQuantityType(.heartRate)` or cycling power | +| Group content | `HKWorkoutZoneGroup.configuration` (`HKWorkoutZoneConfiguration`: `quantityType`, `zones`, `source` = `system`, `user`, `app`) and `zoneDurations` (`HKWorkoutZoneDuration`) | +| Live updates | `HKLiveWorkoutBuilderDelegate.workoutBuilder(_:didUpdateWorkoutZone:)` with `HKLiveWorkoutZoneUpdate` (`currentZoneDuration`, `previousZoneDuration`, `zoneGroup`, `lastSampleProcessedDate`); sent only when the zone changes; not on macOS | +| Person's zones | `HKHealthStore.preferredWorkoutZoneConfiguration(for:)` and `HKWorkoutBuilder.zoneConfiguration(for:)` (both `async throws`, optional result) | +| Custom zones | `HKWorkoutZoneConfiguration(quantityType:zoneBoundaries:)` (throws), `HKWorkoutBuilder.setCustomZoneConfiguration(_:for:)` | + +Rules (session 207): zones are contiguous and non-overlapping, first zone has no lower bound and last none upper; custom boundaries need compatible units and **3 to 9 zones**; set the custom configuration **before** `beginCollection`; HealthKit does not persist custom configurations (your app saves and syncs them); zone counts differ between workouts (cycling power defaults to 6, apps use 5 to 8), so normalize before comparing time-in-zone across workouts; request authorization for workouts and the quantity type first. + +```swift +let heartRate = HKQuantityType(.heartRate) +if try await builder.zoneConfiguration(for: heartRate) == nil { + let bpm = HKUnit.count().unitDivided(by: HKUnit.minute()) + let boundaries = [91.0, 114.0, 136.0, 158.0].map { HKQuantity(unit: bpm, doubleValue: $0) } + let config = try HKWorkoutZoneConfiguration(quantityType: heartRate, zoneBoundaries: boundaries) + try await builder.setCustomZoneConfiguration(config, for: heartRate) +} +try await builder.beginCollection(at: Date()) +``` + +## Limited-history permission (iOS 27.0) + +iOS 27 notes: "Updated HealthKit permissions flow now lets users grant apps access to limited history or full history" (radar 172310874). Apple's authorization article: after the data-type screen a second screen chooses a recent window or full history; the limit applies to sample types only. `getEarliestAuthorizedSampleDate(for:completion:)` (iOS 27.0) or its async form `earliestAuthorizedSampleDate(for:)` returns the earliest date per type; call it after requesting authorization and start your predicate at that date. HealthKit hides full-access versus denied (both give no entry), so limited authorization is the only state you can positively detect. Do not read missing old samples as "no history". diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/mapkit.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/mapkit.md new file mode 100644 index 0000000..586d870 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/mapkit.md @@ -0,0 +1,45 @@ +--- +name: mapkit +description: MapKit geocoding and addresses (MKGeocodingRequest, MKReverseGeocodingRequest, MKAddress, MKAddressRepresentations) and the native SwiftUI Map +when-to-use: turning text into places or coordinates into addresses, formatting an address for display, choosing between SwiftUI Map and an MKMapView wrapper +keywords: MKGeocodingRequest, MKReverseGeocodingRequest, MKAddress, MKAddressRepresentations, MKMapItem, Map, MapContentBuilder, CLGeocoder +priority: medium +related: ../SKILL.md, ../../ios/references/uikit-integration.md +--- + +# MapKit + +Sources, read 2026-11-13: MapKit updates page https://developer.apple.com/documentation/updates/mapkit (June 2025 entry), symbol pages `developer.apple.com/tutorials/data/documentation/mapkit/.json`. + +## Geocoding and addresses (iOS 26.0) + +| Need | Symbol | Notes | +|------|--------|-------| +| Text to places | `MKGeocodingRequest(addressString:)` (failable init) | `mapItems` (`async throws`) or `getMapItems(completionHandler:)`; `preferredLocale`, `region`, `isLoading`, `cancel()` | +| Coordinates to places | `MKReverseGeocodingRequest(location:)` (failable init, takes `CLLocation`) | Same result API plus `location` | +| Address on a place | `MKMapItem.address` (`MKAddress?`), `MKMapItem.addressRepresentations` (`MKAddressRepresentations?`) | All iOS/iPadOS/macOS/tvOS/watchOS/visionOS 26.0 | +| Raw address strings | `MKAddress.fullAddress`, `shortAddress`; `MKAddress(fullAddress:shortAddress:)` | For place cards and annotations built from an `MKMapItem` | +| Formatted address | `MKAddressRepresentations`: `cityName`, `cityWithContext`, `regionName`, `fullAddress(includingRegion:singleLine:)`, `cityWithContext(_:)` with `ContextStyle` | Controls how much disambiguation is added | +| Cycling | cycling transport type for directions and ETAs (June 2025 updates page) | | + +`CLGeocoder` (Core Location) is deprecated at 26.0 on every platform ("Use MapKit"), and `reverseGeocodeLocation(_:completionHandler:)` says "Use MKReverseGeocodingRequest": use the two request classes above, which return `MKMapItem` with the new address types. + +```swift +import MapKit + +func placeName(for location: CLLocation) async throws -> String? { + guard let request = MKReverseGeocodingRequest(location: location) else { return nil } + let items = try await request.mapItems + return items.first?.addressRepresentations?.cityWithContext(.automatic) +} +``` + +`MKAddressRepresentations.ContextStyle` cases: `automatic`, `short`, `full`; `cityWithContext(_:)` returns `String?`. + +## SwiftUI Map first + +`Map` with `@MapContentBuilder` content and `MapCameraPosition` binding (initializers iOS 17.0, macOS 14.0, watchOS 10.0) covers annotations (`Marker`, `Annotation`, `UserAnnotation`), overlays (`MapCircle`, `MapPolygon`, `MapPolyline`), controls (`MapCompass`, `MapScaleView`, `MapUserLocationButton`), selection (`MapSelection`), `LookAroundPreview` and place detail sheets/popovers (`mapItemDetailSheet`, `mapItemDetailPopover`). Wrap `MKMapView` only for deployments below iOS 17 or behavior with no SwiftUI equivalent: [uikit-integration.md](../../ios/references/uikit-integration.md). + +## Privacy + +Location permission (`CLLocationManager`) is separate from geocoding and needs `NSLocationWhenInUseUsageDescription`; privacy declarations: [privacy-manifest.md](../../build-distribution/references/privacy-manifest.md). diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/metrickit.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/metrickit.md new file mode 100644 index 0000000..e8d2c97 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/metrickit.md @@ -0,0 +1,90 @@ +--- +name: metrickit +description: MetricKit 27 (MetricManager async report sequences, state-contextualized metrics) and the StateReporting framework (StateReporter, ReportableMetadata) for per-feature performance attribution +when-to-use: collecting field performance and diagnostic reports, attributing metrics to app states, migrating from MXMetricManager subscribers +keywords: MetricManager, MetricReport, DiagnosticReport, StateReporter, StateReportingDomain, ReportableMetadata, MXMetricManager, trackLaunchTask +priority: medium +related: ../SKILL.md, background-tasks.md, ../../swift-core/references/performance.md +--- + +# MetricKit and StateReporting + +Sources, read 2026-11-13: https://developer.apple.com/documentation/metrickit (JSON `.../tutorials/data/documentation/metrickit.json`), article "Track performance by app state using MetricKit" and sample, https://developer.apple.com/documentation/statereporting and "Getting started with StateReporting", Apple's June 2026 updates index ("The MetricKit framework is significantly upgraded for the 27 platform releases"). + +## Symbols + +| Need | Symbol | Availability | +|------|--------|--------------| +| Receive reports | `MetricManager` (`final class`): `metricReports` (`some AsyncSequence`, daily), `diagnosticReports` (`some AsyncSequence`, individual events) | iOS/iPadOS/Mac Catalyst/macOS 27.0 (`diagnosticReports` also visionOS) | +| Enable state domains | `MetricManager(enabledStateReportingDomains: Set)`; `StateReportingDomain` is `ExpressibleByStringLiteral` (`rawValue` gives the string) | 27.0 | +| Custom metric logs | `MetricManager.logHandle(category:)` | 27.0 | +| Extended launch tracking | `trackLaunchTask(id:onTrackingError:_:)`, `LaunchTaskID` | 27.0 | +| State attached to entries | `MetricManager.ReportedState` (`domain`, `label`, `duration`, `stableMetadata`); `MetricReport.stateEntries`, `intervalEntries`, `timeRange` | 27.0 | +| Encode by domain | `MetricReport.encodingFormatKey` with `EncodingFormat.byStateReportingDomain` in `JSONEncoder.userInfo` | 27.0 | +| Record states | `StateReporter.reporter(for:stableMetadata:volatileMetadata:)`, `reportTransition(to:stableMetadata:volatileMetadata:)`, `reportVolatileMetadataUpdate(_:)` | StateReporting 27.0, all platforms incl. tvOS and watchOS | +| Metadata types | `ReportableMetadata` protocol with macros `@ReportableMetadata`, `@ReportableMetadataKey(_:)`, `@ReportableMetadataIgnored` | 27.0 | +| Legacy | `MXMetricManager.shared`, `add(_:)` subscriber, `pastPayloads`, `pastDiagnosticPayloads`, `makeLogHandle(category:)` | iOS 13.0, macOS 12.0; **deprecated** (27.3 on iOS, iPadOS, macOS, visionOS; 27.0 on Mac Catalyst): "Use MetricManager instead" | + +MetricKit does not deliver reports on simulated devices: test on a device running iOS 27 (Apple's sample requirements). + +## WWDC26 session 222 "Meet the new MetricKit" (https://developer.apple.com/videos/play/wwdc2026/222/, transcript and code read 2026-11-13) + +- The framework is rebuilt "from the ground up" as a Swift-first API; every advance below is exclusive to it (the `MX*` classes are the old API). +- Create `MetricManager` at app start and keep it alive: subscribing late loses data, and the streams keep delivering as later data becomes ready. Run the listening loop in a detached task or a dedicated service class. +- A `MetricReport` covers one day: a full-day entry plus smaller breakdown entries (a few hours each, only when they hold metrics); `intervalEntries.fullDayEntry`, entries hold `values` grouped by `metricGroup` (`.cpu`, `.memory`, `.display`, `.gpu`), cases like `.peakMemory(_)`. Reports and diagnostics are `Codable`: `JSONEncoder().encode(report)` for the server. +- Diagnostics arrive immediately: `report.result` is `.crash(let crash)` (`callStackTree`, `terminationReason`, `terminationCategory` new in iOS 27, tells how the crash was counted in metrics), `.hang(_)`, and new in iOS 27 memory exception diagnostics (app or extension killed for exceeding its memory limit). New metric: Metal frame rate. +- Metrics can be provided per app state: hang time intersected with "tab 1", "tab 2", "tab 3". `MetricReport.EncodingFormat.byStateReportingDomain` (set through `encoder.userInfo[MetricReport.encodingFormatKey]`) encodes by domain. +- Analysis happens on your server: aggregate across devices by your own dimensions; Apple supplies collection only. + +## StateReporting rules (Apple's article) + +- A domain is a reverse-DNS string for one functional area (`com.myapp.checkout`); keep it stable across versions, changing it starts a new data series. +- At most one state is active per domain; keep labels few and fixed ("Low", "High"). Dynamic values go in volatile metadata, never in the label or stable metadata (each unique combination is aggregated separately). +- `reporter(for:...)` returns the same instance per domain; calling it again with different metadata types crashes at runtime. Store the reporter in a long-lived object. +- Call `reportTransition` at human-interaction timescales (tap, navigation, start of an activity); there is a rate limit and data is dropped on per-frame calls. A `nil` label clears the state; an empty string is a fatal error. +- Extensions: reporters work there, but metric data is not available for extensions, so their transitions are not in a `MetricReport`; they do appear in diagnostic reports. The extension must create its own `MetricManager` with the domains it uses. + +```swift +import MetricKit +import StateReporting + +@ReportableMetadata +struct CheckoutStable { let paymentMethod: String } + +@ReportableMetadata +struct CheckoutVolatile { let cartItems: Int } + +extension StateReportingDomain { + static let checkout: StateReportingDomain = "com.example.app.checkout" +} + +@MainActor +final class MetricsCollector { + private let manager = MetricManager(enabledStateReportingDomains: [.checkout]) + private let checkout = StateReporter.reporter( + for: StateReportingDomain.checkout.rawValue, + stableMetadata: CheckoutStable.self, + volatileMetadata: CheckoutVolatile.self) + + func startListening() { + Task { + for await report in manager.metricReports { upload(report) } + } + Task { + for await diagnostic in manager.diagnosticReports { upload(diagnostic) } + } + } + + func beganPaying(method: String, items: Int) { + checkout.reportTransition( + to: "Paying", + stableMetadata: CheckoutStable(paymentMethod: method), + volatileMetadata: CheckoutVolatile(cartItems: items)) + } + + private func upload(_ report: MetricReport) {} + private func upload(_ report: DiagnosticReport) {} +} +``` + +The `StateReporter.reporter(for:...)` call shape, `MetricManager(enabledStateReportingDomains:)` and the `for await` loops follow Apple's article and sample; the sample code here has not been compiled against the Xcode 27 SDK. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/tipkit.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/tipkit.md new file mode 100644 index 0000000..472fdbc --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/tipkit.md @@ -0,0 +1,72 @@ +--- +name: tipkit +description: TipKit - tips, display rules (parameters and events), tip groups, configuration (datastore, display frequency, CloudKit sync) and testing +when-to-use: teaching a feature with an inline tip or popover, showing a tip only after a condition, sequencing several tips, syncing tip state across devices +keywords: Tip, TipView, popoverTip, Tips.configure, Parameter, Rule, Tips.Event, TipGroup, MaxDisplayCount, cloudKitContainer, displayFrequency +priority: medium +related: ../SKILL.md, ../../swiftui-core/references/hig-modality.md +--- + +# TipKit + +Sources, read 2026-11-13: https://developer.apple.com/documentation/tipkit (JSON `.../tutorials/data/documentation/tipkit.json`), sample "Highlighting app features with TipKit" (iOS 18.0, Xcode 16.0), TipKit updates page (latest entry June 2024). Newer symbols exist without an updates entry: `Tip.resetEligibility()` (`async`, iOS 26.0) and `Tips.DonationLimit` (26.0), per their symbol pages. + +## Symbols (all available iOS 17.0, macOS 14.0, tvOS 17.0, visionOS 1.0, watchOS 10.0 unless noted) + +| Need | Symbol | +|------|--------| +| Define a tip | `protocol Tip`: `title`, `message`, `image`, `actions`, `rules`, `options`, `status`, `shouldDisplay`, `invalidate(reason:)`, `resetEligibility()` (26.0, `async`) | +| Show it | `TipView(_:arrowEdge:action:)` (inline, preferred: "doesn't obscure or hide any underlying UI"); `View.popoverTip(_:arrowEdge:action:)`; UIKit `TipUIView`, `TipUIPopoverViewController`; AppKit `TipNSView`, `TipNSPopover` | +| Configure once at launch | `try Tips.configure([...])` with `Tips.ConfigurationOption`: `datastoreLocation(_:)`, `displayFrequency(_:)`, `cloudKitContainer(_:)` (June 2024: sync tips, rules, parameters and events across devices) | +| Rules | `@Tips.RuleBuilder var rules: [Rule]`; `@Parameter` static state with `#Rule(Self.$flag) { $0 == true }`; `Tips.Event(id:)` with `donate()` | +| Display limits | `Tips.MaxDisplayCount`, `MaxDisplayDuration` (June 2024), `IgnoresDisplayFrequency` as tip `options` | +| Ordered tips | `TipGroup(_:_:)` (iOS 18.0, macOS 15.0, watchOS 11.0, visionOS 2.0) with `currentTip`; `TipGroup.Priority` | +| Style | `tipViewStyle(_:)`, `TipViewStyle`, `MiniTipViewStyle` | +| Testing | `Tips.showAllTipsForTesting()`, `showTipsForTesting(_:)`, `hideAllTipsForTesting()`, `hideTipsForTesting(_:)`, `resetDatastore()` | + +## Rules of use + +- Call `Tips.configure()` once, before any `TipView` renders (Apple's sample does it in the `App` initializer). +- Invalidate a tip when the person does the thing it teaches: `tip.invalidate(reason: .actionPerformed)`. +- HIG guidance on tips and onboarding: [hig-modality.md](../../swiftui-core/references/hig-modality.md). +- `@Parameter(.transient)` resets the value to its default the first time it is referenced (comment in Apple's sample). + +```swift +import SwiftUI +import TipKit + +struct FavoriteTip: Tip { + @Parameter static var isLoggedIn: Bool = false + + var title: Text { Text("Save as a Favorite") } + var message: Text? { Text("Your favorites always appear at the top of the list.") } + var image: Image? { Image(systemName: "star") } + + var rules: [Rule] { + #Rule(Self.$isLoggedIn) { $0 == true } + } +} + +@main +struct DemoApp: App { + init() { + do { try Tips.configure() } catch { print("TipKit: \(error)") } + } + var body: some Scene { WindowGroup { ListScreen() } } +} + +struct ListScreen: View { + private let tip = FavoriteTip() + + var body: some View { + VStack { + TipView(tip, arrowEdge: .bottom) + Button("Favorite", systemImage: "star") { + tip.invalidate(reason: .actionPerformed) + } + } + } +} +``` + +Structure follows Apple's sample (`InlineTip`, `ParameterRuleTip`, `Tips.configure()`); `ListScreen` and `DemoApp` are illustrative and not compiled against the SDK here. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/user-notifications.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/user-notifications.md new file mode 100644 index 0000000..0a835ab --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-frameworks/references/user-notifications.md @@ -0,0 +1,67 @@ +--- +name: user-notifications +description: UserNotifications - asking permission in context, provisional authorization, checking status, scheduling local notifications, foreground presentation, interruption levels, badge count, and the iOS 27 critical-alert fix +when-to-use: adding local or remote notification support, deciding when to ask permission, showing a notification while the app is open, setting the badge +keywords: UNUserNotificationCenter, requestAuthorization, provisional, UNNotificationRequest, UNUserNotificationCenterDelegate, willPresent, UNNotificationInterruptionLevel, setBadgeCount, criticalAlert +priority: medium +related: ../SKILL.md, ../../swiftui-core/references/hig-system-surfaces.md +--- + +# UserNotifications + +Sources, read 2026-11-13: https://developer.apple.com/documentation/usernotifications (article "Asking permission to use notifications"), symbol pages `.../tutorials/data/documentation/usernotifications/.json`, iOS 27 release notes (Notifications), UserNotifications updates page (latest entry June 2024). HIG notifications guidance: [hig-system-surfaces.md](../../swiftui-core/references/hig-system-surfaces.md). + +## Symbols (iOS 10.0 / macOS 10.14 unless noted) + +| Need | Symbol | +|------|--------| +| Center | `UNUserNotificationCenter.current()` | +| Ask permission | `requestAuthorization(options:)` (`async throws -> Bool`); `UNAuthorizationOptions`: `alert`, `badge`, `sound`, `carPlay`, `criticalAlert`, `providesAppNotificationSettings`, `provisional` (`timeSensitive` and `announcement` are Deprecated options) | +| Read status | `notificationSettings()` (`async`), `UNNotificationSettings.authorizationStatus`: `notDetermined`, `denied`, `authorized`, `provisional`, `ephemeral` | +| Schedule | `UNMutableNotificationContent`, `UNTimeIntervalNotificationTrigger(timeInterval:repeats:)`, `UNNotificationRequest(identifier:content:trigger:)`, `add(_:)` (`async throws`) | +| Foreground display | `UNUserNotificationCenterDelegate.userNotificationCenter(_:willPresent:)` (`async -> UNNotificationPresentationOptions`: `banner` (14.0), `list`, `sound`, `badge`) | +| Interruption | `UNMutableNotificationContent.interruptionLevel` (15.0): `passive`, `active`, `timeSensitive`, `critical` | +| Badge | `setBadgeCount(_:)` (`async throws`, iOS 16.0, macOS 13.0) | +| Manage | `getPendingNotificationRequests`, `removePendingNotificationRequests(withIdentifiers:)`, `removeDeliveredNotifications(withIdentifiers:)` | + +## Rules (Apple's article) + +- Ask in context, not at first launch: after the person schedules a first task, say. The first request prompts; later requests do not. +- Provisional authorization (`.provisional` added to the options) grants authorization without a prompt; notifications arrive quietly in Notification Center history with Keep and Turn Off buttons. It permits asking at first launch. The status stays `provisional` until the person chooses. +- Always check the status before scheduling local notifications: people change it at any time. +- iOS 27 note (radar 179179362): critical alerts were being turned on automatically for apps that request notification permission; fixed. Request `.criticalAlert` only for genuinely critical alerts. + +```swift +import UserNotifications + +@MainActor +final class Reminders: NSObject, UNUserNotificationCenterDelegate { + private let center = UNUserNotificationCenter.current() + + func configure() { + center.delegate = self + } + + func schedule(_ title: String, in seconds: TimeInterval) async throws { + let settings = await center.notificationSettings() + if settings.authorizationStatus == .notDetermined { + _ = try await center.requestAuthorization(options: [.alert, .sound, .badge]) + } + let status = await center.notificationSettings().authorizationStatus + guard status == .authorized || status == .provisional else { return } + + let content = UNMutableNotificationContent() + content.title = title + content.interruptionLevel = .active + let trigger = UNTimeIntervalNotificationTrigger(timeInterval: seconds, repeats: false) + try await center.add(UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)) + } + + nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, + willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { + [.banner, .list, .sound] + } +} +``` + +Samples are not compiled against the SDK here; the `async` forms of `requestAuthorization`, `add` and `notificationSettings()` and the `willPresent` async declaration were read on their symbol pages. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/SKILL.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/SKILL.md new file mode 100644 index 0000000..da454df --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/SKILL.md @@ -0,0 +1,109 @@ +--- +name: apple-intelligence +description: Use when adding Apple Intelligence features to an Apple-platform app — Foundation Models framework (on-device and Private Cloud Compute language models, guided generation, tools), Writing Tools, Genmoji, Image Playground, Visual Intelligence — or when choosing between them and App Intents / Siri AI. +versions: + foundation-models: 27 + ios: 27.2 +user-invocable: false +references: references/foundation-models.md, references/foundation-models-generation.md, references/foundation-models-pcc.md, references/system-features.md, references/design-guidance.md +related-skills: swiftui-core, swift-core, solid-swift, ios, macos, ipados, watchos, visionos, tvos +--- + + +Covers the Apple Intelligence surface a third-party app can adopt, verified against Apple's documentation JSON on 2026-11-13: the Foundation Models framework (SystemLanguageModel on device, PrivateCloudComputeLanguageModel on server, LanguageModelSession, @Generable guided generation, Tool calling, streaming, multimodal prompts, dynamic profiles, errors and availability), the system features (Writing Tools, Genmoji via NSAdaptiveImageGlyph, Image Playground, Visual Intelligence), and the HIG generative-AI rules. + +A decision table routes each need to the right framework. App Intents, app schemas and Siri AI are already covered by `swiftui-core/references/app-intents.md` and `hig-system-surfaces.md`; this skill links to them instead of repeating them. + + +# Apple Intelligence + +Apple Intelligence integration for iOS, iPadOS, macOS, visionOS, watchOS and tvOS apps. + +## Agent Workflow (MANDATORY) + +Before ANY implementation, delegate via `Task` — spawn 3 agents in parallel (single message, 3 `Task` calls): + +1. **fuse-ai-pilot:explore-codebase** - Find existing Foundation Models, Writing Tools and App Intents usage +2. **fuse-ai-pilot:research-expert** - Re-verify every symbol on its Apple JSON page (`https://developer.apple.com/tutorials/data/documentation/.json`); the apple-docs MCP search is unreliable, never conclude absence from it +3. **mcp__apple-docs__search_apple_docs** - Cross-check only; confirm availability on the JSON page + +After implementation, run **fuse-ai-pilot:sniper** for validation. + +--- + +## Overview + +### When to Use + +- Generating, summarizing, extracting or classifying text with a language model +- Getting typed Swift output from a model (`@Generable`) or letting it call app code (`Tool`) +- Prompting with images, or routing hard requests to Private Cloud Compute +- Supporting Writing Tools, Genmoji or Image Playground in text and image UI +- Surfacing app content in Visual Intelligence search + +### Decision table + +| Need | Use | Reference | +|------|-----|-----------| +| Text generation or understanding inside your own feature, offline, private | `SystemLanguageModel` + `LanguageModelSession` | [foundation-models.md](references/foundation-models.md) | +| Typed output, tool calling, streaming, images in prompts | `@Generable`, `Tool`, `streamResponse`, `Attachment` | [foundation-models-generation.md](references/foundation-models-generation.md) | +| Long documents or deeper reasoning (32K context, reasoning levels) | `PrivateCloudComputeLanguageModel` (iOS 27+, entitlement, daily quota) | [foundation-models-pcc.md](references/foundation-models-pcc.md) | +| Users rewrite, proofread, summarize their own text | Writing Tools (free in standard text views) | [system-features.md](references/system-features.md) | +| Custom emoji inside text | Genmoji (`NSAdaptiveImageGlyph` for custom text engines) | [system-features.md](references/system-features.md) | +| Users create images in your app | Image Playground sheet or view controller | [system-features.md](references/system-features.md) | +| Camera or screenshot search that shows your content | Visual Intelligence (`IntentValueQuery`) | [system-features.md](references/system-features.md) | +| Siri AI, Spotlight semantic index, Shortcuts, on-screen awareness | App Intents + schemas, not the model APIs | `swiftui-core/references/app-intents.md`, `swiftui-core/references/hig-system-surfaces.md` | +| Bring your own or open-source model behind the same API | `LanguageModel` protocol, Core AI | [foundation-models-pcc.md](references/foundation-models-pcc.md) | +| UX rules: transparency, refine/undo, feedback, safety | HIG generative AI | [design-guidance.md](references/design-guidance.md) | + +Rule of thumb from Apple: start on-device, evaluate with the Evaluations framework, move to Private Cloud Compute only when the feature needs more reasoning or context. + +--- + +## Critical Rules + +1. **Check availability first.** `SystemLanguageModel.default.availability` (or `isAvailable`) before any UI that depends on it; always ship a non-AI fallback ([HIG](references/design-guidance.md)). +2. **Switch on `availability` with `@unknown default`.** Reasons can be added later. +3. **One request per session at a time.** A second call before the first finishes is a runtime error; check `isResponding`. +4. **Gate by OS.** FoundationModels starts at 26.0; `PrivateCloudComputeLanguageModel`, `Attachment`, `LanguageModelError`, dynamic profiles start at 27.0. Use `#available`, newest first. +5. **Private Cloud Compute needs the `com.apple.developer.private-cloud-compute` entitlement.** Without it the app crashes on the first prompt, even though `availability` says available. +6. **Never trust model output blindly.** Constrain it with `@Generable` enums/ranges, handle `guardrailViolation` and `refusal`, keep instructions to trusted content. +7. **Do not use the on-device model for** basic math, code generation or logical reasoning (Apple's own list). +8. **Localize.** Prompts, `@Guide` descriptions and UI text go through String Catalogs; check `supportsLocale()` before calling the model. + +--- + +## Privacy + +| Path | Where data goes | Source | +|------|-----------------|--------| +| `SystemLanguageModel` | Stays on device, works offline | Foundation Models overview | +| `PrivateCloudComputeLanguageModel` | Apple's Private Cloud Compute; network required; Apple states it preserves privacy | PCC article | +| Image Playground (27) | Apple pages disagree: the 27-era overview and What's New say images are generated on Private Cloud Compute; the Get Started page still says on device. Treat as PCC and disclose it | see system-features.md | +| Third-party `LanguageModel` providers | Provider's policy; HIG: get to know their privacy features before sending photos or personal data | Safety article | + +HIG: ask permission before using personal information, minimize what is sent, tell people when data may leave the device ([design-guidance.md](references/design-guidance.md)). + +--- + +## Reference Guide + +| Need | Reference | +|------|-----------| +| Availability, model variants, sessions, prompting, context window, errors, safety, languages | [foundation-models.md](references/foundation-models.md) | +| `@Generable`, `@Guide`, streaming, tools, tool-calling modes, images, Vision tools | [foundation-models-generation.md](references/foundation-models-generation.md) | +| Private Cloud Compute, quota UI, reasoning levels, dynamic profiles, custom models | [foundation-models-pcc.md](references/foundation-models-pcc.md) | +| Writing Tools, Genmoji, Image Playground, Visual Intelligence | [system-features.md](references/system-features.md) | +| HIG generative-AI summary and links | [design-guidance.md](references/design-guidance.md) | + +--- + +## Best Practices + +1. **Smallest model first** - On-device, then PCC after evaluation +2. **Typed output** - `@Generable` with short names and few `@Guide` descriptions (they cost context tokens) +3. **Short prompts** - One task per prompt, at most three paragraphs +4. **Fresh sessions** - New `LanguageModelSession` per unrelated task; reseed from a trimmed `Transcript` after `contextSizeExceeded` +5. **Prewarm** - `prewarm(promptPrefix:)` only with at least 1 second of lead time +6. **Test for real** - Foundation Models instrument in Instruments, Evaluations framework, simulated availability and quota in the Xcode scheme +7. **Let people stay in control** - Undo, retry, edit near generated content; label AI output diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/references/design-guidance.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/references/design-guidance.md new file mode 100644 index 0000000..d78734b --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/references/design-guidance.md @@ -0,0 +1,57 @@ +--- +name: design-guidance +description: HIG generative-AI rules - transparency, privacy, inputs, outputs, refining results, feedback during generation, continuous improvement +when-to-use: Designing or reviewing any UI that shows model-generated content +keywords: HIG, generative AI, transparency, privacy, hallucination, refine, undo, feedback, latency +priority: high +related: foundation-models.md, system-features.md +--- + +# Generative AI design guidance + +Source: https://developer.apple.com/design/human-interface-guidelines/generative-ai (JSON: https://developer.apple.com/tutorials/data/design/human-interface-guidelines/generative-ai.json), read 2026-11-13. Change log on the page: June 8, 2026 added "letting people refine results and providing feedback during content generation" and updated "choosing a model type"; June 9, 2025 first version. No platform-specific considerations. Related pages named there: machine-learning, inclusion, accessibility, privacy, loading, and the acceptable-use requirements for the Foundation Models framework (read it before shipping). + +## Best practices + +| Topic | Rule | Implement with | +|-------|------|----------------| +| Control | Let people dismiss, revert, retry; say when AI is used | Edit / Undo / Retry / Adjust controls beside the result | +| Fallback | Great experience when the feature is unavailable or declined; non-AI alternative when possible | `availability` switch ([foundation-models.md](foundation-models.md)) | +| Inclusion | Do not infer personal or cultural traits; ask for what the feature needs; test across diverse people | Explicit inputs, `@Generable` enums | +| Value | Offer it only where it saves time or adds creativity | Scope each feature narrowly | + +## Transparency + +- Say where the app uses AI; never imply human authorship; follow regional disclosure rules. +- Set expectations: capabilities, limits, how to get good results, why weak results happen. Curated example prompts for open-ended input. + +## Privacy + +- Choose the model type for the data: on-device keeps data local, fast, offline; server models for more power or context. Weigh privacy with capability. +- For server processing: process locally first, minimize what is sent, show what is shared, disclose storage and training use. +- Ask permission before using personal information or usage data; use the minimum; always provide an opt-out; explicit consent for model-improvement data. + +## Inputs + +- Teach people what works (predefined examples). +- Reduce hallucinations: scope the task, avoid requesting facts the model cannot verify, state that output may contain errors, avoid AI content where a mistake could harm. +- Ask confirmation before irreversible or significant actions (deleting photos, purchases); respect model usage policies and local regulation. + +## Outputs + +- **Refine or revert** (new 2026-06-08): expose Edit, Undo, Retry, Adjust near generated content; acknowledge when a correction takes effect. +- Coach people after blocked or poor results (Image Playground says "Unable to use that description."); suggest better requests. +- Test misuse and out-of-scope requests; avoid reproducing copyrighted content (pre-approved prompts, instruct the model to avoid mimicry). +- **Latency**: generative models are slow; design a loading state or generate in the background (`loading` HIG page). +- **Specific feedback during generation** (new 2026-06-08): "Finding substitutions for ingredients", not "Processing..."; on failure explain in plain language with a next step. +- Offer alternate versions when meaningful (Image Playground generates several). + +## Continuous improvement + +- Version prompts and retest on model updates ([foundation-models.md](foundation-models.md) prompt versioning). +- Optional, unobtrusive feedback (thumbs up/down, plus detail for complex issues); take it seriously. The framework logs feedback attachments with `LanguageModelSession.logFeedbackAttachment(sentiment:issues:desiredOutput:)` variants. +- Decouple the model from the UX so models can be swapped (`LanguageModel` protocol, [foundation-models-pcc.md](foundation-models-pcc.md)). + +## Verification in this repo + +Any UI that shows generated content also runs the HIG UI gate in `swiftui-core` (`hig-accessibility.md`, `hig-modality.md`): VoiceOver labels on Edit/Undo/Retry, AX5 layout, loading and error states, RTL. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/references/foundation-models-generation.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/references/foundation-models-generation.md new file mode 100644 index 0000000..b8c6c8d --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/references/foundation-models-generation.md @@ -0,0 +1,109 @@ +--- +name: foundation-models-generation +description: Guided generation with @Generable and @Guide, streaming, tool calling, multimodal prompts and Vision tools +when-to-use: Getting typed output from a model, streaming partial results, letting the model call app code, prompting with images +keywords: Generable, Guide, streamResponse, Tool, ToolCallingMode, Attachment, OCRTool, BarcodeReaderTool, DynamicGenerationSchema +priority: high +related: foundation-models.md, foundation-models-pcc.md +--- + +# Foundation Models - Typed output, tools, images + +Sources (read 2026-11-13), base https://developer.apple.com/documentation/foundationmodels : `/generating-swift-data-structures-with-guided-generation`, `/generable`, `/expanding-generation-with-tool-calling`, `/tool`, `/analyzing-images-with-multimodal-prompting`, `/languagemodelsession/streamresponse(to:generating:includeschemainprompt:options:)`. JSON mirror: `/tutorials/data/documentation/...json`. + +## Guided generation + +`@Generable` (structs, enums with associated values, actors; iOS 26.0, watchOS 27.0) makes the framework use constrained sampling, so the model cannot return malformed data. `@Guide(description:, constraints)` only on stored properties. Properties generate in declaration order. + +```swift +@Generable(description: "Basic profile information about a cat") +struct CatProfile { + var name: String // clear name: no guide needed + @Guide(description: "The age of the cat", .range(0...20)) + var age: Int + @Guide(description: "A one sentence profile about the cat's personality") + var profile: String +} + +let response = try await session.respond(to: "Generate a cute rescue cat", generating: CatProfile.self) +let cat: CatProfile = response.content +``` + +- Supported basics: `Bool`, `Int`, `Float`, `Double`, `Decimal`, `Array`, nested `@Generable`. Use `GenerationID` for framework-generated identifiers. +- Guides seen in Apple samples: `.range(_:)`, `.count(_:)`, `.minimumCount(_:)`, `.maximumCount(_:)`, `.minimum(_:)`, `.maximum(_:)`. +- Schemas cost context tokens: short names, `@Guide` only where quality needs it, descriptions as short as possible. Test without guides first. +- Safety/accuracy trick: output a `@Generable enum` so the answer is always one of your cases. Use `GenerationOptions(samplingMode: .greedy)` to always pick the most likely case. +- Unknown at compile time (e.g. a restaurant menu): `DynamicGenerationSchema` -> `try GenerationSchema(root:dependencies:)` -> `respond(to:schema:)` returns `GeneratedContent`; read with `value(_:forProperty:)`. + +## Streaming + +Apple's page gives the declaration; it returns `LanguageModelSession.ResponseStream`, an `AsyncSequence` of `Snapshot` values whose `content` is the partially generated value (`Generable.PartiallyGenerated`). + +```swift +let stream = session.streamResponse(to: "Generate a cute rescue cat", generating: CatProfile.self) +for try await snapshot in stream { + partial = snapshot.content // update @Observable state on the main actor +} +``` + +`ResponseStream.collect()` waits for the final response. `includeSchemaInPrompt` defaults to `true`; keep it unless the model has seen the format. In the background, use non-streaming `respond` (rate limiting). + +## Tool calling + +`Tool` (protocol, `Sendable`, iOS 26.0, watchOS 27.0): `name`, `description`, `@Generable struct Arguments`, `call(arguments:) async throws -> Output` where `Output` is `String`, `GeneratedContent` or a `@Generable` type. The framework puts name, description and parameters in the prompt; calls may run concurrently and in parallel. + +```swift +struct BreadDatabaseTool: Tool { + let name = "searchBreadDatabase" + let description = "Searches a local database for bread recipes." + + @Generable + struct Arguments { + @Guide(description: "The type of bread to search for") var searchTerm: String + @Guide(description: "The number of recipes to get", .range(1...6)) var limit: Int + } + + func call(arguments: Arguments) async throws -> String { + // query your store; return a short string or a @Generable value + "..." + } +} + +let session = LanguageModelSession(tools: [BreadDatabaseTool()]) +let answer = try await session.respond(to: "Find three sourdough bread recipes") +``` + +- Keep 3-5 tools, short descriptions. If the model always needs a piece of data, put it in the prompt instead of a tool. +- **Tool calling mode** (`ToolCallingMode`, 27.0): `.allowed`, `.required`, `.disallowed` (without it the model decides) via `GenerationOptions(toolCallingMode:)`. With `.required` you must define an exit (throw from the tool, or change the mode in a `DynamicProfile`), otherwise the model keeps calling. +- Errors: throw to abort (not authorized, network too slow) or return a short failure string. The session throws `LanguageModelSession.ToolCallError` (`tool`, `underlyingError`) and rolls the transcript back; `transcriptErrorHandlingPolicy` (`.preserveTranscript`) changes that. +- Integrate existing frameworks (Contacts, HealthKit) inside tools so their permissions still apply. +- `session.transcript` is observable (entries: `.instructions`, `.prompt`, `.toolCalls`, `.toolOutput`, `.response`, `.reasoning`) - useful to render a call graph in SwiftUI. + +## Images (27.0) + +`Attachment` (27.0 all platforms) inside a prompt builder; supports `CGImage`, `CIImage`, `CVPixelBuffer`, image URLs; the framework scales and converts. `orientation:` fixes untransformed images; `.label(_:)` names an image for tools. + +```swift +@Generable enum ImageLabel { case cat, dog, frog, bird } + +func classify(_ image: CGImage) async throws -> ImageLabel { + let session = LanguageModelSession() + let response = try await session.respond( + generating: ImageLabel.self, + options: GenerationOptions(samplingMode: .greedy) + ) { + "Choose the label that best represents the following image:" + Attachment(image) + } + return response.content +} +``` + +- Be specific ("List all food items in this photo"), crop to the region of interest, constrain output with `@Generable`. +- Vision tools (`import Vision`; `ToolCallingMode` is `GenerationOptions.ToolCallingMode`) plug into a session: `OCRTool` (iOS/iPadOS/macOS/visionOS 27.0, not in Simulator) and `BarcodeReaderTool` (27.0, incl. watchOS): `LanguageModelSession(tools: [OCRTool()])`, then label the attachment. +- Custom image tools receive an `ImageReference` argument and resolve it with `resolved(in: Transcript)`. +- Run on-device first; use `PrivateCloudComputeLanguageModel` if more reasoning or context is needed ([foundation-models-pcc.md](foundation-models-pcc.md)). Check multimodal safety ([foundation-models.md](foundation-models.md)). + +## Swift 6 composition + +Keep model calls out of views: an `@MainActor @Observable` view model owns the session and published state; tools are `Sendable` value types (or actors) and protocols live in `Protocols/` per `solid-swift`. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/references/foundation-models-pcc.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/references/foundation-models-pcc.md new file mode 100644 index 0000000..29c9d47 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/references/foundation-models-pcc.md @@ -0,0 +1,106 @@ +--- +name: foundation-models-pcc +description: Private Cloud Compute model, quota UI, reasoning levels, dynamic profiles and custom LanguageModel providers +when-to-use: A feature needs more context or reasoning than the on-device model, or must swap models and tools at runtime +keywords: PrivateCloudComputeLanguageModel, quotaUsage, ContextOptions, reasoningLevel, DynamicProfile, Profile, LanguageModel, CoreAILanguageModel +priority: medium +related: foundation-models.md, foundation-models-generation.md +--- + +# Foundation Models - Private Cloud Compute, profiles, custom models + +Sources (read 2026-11-13), base https://developer.apple.com/documentation/foundationmodels : `/adding-server-side-intelligence-with-private-cloud-compute`, `/privatecloudcomputelanguagemodel`, `/detecting-available-apple-foundation-models`, `/composing-dynamic-sessions-with-instructions-and-profiles`, `/running-a-core-ai-model-in-a-foundation-models-session`, `/languagemodel`. JSON mirror: `/tutorials/data/documentation/...json`. + +## Private Cloud Compute (PCC) + +`PrivateCloudComputeLanguageModel` (iOS, iPadOS, macOS, visionOS, watchOS 27.0+; not listed for tvOS) runs AFM Cloud: 32K-token context, reasoning levels, no API keys or authentication to manage, privacy preserved per Apple, network required, per-day request limit (people can upgrade iCloud+). + +| | `SystemLanguageModel` | `PrivateCloudComputeLanguageModel` | +|---|---|---| +| Offline | yes | no | +| Usage limit | unlimited | per day | +| Reasoning | not supported | light / moderate / deep | +| Context | read `contextSize` (4-8K per the models article; this article's table says 4K) | 32K | + +Apple's rule: build on-device first, evaluate (Evaluations framework), move up only if quality needs it. + +### Setup + +1. Request the managed entitlement `com.apple.developer.private-cloud-compute` (eligibility requirements apply). Without it the app **crashes with a fatal error on the first prompt**, even though `availability` reports `.available` (it only checks OS readiness). +2. Create one shared instance (creation starts an authentication and readiness check; a missing entitlement logs a warning). +3. Gate by OS and fall back to on-device when the network fails. + +```swift +// PrivateCloudComputeLanguageModel exists from 27.0: keep creation behind the +// availability check when the deployment target is lower. Share one instance app-wide. +@available(iOS 27.0, macOS 27.0, watchOS 27.0, visionOS 27.0, *) +let pcc = PrivateCloudComputeLanguageModel() + +func makeSession() -> LanguageModelSession { + if #available(iOS 27.0, macOS 27.0, watchOS 27.0, visionOS 27.0, *), pcc.isAvailable { + return LanguageModelSession(model: pcc) // same respond/stream/tools API + } + return LanguageModelSession() // on-device (no on-device model on watchOS) +} +``` + +`pcc.availability` cases: `.available`, `.unavailable(.deviceNotEligible)`, `.unavailable(.systemNotReady)`, plus `@unknown default`. + +`LanguageModelSession(model:)` with a `some LanguageModel` is one of several 27.0 overloads (`/foundationmodels/languagemodelsession/init(model:tools:instructions:)`, per Apple's PCC article). + +### Quota + +Treat quota as a final availability check: `pcc.quotaUsage.isLimitReached`. Show status UI, not a dismissible alert: + +```swift +if pcc.quotaUsage.isLimitReached { + Text("Usage limit exceeded") +} else if case .belowLimit(let info) = pcc.quotaUsage.status, info.isApproachingLimit { + Text("Nearing usage limit") +} +if let suggestion = pcc.quotaUsage.limitIncreaseSuggestion { + Button("Show options") { suggestion.show() } // system upgrade UI +} +``` + +Mid-session the framework throws `PrivateCloudComputeLanguageModel.Error.quotaLimitReached` (same enum: `networkFailure`, `serviceUnavailable`; `/foundationmodels/privatecloudcomputelanguagemodel/error`, 27.0); `resetDate` says when it refreshes (empty if unknown). Not a rate limit: waiting a short time does not help. Test with the Xcode scheme option (Run > Options > "Simulated Apple Foundation Models Availability": approaching / reached). + +### Reasoning + +```swift +let response = try await session.respond( + to: "What are the tradeoffs in this architecture?", + contextOptions: ContextOptions(reasoningLevel: .deep) +) +``` + +`ContextOptions.ReasoningLevel`: `.light`, `.moderate`, `.deep`. Start at `.moderate`; `.deep` is slower and uses more context. Reasoning appears as `.reasoning` transcript entries, not in `response.content`. + +## Dynamic profiles (27.0) + +Swap instructions, tools, model and options per app state within one continuous session. Layers: `DynamicInstructions` (body re-evaluated before each request) -> `Profile` (instructions + modifiers `.model(_:)`, `.temperature(_:)`, `.samplingMode(_:)`, `.reasoningLevel(_:)`, `.maximumResponseTokens(_:)`, `.toolCallingMode(_:)`, `.transcriptErrorHandlingPolicy(_:)`) -> `LanguageModelSession.DynamicProfile` (exactly one `Profile` active, chosen with `if/else`). + +```swift +struct EditorProfile: LanguageModelSession.DynamicProfile { + var pcc = PrivateCloudComputeLanguageModel() + var isEditingAnimation = false + var body: some LanguageModelSession.DynamicProfile { + if isEditingAnimation { + Profile { AnimationEditingInstructions() }.model(pcc).reasoningLevel(.light) + } else { + Profile { ImageEditingInstructions() }.temperature(0.8) + } + } +} +let session = LanguageModelSession(profile: EditorProfile()) +``` + +Modifier precedence: call-site `GenerationOptions` > innermost profile modifier > outer dynamic-profile modifier. Append conditional instructions and tools in place to keep prompt caching effective (`/optimizing-key-value-caching-in-language-model-sessions`). Per-session custom state: `SessionProperty`, `SessionPropertyKey`, `@SessionPropertyEntry`. Full worked sample: Apple's "Origami" tutorial linked from the framework page. + +## Custom model providers + +`LanguageModel` protocol (27.0, `Sendable`) lets any provider plug into the same session API: `LanguageModelSession(model: MyProvider())`, with an `Executor` and `LanguageModelExecutorGenerationChannel`; distribute through Swift Package Manager. Capability checks: `capabilities` (e.g. `.reasoning`). + +Core AI (iOS/macOS 27, Xcode 27) runs open-source models you export with the `coreai-models` package: `CoreAILanguageModel(resourcesAt:)` (async load, `import CoreAILanguageModels`) then `LanguageModelSession(model: model)`. Load ahead of use; reasoning output goes to the transcript. Use this for devices without Apple Intelligence or cross-platform needs. Privacy then depends on the model you bundle. + +WWDC26 (video pages titles read 2026-11-13): 242 "Build agentic app experiences with the Foundation Models framework", 339 "Bring an LLM provider to the Foundation Models framework", 243 "Debug and profile agentic app experiences with Instruments" (https://developer.apple.com/videos/play/wwdc2026//). diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/references/foundation-models.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/references/foundation-models.md new file mode 100644 index 0000000..e94edb6 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/references/foundation-models.md @@ -0,0 +1,125 @@ +--- +name: foundation-models +description: Foundation Models framework core - availability, model variants, sessions, prompting, context window, errors, safety, languages +when-to-use: Calling the on-device Apple Foundation Model from a Swift app +keywords: FoundationModels, SystemLanguageModel, LanguageModelSession, availability, context window, LanguageModelError, guardrails +priority: high +related: foundation-models-generation.md, foundation-models-pcc.md, design-guidance.md +--- + +# Foundation Models - Core + +Sources (all read 2026-11-13). Each page has a JSON mirror: replace `/documentation/` with `/tutorials/data/documentation/` and append `.json`. +Base: https://developer.apple.com/documentation/foundationmodels (symbol pages below it). + +## Overview + +`SystemLanguageModel` is the on-device model behind Apple Intelligence; `LanguageModelSession` is the stateful context you prompt it with. Platform pages (read 2026-11-13): `LanguageModelSession` is iOS, iPadOS, macOS, visionOS 26.0+, watchOS 27.0+, tvOS 27.0+ (tvOS page for `SystemLanguageModel` shows 27.3 beta). `SystemLanguageModel` is not listed for watchOS: Watch apps use the server model. + +## Check availability + +Source: `/foundationmodels/detecting-available-apple-foundation-models`, `/foundationmodels/systemlanguagemodel` (`isAvailable`, `availability`, `Availability`, `UnavailableReason` - iOS 26.0). + +```swift +let model = SystemLanguageModel.default +switch model.availability { +case .available: + break // show the intelligence UI +case .unavailable(.deviceNotEligible): + break // offer the non-AI path +case .unavailable(.appleIntelligenceNotEnabled): + break // Apple Intelligence is off (iOS 27+: on by default, cannot be turned off) +case .unavailable(.modelNotReady): + break // downloading or other system reason +@unknown default: + break +} +``` + +- Quick Boolean: `model.isAvailable`. Check `.default` first; specialized models such as `SystemLanguageModel(useCase: .contentTagging)` are not available unless the general model is. +- It can take time for the model to download after Apple Intelligence is enabled. +- Fall back to another model (server LLM, custom `LanguageModel`) for devices that never support it. + +### Models and devices (27 generation) + +| Model | Size / context (Apple table) | Runs | Symbol | +|-------|------------------------------|------|--------| +| AFM Core Advanced | 20B params, 8K tokens | on device | `SystemLanguageModel` | +| AFM Core | 3B params, 4-8K tokens | on device | `SystemLanguageModel` | +| AFM Cloud | 32K tokens | Private Cloud Compute | `PrivateCloudComputeLanguageModel` | + +One on-device model per device, chosen by the system; the app cannot pick. Apple Watch has no on-device model, only AFM Cloud via a paired Apple Intelligence iPhone. Per-device matrix: read the article before promising a variant. + +Detect the variant (iOS/iPadOS/macOS/visionOS 27.0+ `variant`, `Variant.core3`, `.coreAdvanced3`, `displayName`); earlier OS: `#available` newest first (26.4 = AFM 2.1 Core, 26.0-26.3 = AFM 2 Core): + +```swift +if #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) { + let name = SystemLanguageModel.default.variant.displayName +} +``` + +Context size: read `contextSize` (back-deployed before 26.4) and `tokenCount(for:)` (26.4+) instead of hard-coding. Apple's articles still quote 4,096 tokens for the older model while the 27 table says 4-8K: the runtime value wins. + +## Sessions and prompting + +Source: `/foundationmodels/generating-content-and-performing-tasks-with-foundation-models`, `/foundationmodels/languagemodelsession` (26.0; watchOS 27.0). + +```swift +let session = LanguageModelSession(instructions: "Suggest five related topics, three to seven words each.") +let response = try await session.respond(to: "Making homemade bread") +print(response.content) +``` + +- Single-turn: new session per call. Multi-turn: reuse the session; it keeps a `Transcript`. +- **Instructions** outrank the prompt; keep them trusted (role, task, style, safety). **Prompt**: one specific task, imperative, bounded length ("in three sentences"). +- `respond` is async; a session handles one request at a time. Check `isResponding`. +- `GenerationOptions(temperature:)`, `samplingMode: .greedy` for deterministic picks, `maximumResponseTokens` only to stop runaway output (can yield truncated text). +- Good fits: summarize, extract entities, classify, refine text, tags, game dialog. Poor fits: basic math, code generation, logical reasoning. +- `SystemLanguageModel(useCase: .contentTagging)` for tag generation. +- `prewarm(promptPrefix:)` when the user is likely to prompt within seconds (needs >= 1 s lead). +- Background work: prefer non-streaming `respond` to reduce `rateLimited` errors. + +## Context window + +Source: `/foundationmodels/managing-the-context-window`. + +Everything counts: instructions, prompts, tool definitions and I/O, `@Generable` schemas, responses. On overflow the session throws `LanguageModelError.contextSizeExceeded`; start a new session seeded from a trimmed `Transcript`: + +```swift +func trimmed(_ old: LanguageModelSession) -> LanguageModelSession { + let entries = [old.transcript.first, old.transcript.last].compactMap { $0 } + let session = LanguageModelSession(transcript: Transcript(entries: entries)) + session.prewarm() + return session +} +``` + +Tactics: concise prompts; `@Guide(.maximumCount)` on arrays; short property names; 3-5 tools max; split big jobs across sessions and chain summaries. Profile token use with Instruments > Foundation Models template. + +## Errors + +Source: `/foundationmodels/languagemodelerror` (27.0, `@nonexhaustive`). `GenerationError` is deprecated 27.0: Xcode 27 builds throw `LanguageModelError`, `SystemLanguageModel.Error` or `LanguageModelSession.Error` instead (`/foundationmodels/languagemodelsession/generationerror`). + +Cases: `contextSizeExceeded`, `rateLimited`, `refusal`, `timeout`, `guardrailViolation`, `unsupportedCapability`, `unsupportedTranscriptContent`, `unsupportedGenerationGuide`, `unsupportedLanguageOrLocale`. Built with Xcode 27 the framework can also throw `SystemLanguageModel.Error` (e.g. `assetsUnavailable`) and `LanguageModelSession.Error`; PCC errors (`quotaLimitReached`, `networkFailure`, `serviceUnavailable`) are `PrivateCloudComputeLanguageModel.Error` ([foundation-models-pcc.md](foundation-models-pcc.md)). Tool failures surface as `LanguageModelSession.ToolCallError`. For OS 26 targets catch `LanguageModelSession.GenerationError` under an `#available(iOS 27.0, ...)` split. + +## Safety + +Source: `/foundationmodels/improving-the-safety-of-generative-model-output`. + +- Two built-in layers: trained models + guardrails (`SystemLanguageModel.Guardrails`: `.default`, `.permissiveContentTransformations`). Input and output are both checked; violation throws `guardrailViolation`. +- String requests: a refusal arrives as text ("Sorry, I can't help"). Guided generation: it throws `refusal`; `refusal.explanation` gets a message (async, can fail; fall back to `debugDescription`). +- Prefer bounded input (fixed prompt choices) or bounded output (`@Generable` enum). Treat webpage or user text as untrusted. Multimodal: check each media item and the combination. + +## Languages + +Source: `/foundationmodels/supporting-languages-and-locales-with-foundation-models`. + +The model is multilingual. Call `SystemLanguageModel.default.supportsLocale()` (uses the current, app-specific locale) before prompting; `supportedLanguages` lists them. Unsupported language throws `unsupportedLanguageOrLocale`; guardrails only cover supported languages. Put the target language in instructions; prompts and `@Generable` names/descriptions must be in a language the model supports. + +## Prompt versioning + +Source: `/foundationmodels/updating-prompts-for-new-model-versions`. Apple updates the model in OS releases. Record outputs per model version, keep prompts as versioned text or String Catalog keys (`String(localized:table:)`), gate with `#available`, or fetch prompts from a server. + +## Testing + +Xcode scheme option "Simulated Apple Foundation Models Availability"; Evaluations framework (`/evaluations`, 27.0) for datasets, metrics, prompt comparison; `#Playground` for quick trials. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/references/system-features.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/references/system-features.md new file mode 100644 index 0000000..c0f7352 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/apple-intelligence/references/system-features.md @@ -0,0 +1,93 @@ +--- +name: system-features +description: Writing Tools, Genmoji, Image Playground and Visual Intelligence integration, plus the App Intents hand-off for Siri AI +when-to-use: Supporting Apple Intelligence system features in text views, image creation UI or visual search +keywords: Writing Tools, UIWritingToolsCoordinator, writingToolsBehavior, NSAdaptiveImageGlyph, Genmoji, imagePlaygroundSheet, ImagePlaygroundViewController, IntentValueQuery, SemanticContentDescriptor +priority: medium +related: foundation-models.md, design-guidance.md +--- + +# Apple Intelligence system features + +Entry pages (read 2026-11-13): https://developer.apple.com/apple-intelligence/ , /get-started/ , /whats-new/. Symbol pages below https://developer.apple.com/documentation ; JSON mirror: `/tutorials/data/documentation/...json`. + +## Writing Tools (rewrite, proofread, summarize) + +Standard views get it automatically: `UITextView`, `UITextField`, `NSTextView`, `NSTextField`, SwiftUI `Text` (selectable), `TextField`, `TextEditor`, `WKWebView` (Get Started names `Text`, `UITextView`, `NSTextView`, `WKWebView`; the UIKit/AppKit/SwiftUI Writing Tools pages add the field and editor types). Do nothing unless you need to tune it. + +| Goal | API | Availability | +|------|-----|--------------| +| Pick experience or disable (SwiftUI) | `.writingToolsBehavior(_:)` with `WritingToolsBehavior` `.automatic/.complete/.limited/.disabled` | iOS/iPadOS 18.0, macOS 15.0, visionOS 2.4 | +| Pick experience or disable (UIKit) | `writingToolsBehavior` = `UIWritingToolsBehavior` `.default/.complete/.limited/.none` | iOS/iPadOS 18.0, visionOS 2.4 | +| AppKit equivalent | `NSWritingToolsBehavior` (see `/appkit/writing-tools`) | platform not opened; check the page | +| Custom text view | `UIWritingToolsCoordinator(delegate:)` + `addInteraction(_:)`; AppKit `NSWritingToolsCoordinator` via the view's `writingToolsCoordinator` | iOS 18.2 / macOS 15.2 | +| Is it supported on this device | `UIWritingToolsCoordinator.isWritingToolsAvailable` (true even if the user has it off) | iOS 18.2 | + +```swift +TextEditor(text: $notes) + .writingToolsBehavior(.disabled) // e.g. a code listing editor +``` + +- Limited experience keeps changes in the Writing Tools panel until approved; complete shows them inline with accept/reject. +- While active the system edits your content temporarily: suspend cloud sync/autosave. UIKit hooks: `textViewWritingToolsWillBegin(_:)` / `textViewWritingToolsDidEnd(_:)` (complete) and `willPresentWritingTools()` / `didDismissWritingTools()` (limited). Protect ranges (code, names, quotes) with `textView(_:writingToolsIgnoredRangesInEnclosingRange:)`. +- Custom engines also see pasteboard-based support: `/appkit/supporting-writing-tools-via-the-pasteboard`. +- Siri: the overview page says writing and editing with Siri works systemwide in standard text controls; custom controls adopt the same Writing Tools APIs. +- Source: `/uikit/writing-tools`, `/appkit/writing-tools`, `/uikit/customizing-writing-tools-behavior-for-system-views`, `/swiftui/view/writingtoolsbehavior(_:)`. + +## Genmoji + +Genmoji are inline images, not text. Per Apple's overview, Genmoji are supported automatically as stickers in your app when you use system text controls. For a custom text engine, preserve the `adaptiveImageGlyph` attribute (`NSAdaptiveImageGlyphAttributeName` in Objective-C) when you filter or rewrite attributed strings, and persist `NSAdaptiveImageGlyph.imageContent` with your content. Never strip unknown attributes in a custom text storage. + +- `NSAdaptiveImageGlyph` (UIKit page: iOS/iPadOS 18.0, tvOS 18.0, visionOS 2.0, watchOS 11.0; an AppKit twin exists): `init(imageContent:)`, `imageContent`, `contentIdentifier`, `contentDescription`, `contentType`. +- You normally receive instances only from the text input system. +- Source: `/uikit/nsadaptiveimageglyph`, `/appkit/nsadaptiveimageglyph`. The exact opt-in trait for custom text inputs was not verified (the page I tried returned no data): check `UITextInputTraits` docs. + +## Image Playground + +Source: `/imageplayground`, `/whats-new` (Apple Intelligence). WWDC26 session 375 "Create high-quality images using Image Playground" (https://developer.apple.com/videos/play/wwdc2026/375/). + +- **SwiftUI**: `.imagePlaygroundSheet(isPresented:concepts:sourceImage:onCompletion:onCancellation:)` (iOS/iPadOS 18.1, macOS 15.1, visionOS 2.4). Completion returns a file `URL`. Gate the button with `@Environment(\.supportsImagePlayground)`. +- **UIKit/AppKit**: `ImagePlaygroundViewController` (delegate delivers the image or cancel; `concepts`, `sourceImage`, `allowedGenerationStyles`, `selectedGenerationStyle`, `personalizationPolicy`); `ImagePlaygroundViewController.isAvailable` (class var). +- **Input**: `ImagePlaygroundConcept.text(_:)`, `.extracted(from:title:)`, `.drawing(_:)`, `.image(_:)`. +- **Options** (`ImagePlaygroundOptions`, 26.4; apply with `.imagePlaygroundOptions(_:)` or the controller's `options`): `creationVariety` (26.4), `personalization` `.automatic/.enabled/.disabled` (26.4), and new in 27.0 `creationStrategy` `.automatic/.editExisting/.generateNew` and `sizeSpecification` via `SizeSpecification.closest(to:)`. +- **`ImageCreator` is deprecated in 27.0** ("Use ImagePlaygroundViewController or imagePlaygroundSheet"). Do not build new code on it, even though the Get Started page still advertises it. +- Where it runs: the 27-era Apple Intelligence overview and What's New say the new model runs on Private Cloud Compute and images are not stored or shared; the Get Started page still says generation is on device. Disclose possible server processing ([design-guidance.md](design-guidance.md)). + +```swift +@Environment(\.supportsImagePlayground) private var supportsImagePlayground +@State private var showSheet = false + +if supportsImagePlayground { + Button("Create image") { showSheet = true } + .imagePlaygroundSheet(isPresented: $showSheet) { url in imageURL = url } +} +``` + +## Visual Intelligence + +Users search with the camera (iPhone), onscreen content (Mac, iPad) or objects around them (Vision Pro); your app returns matching content as `AppEntity` values and opens it from an `OpenIntent`. Source: `/visualintelligence`, `/visualintelligence/integrating-your-app-with-visual-intelligence`. + +1. Make a localized `DisplayRepresentation` (title, subtitle, image) on an `AppEntity` (`IndexedEntity` in Apple's sample). +2. Implement `IntentValueQuery` (26.0 on all platforms) and `values(for: SemanticContentDescriptor)`. +3. Read `labels` (high-level en_US terms such as "tower"; not translated, may change; never the proper name) and `pixelBuffer`, search your content, return entities. Return fast; cap the list (about 100) and link to the full list in-app. +4. Provide an `OpenIntent` per entity type (one per `@UnionValue` member). + +```swift +struct LandmarkIntentValueQuery: IntentValueQuery { + @Dependency var modelData: ModelData + func values(for input: SemanticContentDescriptor) async throws -> [VisualSearchResult] { + guard let pixelBuffer = input.pixelBuffer else { return [] } + return try await modelData.search(matching: pixelBuffer) + } +} +``` + +`SemanticContentDescriptor`: iOS/iPadOS 26.0, macOS/Mac Catalyst 27.0. The `VisualSearchResult` type is used in Apple's sample; its declaration was not opened. + +## App Intents, schemas, Siri AI (do not duplicate) + +Code and rules live in `swiftui-core/references/app-intents.md` and `hig-system-surfaces.md`. Facts from the App Intents pages (read 2026-11-13) that decide routing: + +- Apple Intelligence uses your intents/entities/enums; steps: index entities for Spotlight, choose `Transferable` types, adopt **schemas** (`@AppIntent(schema:)`, `@AppEntity(schema:)`, `@AppEnum(schema:)`; domains in `/appintents/app-schema-domains`), associate entities with onscreen views (`appEntityIdentifier(_:)` SwiftUI 18.4+, `appEntityIdentifier` property on UIKit/AppKit responders), donate actions. +- The Apple Intelligence overview and What's New pages name a new View Annotations API and an App Intents Testing framework (`AppIntentsTesting`); I did not verify those symbols. +- **Siri AI Developer Preview** (`/appintents/siri-ai-developer-preview`): custom actions/content for Siri; may change; not available to external TestFlight testers or App Store builds; test with a development profile or internal TestFlight on an Apple Intelligence device. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/SKILL.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/SKILL.md index 29aea66..8d5841b 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/SKILL.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/SKILL.md @@ -4,7 +4,7 @@ description: Use when preparing an Apple release — code signing, TestFlight up versions: xcode: 27.2 user-invocable: false -references: references/code-signing.md, references/testflight.md, references/app-store.md, references/app-icons.md, references/storekit2.md +references: references/code-signing.md, references/testflight.md, references/app-store.md, references/app-icons.md, references/storekit2.md, references/storekit-2026-updates.md, references/app-review-guidelines.md, references/age-ratings.md, references/privacy-manifest.md, references/eu-alternative-distribution.md, references/app-store-connect-2026.md related-skills: swift-core, ios, macos, mcp-tools --- @@ -63,6 +63,24 @@ After implementation, run **fuse-ai-pilot:sniper** for validation. | App Store submission | [app-store.md](references/app-store.md) | | Icons, assets | [app-icons.md](references/app-icons.md) | | In-app purchases, subscriptions | [storekit2.md](references/storekit2.md) | +| IAP/subscription changes 2025-2026 (offer codes, retention, multiseat, Bundles) | [storekit-2026-updates.md](references/storekit-2026-updates.md) | +| Review guidelines revisions, rejections | [app-review-guidelines.md](references/app-review-guidelines.md) | +| Age ratings, new declarations, regional age laws | [age-ratings.md](references/age-ratings.md) | +| Privacy manifest, required-reason API, SDK rule | [privacy-manifest.md](references/privacy-manifest.md) | +| EU DMA terms, trader status, Japan/Brazil | [eu-alternative-distribution.md](references/eu-alternative-distribution.md) | +| Nutrition Labels, Xcode Cloud, webhooks, product page assets | [app-store-connect-2026.md](references/app-store-connect-2026.md) | +| macOS Developer ID, notarization (macos skill) | `macos` skill `references/notarization.md` | + +--- + +## Deadlines (read 2026-11-13, sources in each reference) + +| Date | Action | +|------|--------| +| 2027-01-12 | Complete the Shared Location and Dating and Relationships age rating declarations ([age-ratings.md](references/age-ratings.md)) | +| 2027-02-01 | Developer ID certificates from the old Sub-CA stop working, `.pkg` signed with them stop installing: move to G2 ([code-signing.md](references/code-signing.md)) | +| Early 2027 | Regulated medical device status (EEA/UK/US) or updates are blocked; no new On-Demand Resources uploads ([app-store-connect-2026.md](references/app-store-connect-2026.md)) | +| April 2027 | Upload with the iOS/iPadOS/tvOS/visionOS/watchOS 27 SDK, iOS 15+ target; iPhone Duo screenshots (specs page: apps on the iOS 27.1 SDK or later; news: all submissions) ([app-store.md](references/app-store.md)). Today the minimum is the 26 SDK and iOS 13 | --- @@ -70,11 +88,12 @@ After implementation, run **fuse-ai-pilot:sniper** for validation. - [ ] Version and build number updated - [ ] Layered app icon (Icon Composer) checked in default/dark/clear/tinted appearances, incl. alternate icons ([HIG app icons](https://developer.apple.com/design/human-interface-guidelines/app-icons)) -- [ ] Privacy manifest (PrivacyInfo.xcprivacy) +- [ ] Privacy manifest (PrivacyInfo.xcprivacy) valid, SDK manifests covered ([privacy-manifest.md](references/privacy-manifest.md)) - [ ] Release configuration - [ ] Archive validates - [ ] TestFlight tested -- [ ] Screenshots updated +- [ ] Screenshots updated (no alpha, required sizes) +- [ ] Age rating, trader, medical device declarations ([age-ratings.md](references/age-ratings.md)) - [ ] App Store metadata complete --- diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/age-ratings.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/age-ratings.md new file mode 100644 index 0000000..4a1f539 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/age-ratings.md @@ -0,0 +1,58 @@ +--- +name: age-ratings +description: App Store age rating system (4+/9+/13+/16+/18+), required questionnaire answers, new Shared Location and Dating declarations (deadline 2027-01-12), social media questions, regional rules (Brazil, Korea, Australia, Singapore, US states) +when-to-use: answering the age rating questionnaire, preparing an update after 2026-11-16, shipping to Brazil/Korea/Texas/Utah/Louisiana, apps with chat, AI assistants, dating or location sharing +keywords: age rating, questionnaire, Shared Location, Dating and Relationships, social media, Declared Age Range, GRAC, Brazil, loot boxes, App Store Connect +priority: high +requires: app-store.md +related: app-review-guidelines.md, app-store-connect-2026.md +--- + +# Age Ratings + +All facts below: Apple Developer News and App Store Connect Help, read 2026-11-13. Ratings values: https://developer.apple.com/help/app-store-connect/reference/age-ratings-values-and-definitions ; how to set: https://developer.apple.com/help/app-store-connect/manage-app-information/set-an-app-age-rating/ + +## Deadlines first + +| Date | What | Source | +|------|------|--------| +| 2026-11-16 | New content descriptors **Shared Location** and **Dating and Relationships** appear in the questionnaire | https://developer.apple.com/news/?id=yxkh08us (2026-11-02) | +| **2027-01-12** | Every app must have these two declarations completed. You must answer when submitting an update or changing the questionnaire | same | +| September 2026 (in force) | Social media answers required to submit new apps/updates, or to submit apps for notarization for alternative distribution | https://developer.apple.com/news/?id=tlur8uvi (2026-07-09) | +| Early 2027 | Regulated medical device status required for existing EEA/UK/US apps in scope, or updates are blocked (see [app-store-connect-2026.md](app-store-connect-2026.md)) | https://developer.apple.com/news/?id=nyqbfz1y | + +## System (since 2025-07-24) + +- Ratings are 4+, 9+, **13+, 16+, 18+**, assigned per country or region (region-specific suitability standards). +- Required questions cover in-app controls, capabilities, medical or wellness topics and violent themes. You may set a **higher** rating to reflect your own minimum age. +- Consider how every feature, **including AI assistants and chatbots**, changes how often sensitive content appears. COPPA and GDPR still apply. Source: https://developer.apple.com/news/?id=ks775ehf (2025-07-24). +- Answers were due 2026-01-31 to avoid blocking updates (https://developer.apple.com/news/upcoming-requirements/). + +## New declarations (from 2026-11-16) + +- **Shared Location**: sharing real-world location with another person or group. +- **Dating and Relationships**: features that enable dating or relationship connections between real people and/or a virtual companion that engages a user in sexual or romantic content. +- Dating and Relationships forces a minimum **18+**. Shared Location may not change the minimum rating in some regions. +- Brazil: local rules require **A16** for Shared Location and **A18** for Dating and Relationships. An app that qualifies lower (for example parent-child location sharing) can request an official rating from Brazil's Ministry of Justice (MJSP); once verified it shows on the Brazil storefront. + +## Social media questions + +A social media capability is "the ability to redistribute, amplify, or interact with user-generated content through a social feed or similar discovery method". It adds a **Social Media** content descriptor and places the app in the Social Media Time Allowances category (iOS/iPadOS/macOS 27+) regardless of the App Store category; capabilities disabled for under-13 users exclude those users. Source: https://developer.apple.com/news/?id=tlur8uvi. + +## Regional rules + +| Region | Rule | Source | +|--------|------|--------| +| Brazil, Australia, Singapore | From 2026-02-24 Apple blocks downloads of **18+** apps unless the user is confirmed adult; apps flagged with loot boxes are 18+ in Brazil | https://developer.apple.com/news/?id=f5zj08ey | +| Utah, Louisiana | Age categories shared through the Declared Age Range API for new accounts (Utah from 2026-05-06, Louisiana from 2026-07-01) | same | +| Texas (SB 2420) | Paused after an injunction (2025-12-23); in force for new Texas accounts from **2026-06-04**: parental consent for minors, Significant Change API under PermissionKit | https://developer.apple.com/news/?id=8jzbigf4, https://developer.apple.com/news/?id=sg176nne | +| Korea | With a GRAC rating you can override the Korea rating to All, 12+, 15+ or 19+ by supplying the RCN; since 2026-10-22 "infrequent profanity and crude humor" and "infrequent mature or suggestive themes" are 12+ | https://developer.apple.com/news/?id=oj3r9pvw, ASC release notes 2026-10-22 | + +Developers keep their own legal duty to confirm age where a law requires it; the Declared Age Range API gives a signal, not proof (news f5zj08ey). + +## Checklist + +- [ ] Questionnaire fully answered, including AI/chatbot and social media capabilities +- [ ] Shared Location and Dating and Relationships declared before 2027-01-12 +- [ ] Brazil/Korea overrides requested where an official rating exists +- [ ] Apps with chat or UGC meet [app-review-guidelines.md](app-review-guidelines.md) section 1.2 diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/app-icons.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/app-icons.md index ceaa0af..873e630 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/app-icons.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/app-icons.md @@ -11,6 +11,10 @@ related: code-signing.md, app-store.md Source: https://developer.apple.com/design/human-interface-guidelines/app-icons +## Icon Formats (HIG update 2026-10-28) + +In iOS, iPadOS, macOS and watchOS you provide the icon in **one of two formats**: a nonlayered bitmap image (such as PNG) or a layered Icon Composer file. Apple recommends Icon Composer for more control over how Liquid Glass applies to individual elements and how color applies across appearance variants. Vector layers (SVG, PDF) stay crisp at any size; use PNG for mesh gradients and raster artwork. Icon Composer lets you annotate default, dark and mono variants. Source: https://developer.apple.com/design/human-interface-guidelines/app-icons (revision entry "October 28, 2026: Added guidance for app icon format options", read 2026-11-13). + ## Layered Icons (Liquid Glass) - iOS, iPadOS, macOS and watchOS icons are a **background layer + one or more foreground layers**. The system applies Liquid Glass effects (specular highlights, refraction, translucency), adapting per size and system version. @@ -38,7 +42,16 @@ tvOS/visionOS: add layers directly to an image stack in Xcode (Parallax Previewe ## Appearances (iOS, iPadOS, macOS) -People pick **default, dark, clear, or tinted** Home Screen icons. Layouts per platform: +Two different lists, both from Apple, both current (read 2026-11-13): + +- **What people choose on the Home Screen** (HIG app-icons, "Appearances"): "In iOS, iPadOS, and macOS, people can choose whether their Home Screen app icons are default, dark, clear, or tinted in appearance. [...] You can design app icon variants for every appearance variant, and the system automatically generates variants you don't provide." HIG sizes table: "Default, dark, clear light, clear dark, tinted light, tinted dark". +- **What you annotate in Icon Composer** (HIG app-icons "Icon Composer" paragraph: "annotate for default, dark, and mono appearance variants"; https://developer.apple.com/icon-composer/ "Annotate Across Rendering Modes": "choose how your icon looks in Default, Dark, and Mono modes"). Apple names these "rendering modes" on the product page and "appearance variants" in the HIG. + +Apple's pages never map Icon Composer's three modes onto the four Home Screen choices. Do not claim that "Mono" equals "Clear" or "Tinted": check the exported icon in Icon Composer and in Device Hub for all four choices. Icon Composer 2 is in beta and requires macOS Tahoe 26.4 or later (https://developer.apple.com/design/whats-new/ lists "Icon Composer 2 beta"; the Icon Composer page states the macOS requirement). + +For a bitmap icon the system segments it into two layers (foreground, background) so it works with dark and tinted variants (HIG, "Icon formats"). + +Layouts per platform: | Platform | Layout | Mask | Size | Appearances | |----------|--------|------|------|-------------| @@ -57,8 +70,9 @@ People pick **default, dark, clear, or tinted** Home Screen icons. Layouts per p Source: https://developer.apple.com/design/human-interface-guidelines/sf-symbols - Thousands of symbols aligned with San Francisco at every weight and size; availability depends on the OS version targeted. -- Four rendering modes: monochrome, hierarchical, palette, multicolor. Gradients (SF Symbols 7+) and variable color work across modes. -- Animations (incl. Draw On/Off, SF Symbols 7+): use judiciously, honour Reduce Motion. +- Four rendering modes: monochrome, hierarchical, palette, multicolor. Gradients ("SF Symbols 7 and later", HIG revision 2025-07-28) and variable color work across modes. +- Animations (incl. Draw On/Off, SF Symbols 7 and later): use judiciously, honour Reduce Motion. +- **Current release naming**: Apple's design What's new page (published 2026-11-06, https://developer.apple.com/design/whats-new/, read 2026-11-13) lists "Download SF Symbols 8 beta" (dated June 8, 2026), in the WWDC26 group next to the HIG "App icons: Refined guidance for Liquid Glass" entry (HIG revision June 8, 2026). The current Design Resources page https://developer.apple.com/design/resources/ (read 2026-11-14) says "Download SF Symbols 27 - Requires macOS Sonoma or later", and https://developer.apple.com/sf-symbols/ shows no "beta" in its text; its download link is `SF-Symbols-27.dmg`, and it says new symbols are available in apps running iOS 27, iPadOS 27, macOS 27, watchOS 27, tvOS 27 and visionOS 27. The HIG sf-symbols page (last revision July 28, 2025) names only SF Symbols 7 and earlier. So: write "SF Symbols 27 (announced at WWDC26 as 'SF Symbols 8 beta')"; both names point to the same app, and symbols are available from OS 27. - Icon-only symbols need an accessibility label; symbols get RTL variants automatically. ## Launch Screen (iOS/iPadOS) diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/app-review-guidelines.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/app-review-guidelines.md new file mode 100644 index 0000000..84c0d61 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/app-review-guidelines.md @@ -0,0 +1,48 @@ +--- +name: app-review-guidelines +description: App Review Guidelines revision log since 2025-06 (2025-06-09, 2025-11-13, 2026-02-06, 2026-06-08, 2026-10-16) and the guideline sections that cause most rejections, with review-timing facts +when-to-use: preparing a submission, answering a rejection, checking whether a guideline changed, writing App Review notes +keywords: App Review Guidelines, rejection, 2.1, 2.3.14, 2.5.19, 3.1.1(a), 4.1(c), 4.7, 5.1.2(i), 1.2, creative assets, hidden features +priority: high +requires: app-store.md +related: age-ratings.md, privacy-manifest.md, eu-alternative-distribution.md +--- + +# App Review Guidelines + +Canonical text: https://developer.apple.com/app-store/review/guidelines/ (page shows "Last Updated: October 16, 2026", read 2026-11-13). The guidelines apply to alternative distribution for sections marked as covering iOS/iPadOS notarization. Re-read the page before quoting a clause; this file records changes announced in Apple Developer News. + +## Revision log + +| Date | Change | Source | +|------|--------|--------| +| 2025-06-09 | 3.1.2(a): removed the line allowing one subscription shared across your own apps and services; bullet 5 moved to the new 3.2.2(x), which also newly permits developers to otherwise incentivize users to take specific actions in the app; 3.2.1(viii): financial apps need licensing in each location they are offered | https://developer.apple.com/news/?id=r9dcmrvs | +| 2025-11-13 | **1.2.1(a)** creator apps must let users identify content above the app's age rating and gate underage users by verified or declared age. **4.1(c)** no other developer's icon, brand or product name in your icon or name without approval. **4.7 / 4.7.2 / 4.7.5** HTML5/JavaScript mini apps and mini games in scope; no exposing native platform APIs to non-embedded software without Apple's permission; same age-identification duty. **5.1.1(ix)** crypto exchanges are highly regulated services. **5.1.2(i)** disclose where personal data goes to third parties, **including third-party AI**, and get explicit permission first. **3.2.2(ix)** loan apps: maximum APR 36% including costs and fees, no repayment in full in 60 days or less. **2.5.10** empty-ad-banner sentence deleted | https://developer.apple.com/news/?id=ey6d8onl | +| 2026-02-06 | 1.2: apps with random or anonymous chat are subject to the user-generated-content guideline | https://developer.apple.com/news/?id=d75yllv4 | +| 2026-06-08 | Introduction: revised kid and teen safety guidance. 1.2: developer responsibility for violating content. 4.3(a), 4.3(b): basis and examples clarified. **4.5.3**: Live Activities may not spam, phish or send unsolicited messages | https://developer.apple.com/news/?id=a233fmpw | +| 2026-10-16 | **2.3.14** new: creative assets (product page header, search results) must relate to app content or brand, be suitable for all audiences, with no misleading references to other apps, unverifiable claims, or specific/discounted prices. **2.5.19** new: no hidden, dormant or undocumented features (obfuscation to hide them can end in removal and account termination); formerly in 2.3.1. **3.1.1(a)**: music-streaming entitlement bullet merged into StoreKit External Purchase Link Entitlements; links may go to a permitted destination. **1.2** scope and Developer Code of Conduct clarified. **5** apps facilitating human trafficking or child exploitation are removed and blocked from alternative distribution | https://developer.apple.com/news/?id=92th7e5i | + +## Sections that decide most submissions + +| Section | Rule in short (verbatim source: guidelines page) | Prepare | +|---------|----------------------------------------------------|---------| +| 2.1(a) App Completeness | Final version, working URLs, no placeholder text, tested on device, demo account or demo mode if login exists, backend live | Demo credentials in App Review Information | +| 2.1(b) | Configured in-app purchases must be complete, visible and functional; explain any item the reviewer cannot find | Review notes per IAP | +| 2.3 Accurate Metadata | Metadata, screenshots and previews match the app; 2.3.14 for creative assets | Real-UI screenshots | +| 3.1.1 / 3.1.2 | In-app purchase for digital goods; subscription rules | [storekit-2026-updates.md](storekit-2026-updates.md) | +| 4.2 / 4.3 | Minimum functionality; spam | Distinct feature set | +| 4.8 | A third-party or social login for the primary account requires an equivalent login option that limits data to name and email and lets users keep the email private | [app-store-connect-2026.md](app-store-connect-2026.md) (Sign in with Apple domain) | +| 5.1.1(i), 5.1.2 | Privacy policy link in App Store Connect and in-app; data use, sharing, permission | [privacy-manifest.md](privacy-manifest.md) | +| 1.2 | UGC apps: filtering, reporting with timely response, blocking, published contact | Moderation before submit | + +"Before You Submit" (guidelines page): test for crashes, complete metadata, current contact info, full reviewer access (demo account or demo mode, hardware), live backend, explanations of non-obvious features and purchases, regulatory documents where required. + +## Timing and appeals (no numeric promise) + +Apple states only that App Review "will examine your app as soon as we can", that complex or repeatedly rejected apps take longer, and that expedite requests are for critical timing issues. Do not quote "1-3 days" or similar: no such figure appears in the guidelines. Release dates in the future hold an approved app until that date, and appearing on all storefronts can take up to 24 hours. Reply to a rejection in App Store Connect (Resolution Center); appeals exist; bug-fix updates are not delayed over guideline violations except legal or safety ones. Source: guidelines "After You Submit". + +## Answering a rejection + +1. Quote the guideline number from the message and re-read that clause on the page. +2. Fix every item listed, then reply in Resolution Center with what changed. +3. If you disagree, use the appeal route; do not resubmit unchanged. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/app-store-connect-2026.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/app-store-connect-2026.md new file mode 100644 index 0000000..8b468c2 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/app-store-connect-2026.md @@ -0,0 +1,50 @@ +--- +name: app-store-connect-2026 +description: App Store Connect features and requirements 2025-2026 - Accessibility Nutrition Labels, Xcode Cloud, webhooks, custom product pages, creative assets, medical device status, Sign in with Apple domain, On-Demand Resources cut-off +when-to-use: setting up a release pipeline, filling product page metadata, answering compliance declarations, planning for early 2027 requirements +keywords: Accessibility Nutrition Labels, Xcode Cloud, webhooks, custom product pages, creative assets, Asset Library, regulated medical device, Sign in with Apple, private.icloud.com, On-Demand Resources +priority: medium +requires: app-store.md +related: age-ratings.md, testflight.md, storekit-2026-updates.md +--- + +# App Store Connect 2025-2026 + +All entries: App Store Connect release notes (https://developer.apple.com/help/app-store-connect/release-notes/) and Apple Developer News, read 2026-11-13. + +## Deadlines and cut-offs + +| When | What | Source | +|------|------|--------| +| Early 2027 | **Regulated medical device status** required for existing apps in the EEA, UK or US that are in Health & Fitness or Medical, or that report "frequent" Medical or Treatment Information in the age questionnaire. Without it you cannot submit updates. New apps need it since 2026-03-26. "If your app is not a regulated medical device, you can select No" | https://developer.apple.com/news/?id=nyqbfz1y | +| Early 2027 | App Store Connect stops accepting **On-Demand Resources** uploads from new apps or apps that never used them; migrate to Background Assets | ASC release notes 2026-11-12 | +| 2027-01-12 | Age rating declarations | [age-ratings.md](age-ratings.md) | +| Later in 2026 | New Sign in with Apple addresses issued on `private.icloud.com` | https://developer.apple.com/news/?id=1ptvdtcm (2026-08-24) | + +## Sign in with Apple private relay domain + +Existing `privaterelay.appleid.com` addresses keep forwarding. Make account systems, email validation and allowlists accept **both** `privaterelay.appleid.com` and `private.icloud.com`. Hide My Email stays on `icloud.com`. Developers based in Korea must register a server-to-server notification endpoint for new or updated Services IDs from 2026-01-01 (https://developer.apple.com/news/?id=j9zukcr6). + +## Accessibility Nutrition Labels + +- Labels show on the product page for devices on iOS 26, iPadOS 26, macOS 26, tvOS 26, visionOS 26, watchOS 26 or later (ASC release notes 2025-09-03). Overview: https://developer.apple.com/help/app-store-connect/manage-app-accessibility/overview-of-accessibility-nutrition-labels +- You declare per device which features the app supports: VoiceOver, Voice Control, Larger Text, Dark Interface, Differentiate Without Color Alone, Sufficient Contrast, Reduced Motion, Captions, Audio Descriptions (not every label applies to every device). Apple recommends evaluating in that order. +- A device with no answer still shows the section and says you haven't indicated support yet; an optional accessibility URL (not shown on Apple TV) explains details. +- Audit the app on each supported device against Apple's evaluation criteria before answering. Implementation checks: `swiftui-core` `references/hig-accessibility.md`. + +## Xcode Cloud + +- Apple Developer Program membership includes **25 compute hours per month**; larger monthly plans (100, 250, 1,000 and 10,000 hours) are sold separately (https://developer.apple.com/xcode-cloud/). +- Since 2026-10-21 Xcode Cloud has its **own section in App Store Connect** (https://developer.apple.com/help/app-store-connect/get-started/app-store-connect-sections). +- Xcode Cloud can create and upload builds directly ([testflight.md](testflight.md)). + +## Webhooks + +Since 2025-10-01 you can configure webhooks in App Store Connect so your server is notified when a build upload, beta build or Apple-hosted asset pack version changes status. Build upload status (warnings, errors) is also visible in the app. Use it instead of polling in CI. + +## Product page assets + +- **Custom product pages**: up to **70** per app (since 2025-10-28), each can carry keywords so it can appear in search results for them (https://developer.apple.com/news/?id=gf6mgrs6). +- You can submit extra items to App Review independently of an app version under review: In-App Events, a bug-fix version separate from custom product pages, Game Center features (same news). +- **Creative assets** and the **Asset Library** (2026-10-05): product page headers, search result assets and in-app events, with a live preview. Guideline 2.3.14 governs content ([app-review-guidelines.md](app-review-guidelines.md)). Specs: https://developer.apple.com/help/app-store-connect/reference/app-information/creative-assets-specifications +- Screenshot rules: [app-store.md](app-store.md). diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/app-store.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/app-store.md index b9f745f..4a6ab3a 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/app-store.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/app-store.md @@ -1,11 +1,11 @@ --- name: app-store -description: App Store submission with review guidelines, metadata, and approval process -when-to-use: submitting to App Store, preparing metadata, handling review feedback -keywords: App Store, submission, review, metadata, screenshots, App Store Connect +description: App Store submission requirements (SDK and deployment minimums today and April 2027, screenshots incl. iPhone Duo), metadata checklist and pointers to guidelines, age ratings, privacy manifest +when-to-use: submitting to App Store, preparing metadata and screenshots, checking upload minimums, handling review feedback +keywords: App Store, submission, SDK minimum, April 2027, screenshots, iPhone Duo, metadata, App Store Connect priority: high requires: code-signing.md, testflight.md -related: app-icons.md +related: app-icons.md, app-review-guidelines.md, age-ratings.md, privacy-manifest.md, eu-alternative-distribution.md, app-store-connect-2026.md --- # App Store Submission @@ -28,8 +28,17 @@ related: app-icons.md - App icons (all variants) - Launch screen (mandatory in `Info.plist` for iOS/iPadOS apps built with the 27 SDK: `UILaunchStoryboardName`, `UILaunchStoryboards`, `UILaunchScreen` or `UILaunchScreens`) - Correct deployment target (never 27.1 for macOS/watchOS/tvOS/visionOS with Xcode 27.2: the SDK lists it by mistake) -- Built with Xcode 26+ and the iOS/iPadOS/tvOS/visionOS/watchOS 26 SDK or later (current upload minimum per https://developer.apple.com/news/upcoming-requirements/, checked 2026-11-08; Xcode 27.2 ships the 27.2 SDKs) -- 27 SDK builds: scene-based life cycle required (UIKit apps), `ARCHS_STANDARD` excludes `x86_64` at macOS 27.0+ deployment, On Demand Resources deprecated (Background Assets). See swift-core `references/sdk-27-changes.md` +- **Today (2026-11-13)**: built with Xcode 26+ and the iOS/iPadOS/tvOS/visionOS/watchOS 26 SDK or later (minimum since 2026-04-28); iOS and iPadOS apps must target iOS 13 or later (since 2026-09-09). Source: https://developer.apple.com/news/upcoming-requirements/. Xcode 27.2 ships the 27.2 SDKs. +- **Starting April 2027**: iOS/iPadOS apps must be built with the iOS & iPadOS **27 SDK** or later **and target iOS 15 or later**; tvOS, visionOS and watchOS apps with the 27 SDK or later. SDK minimums: https://developer.apple.com/news/?id=k1mtkt1k (2026-09-09); the iOS 15 target: only https://developer.apple.com/app-store/submitting/ (read 2026-11-13). The upcoming-requirements page does not list this yet; plan the move to Xcode 27 now. +- 27 SDK builds: scene-based life cycle required (UIKit apps), `ARCHS_STANDARD` excludes `x86_64` at macOS 27.0+ deployment, On Demand Resources deprecated (Background Assets; uploads from new ODR apps refused from early 2027). See swift-core `references/sdk-27-changes.md` +- macOS builds: no `com.apple.quarantine` attribute in TestFlight/App Store apps; Apple states macOS 26 is the last release supporting Intel Macs (news k1mtkt1k) and macOS 27 the final release supporting Rosetta (news w5ngl9k2); see [notarization.md](../../macos/references/notarization.md). A universal app with minimum macOS 13+ may drop `x86_64` for the Mac App Store (ASC release notes 2026-06-18) + +### Screenshots (https://developer.apple.com/help/app-store-connect/reference/app-information/screenshot-specifications, read 2026-11-13) + +- At least one, up to 10 per device size; `.jpeg`, `.jpg` or `.png`; **no alpha channel or transparency** +- Required sizes: iPhone with Dynamic Island (medium display) and, if the app supports iPadOS, iPad 13-inch. Mac, Apple TV, Apple Vision Pro and Apple Watch apps need their own set (Mac 16:10: 1280x800, 1440x900, 2560x1600 or 2880x1800; Apple TV 1920x1080 or 3840x2160; Vision Pro 3840x2160; Watch sizes per model, identical across localizations) +- If the UI is consistent across sizes, supply the highest required resolution and App Store Connect scales it down +- **iPhone Duo**: 1398x2034 / 2034x1398 px (outer display) and 2007x2853 / 2853x2007 px (inner display). The specifications page says that from April 2027 screenshots are **required for any app using the iOS 27.1 SDK or later**; the news post (https://developer.apple.com/news/?id=kkphp5qo) words it more broadly: "any apps or games submitted will need to include screenshots for iPhone Duo". Plan for the broader reading. Submitting them adds a "made for iPhone Duo" badge **Metadata:** - App name and subtitle @@ -39,21 +48,14 @@ related: app-icons.md - App preview videos (optional) - Privacy policy URL -### Privacy Manifest (Required 2024+) -Declare API usage and tracking. +### Privacy Manifest +`PrivacyInfo.xcprivacy` with required-reason API entries (`NSPrivacyAccessedAPITypes`) is enforced by App Store Connect since 2024-05-01. Workflow, SDK rule and placement: [privacy-manifest.md](privacy-manifest.md). -**PrivacyInfo.xcprivacy:** -- NSPrivacyAccessedAPITypes -- NSPrivacyTrackingDomains -- Required for all apps +### Compliance declarations +Age rating questionnaire ([age-ratings.md](age-ratings.md)), EU trader status and regional terms ([eu-alternative-distribution.md](eu-alternative-distribution.md)), regulated medical device status, Accessibility Nutrition Labels ([app-store-connect-2026.md](app-store-connect-2026.md)). ### Review Process - -| Stage | Duration | -|-------|----------| -| Waiting for Review | 1-3 days | -| In Review | 24-48 hours | -| Pending Developer Release | Until you release | +No review duration is published: Apple says App Review examines an app "as soon as we can", with longer times for complex apps or repeated rejections. Track status in App Store Connect; "Pending Developer Release" lasts until you release. Details and sources: [app-review-guidelines.md](app-review-guidelines.md). --- @@ -62,43 +64,30 @@ Declare API usage and tracking. ### Before Upload - [ ] Version number correct - [ ] Build number unique -- [ ] Privacy manifest complete +- [ ] Privacy manifest complete ([privacy-manifest.md](privacy-manifest.md)) - [ ] Export compliance answered - [ ] All capabilities configured +- [ ] SDK/deployment minimums met (today vs April 2027, above) +- [ ] macOS: no quarantine attribute, Developer ID certificates from G2 if also distributing outside the store ### In App Store Connect - [ ] App name and subtitle - [ ] Description -- [ ] Keywords (100 chars) -- [ ] Screenshots (all devices) +- [ ] Keywords (up to 100 bytes, https://developer.apple.com/help/app-store-connect/reference/app-information/platform-version-information) +- [ ] Screenshots (required sizes, no alpha; iPhone Duo set from April 2027) - [ ] App preview (optional) - [ ] Category selected -- [ ] Age rating questionnaire +- [ ] Age rating questionnaire, incl. Shared Location and Dating declarations by 2027-01-12 +- [ ] Trader status (EU), regulated medical device status where in scope - [ ] Privacy policy URL - [ ] Support URL - [ ] Copyright --- -## Common Rejection Reasons - -| Reason | Solution | -|--------|----------| -| Guideline 2.1 - Crashes | Fix stability issues | -| Guideline 4.2 - Minimum functionality | Add more features | -| Guideline 5.1.1 - Privacy | Add privacy policy | -| Guideline 2.3 - Screenshots | Match actual app | -| Guideline 4.0 - Design | Follow HIG | - ---- - -## Responding to Rejection +## Guidelines and Rejections -1. Read rejection reason carefully -2. Address ALL issues mentioned -3. Update Resolution Center -4. Resubmit for review -5. Appeal if you disagree (rarely works) +The rejection list is maintained against the live guidelines (last updated 2026-10-16) in [app-review-guidelines.md](app-review-guidelines.md): revision log 2025-06 to 2026-10, the sections that decide most submissions (2.1, 2.3, 3.1, 4.2, 4.3, 5.1), and how to answer a rejection. --- diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/code-signing.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/code-signing.md index 05a461d..b247671 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/code-signing.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/code-signing.md @@ -36,6 +36,19 @@ Let Xcode manage certificates and profiles. | Distribution | App Store/TestFlight | | Developer ID | macOS outside App Store | +### Developer ID Sub-CA expiry (deadline 2027-02-01) + +The original Developer ID Certification Authority (Sub-CA) expires on **2027-02-01**; certificates it issued stop working that day. Replacements come from **Developer ID Certification Authority (G2)**, valid until 2031, but G2-issued certificates expire annually and must be renewed each year. Sources: https://developer.apple.com/news/?id=w4atic4c (2026-10-01) and https://developer.apple.com/help/account/certificates/replace-developer-id-certificates (both read 2026-11-13). + +| Step | Detail | +|------|--------| +| Check | Certificates, Identifiers & Profiles: Developer ID Application and Installer certificates expiring on or before 2027-02-01 are likely affected. Confirm in Keychain Access: Issuer Name > Organizational Unit `Apple Certification Authority` = old Sub-CA (replace), `G2` = current (no action) | +| Create | New certificate; when asked for the Developer ID Certificate Intermediary choose **G2 Sub-CA** (Xcode 11.4.1 or later). Any other option may issue a certificate that also expires in 2027. Repeat for both Application and Installer types | +| Re-sign installer packages (`.pkg`) | From 2027-02-01 a `.pkg` signed with an affected certificate no longer installs: re-sign every package before that date | +| Re-sign Mac apps | Software already signed and notarized (with a secure timestamp) keeps working; sign future updates with the new certificate and a secure timestamp | + +A team can hold up to five Developer ID Application and five Installer certificates, so create and test the replacement before the old one expires. Notarization workflow: `macos` skill `references/notarization.md`. + ### Provisioning Profiles Link app, team, certificates, and devices. @@ -110,4 +123,5 @@ Centralized certificate management. - ✅ Store CI secrets securely - ❌ Don't share certificates insecurely - ❌ Don't commit profiles to git +- ✅ Renew G2 Developer ID certificates yearly; calendar the 2027-02-01 Sub-CA cut-off - ❌ Don't ignore expiration dates diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/eu-alternative-distribution.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/eu-alternative-distribution.md new file mode 100644 index 0000000..9030f88 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/eu-alternative-distribution.md @@ -0,0 +1,54 @@ +--- +name: eu-alternative-distribution +description: EU Digital Markets Act business terms from 2026-10-01 (Core Technology Commission 5%, alternative payments, Web Distribution), DSA trader status, and iOS alternative distribution in Japan and Brazil +when-to-use: shipping iOS/iPadOS apps in the EU, Japan or Brazil, offering alternative payments, using an alternative marketplace or Web Distribution, declaring trader status +keywords: DMA, EU, Core Technology Commission, alternative app marketplace, Web Distribution, alternative payments, trader status, DSA, Japan MSCA, Brazil CADE, notarization iOS +priority: medium +requires: app-store.md +related: age-ratings.md, app-review-guidelines.md +--- + +# EU, Japan and Brazil Distribution + +Facts only from Apple pages read 2026-11-13. Commission rates change with the Developer Program License Agreement (DPLA): re-read https://developer.apple.com/support/apps-in-the-eu/ before quoting a number to a client. + +## EU business terms (effective 2026-10-01) + +Announced 2026-08-18 (https://developer.apple.com/news/?id=gmws0jgp). Every developer distributing in the EU moves to one set of terms. + +| Item | Rule (https://developer.apple.com/support/apps-in-the-eu/) | +|------|------| +| Core Technology Fee | Replaced by the **Core Technology Commission (CTC): 5%** on digital goods and services sold in alternative marketplaces, apps distributed through them, and apps using Web Distribution | +| App Store commission, Apple In-App Purchase | 26%; 15% for Small Business Program, Mini Apps Partner Program or Video Partner Program participants and for auto-renewable subscriptions after year one | +| App Store commission, alternative payment in the app | 20%; 10% for the same reduced groups | +| Store services commission | 15% (10% reduced) on out-of-app offers with an actionable link, only for sales within 7 days of the link tap | +| Alternative payments | Alternative processors and out-of-app offers (website, marketplace, other app) alongside Apple In-App Purchase; chosen payment options must be **kept for 12 months** | +| Child safety | Kids category: alternative payment flows behind a parental gate, no out-of-app purchase offers. Under 13: parental gate, no out-of-app offers. 13-17: both behind a parental gate | +| Eligibility | Operating an alternative marketplace or using Web Distribution needs at least one criterion (financial-stability score, public company, venture funding, audit, approved nonprofit/government, USD 1,000,000 letter of credit, or 1 million first annual installs). **No EU legal entity or EU establishment required** | +| iOS/iPadOS 27.2 | Updated install experience; EU users can keep alternative marketplaces and alternatively distributed apps for 90 days while travelling outside the EU | + +Notarization for iOS and iPadOS apps (not the macOS notary service) applies to alternative distribution; guidelines marked for notarization in https://developer.apple.com/app-store/review/guidelines/ apply. Age rating answers are required to submit apps for that notarization ([age-ratings.md](age-ratings.md)). Web Distribution API: https://developer.apple.com/documentation/marketplacekit/distributing-your-app-from-your-website + +For sales that bypass Apple In-App Purchase you collect and remit applicable taxes yourself and must track and report all alternative-payment transactions to Apple for commission calculation (same support page). + +## Trader status (EU Digital Services Act) + +- DSA Articles 30 and 31 require Apple to verify and display contact details (address, phone, email) of traders distributing in the EU App Store (https://developer.apple.com/help/app-store-connect/manage-compliance-information/manage-european-union-digital-services-act-trader-requirements/). +- You assess whether you are a trader (a hobbyist with no commercial intent may not be); Apple cannot decide for you. TestFlight-only or non-EU-only distribution is not trading on the EU App Store. +- Apps without trader status are removed from the App Store in the EU until status is provided and verified; status is also required to submit updates (https://developer.apple.com/news/upcoming-requirements/). + +## Japan and Brazil (iOS) + +| Region | Since | What | +|--------|-------|------| +| Japan (Mobile Software Competition Act) | iOS 26.2; DPLA acceptance due 2026-03-17 | Alternative marketplaces, alternative payments, notarization for iOS apps. https://developer.apple.com/news/?id=074b3wzz (2025-12-17) | +| Brazil (CADE agreement) | iOS 26.5; DPLA acceptance due 2026-07-06 | Same option set, with child-safety protections. https://developer.apple.com/news/?id=dhwadr2x (2026-06-18) | + +Texas (SB 2420) is an age-assurance law, not alternative distribution: see [age-ratings.md](age-ratings.md). + +## Checklist + +- [ ] Latest DPLA accepted for each region you distribute in +- [ ] Trader status confirmed before shipping to the EU App Store +- [ ] Payment option choice recorded (12-month commitment in the EU) +- [ ] Kids/under-18 flows gated per the child-safety rules above diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/privacy-manifest.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/privacy-manifest.md new file mode 100644 index 0000000..7e3d280 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/privacy-manifest.md @@ -0,0 +1,66 @@ +--- +name: privacy-manifest +description: PrivacyInfo.xcprivacy workflow for the app and third-party SDKs - data collection, required-reason API categories, bundle placement, App Store Connect validation rules +when-to-use: adding or auditing a privacy manifest, adopting a third-party SDK, fixing an App Store Connect privacy manifest email or rejection +keywords: PrivacyInfo.xcprivacy, privacy manifest, required reason API, NSPrivacyAccessedAPITypes, third-party SDK, tracking domains, privacy report +priority: high +requires: app-store.md +related: app-review-guidelines.md, code-signing.md +--- + +# Privacy Manifest + +All text below was read 2026-11-13 from Apple documentation (JSON endpoints behind developer.apple.com/documentation). + +## What it records + +Source: https://developer.apple.com/documentation/bundleresources/privacy-manifest-files + +"Apps and third-party SDKs - distributed as XCFrameworks, Swift packages, or Xcode projects - can contain a privacy manifest file, named `PrivacyInfo.xcprivacy`." It records: +- the **types of data collected** (all platforms); +- the **required reason APIs** used (iOS, iPadOS, tvOS, visionOS, watchOS). + +`PrivacyInfo.xcprivacy` is the required file name. Create it in Xcode with File > New File > Resource > App Privacy File and check the target; it must be in the target's resources for Xcode to use it in a privacy report. A static-library SDK ships it by using a static framework target (Xcode 15+) with Mach-O type "Static Library". + +## Required-reason API workflow + +Source: https://developer.apple.com/documentation/bundleresources/describing-use-of-required-reason-api + +1. Find every use of covered API, in your code **and in third-party SDKs**. +2. For each category used, add a dictionary to the `NSPrivacyAccessedAPITypes` array with `NSPrivacyAccessedAPIType` (the category) and `NSPrivacyAccessedAPITypeReasons` (approved reason codes). +3. Categories (https://developer.apple.com/documentation/bundleresources/app-privacy-configuration/nsprivacyaccessedapitypes/nsprivacyaccessedapitype): `NSPrivacyAccessedAPICategoryFileTimestamp`, `NSPrivacyAccessedAPICategorySystemBootTime`, `NSPrivacyAccessedAPICategoryDiskSpace`, `NSPrivacyAccessedAPICategoryActiveKeyboards`, `NSPrivacyAccessedAPICategoryUserDefaults`. Take reason codes and the API list from the key's page; Apple updates them over time. +4. Declared reasons must accurately reflect the use and be consistent with functionality shown to users; you may use the API and derived data **for the declared reasons only**, never for tracking. Fingerprinting is not allowed whether or not the user grants tracking permission. +5. Each executable or dynamic library that uses a required-reason API needs its bundle to carry a manifest that reports it. +6. No listed reason fits and the use benefits the user: submit a request for a new approved reason (Apple's note on that page). + +Enforcement: "Starting May 1, 2024, apps that don't describe their use of required reason API in their privacy manifest file aren't accepted by App Store Connect." (same page; also https://developer.apple.com/news/upcoming-requirements/). + +## Placement + +Source: https://developer.apple.com/documentation/bundleresources/adding-a-privacy-manifest-to-your-app-or-third-party-sdk + +| Product | Location | +|---------|----------| +| iOS/iPadOS/tvOS/visionOS/watchOS app | `App.app/PrivacyInfo.xcprivacy` (bundle root) | +| macOS and Mac Catalyst app | `App.app/Contents/Resources/PrivacyInfo.xcprivacy` | +| iOS-family framework | `Framework.framework/PrivacyInfo.xcprivacy` | +| macOS and Mac Catalyst framework | `Framework.framework/Versions/A/Resources/PrivacyInfo.xcprivacy` | + +Xcode places it correctly; check the paths if you build without Xcode. + +## Third-party SDK rule (Apple's exact scope) + +Source: https://developer.apple.com/support/third-party-SDK-requirements/ ("SDKs that require a privacy manifest and signature") + +> "You must include the privacy manifest for any SDK listed below when you submit new apps in App Store Connect that include those SDKs, or when you submit an app update that adds one of the listed SDKs as part of the update. Signatures are also required in these cases where the listed SDKs are used as binary dependencies. Any version of a listed SDK, as well as any SDKs that repackage those on the list, are included in the requirement." + +The list includes Alamofire, Firebase pods, Flutter, GoogleSignIn, Kingfisher, Lottie, OneSignal, RxSwift, SDWebImage, SnapKit and others: read the page for the full list. For an SDK **you author**: "include a privacy manifest file in your third-party SDK if it uses a required reasons API, collects data about the person using apps that include the third-party SDK, enables the app to collect data about people using the app, or contacts tracking domains" (privacy-manifest-files page). + +Validity: "App Store Connect rejects app submissions that include invalid privacy manifest files" (unexpected keys or values; email names the file path). For an invalid file from an SDK, get an updated SDK; troubleshooting is TN3181. Since 2025-02-12 apps must contain a valid manifest for the listed SDKs. + +## Checklist + +- [ ] App manifest present with data collection and required-reason entries +- [ ] Every embedded SDK either listed on Apple's page (manifest + signature) or carrying its own manifest when it matches the scope above +- [ ] Reasons truthful and not reused for tracking +- [ ] Generate Xcode's privacy report (it combines the SDK manifests) and use it for accurate Privacy Nutrition Label answers diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/storekit-2026-updates.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/storekit-2026-updates.md new file mode 100644 index 0000000..295376c --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/storekit-2026-updates.md @@ -0,0 +1,77 @@ +--- +name: storekit-2026-updates +description: In-app purchase and subscription changes 2025-10 to 2026-11 (offer codes for all IAP types, promo codes removed, 12-month-commitment monthly plans, Bundles and Suites, multiseat, retention messages) with verified StoreKit symbols +when-to-use: configuring subscriptions or IAP in App Store Connect, adding offer code redemption, planning iOS 27 subscription features, replacing IAP promo codes +keywords: offer codes, promo codes, retention messages, multiseat, Bundles, Suites, 12-month commitment, win-back offer, StoreKit Message, Retention Messaging API +priority: medium +requires: storekit2.md +related: app-review-guidelines.md, eu-alternative-distribution.md, app-store-connect-2026.md +--- + +# StoreKit and IAP Updates 2025-2026 + +Base StoreKit 2 code lives in [storekit2.md](storekit2.md). This file lists what changed. Dates are Apple publication dates; pages read 2026-11-13. + +## Timeline + +| Date | Change | Source | +|------|--------|--------| +| 2025-10-29 | **Offer codes for all IAP types**: consumable, non-consumable, non-renewing subscriptions, and auto-renewable subscriptions (including ones that do not auto-renew after the promotional period) | https://developer.apple.com/news/?id=gf6mgrs6 | +| 2026-03-27 | **Promo codes for In-App Purchases are no longer supported**: use offer codes | ASC release notes https://developer.apple.com/help/app-store-connect/release-notes/ | +| 2026-04-27 | **Monthly subscriptions with a 12-month commitment**: configure in App Store Connect, test in Xcode; subscribers can cancel to stop renewal after the commitment payments; available worldwide except the United States and Singapore on iOS/iPadOS/macOS/tvOS/visionOS 26.4+ with the 26.5 releases | https://developer.apple.com/news/?id=agq42lxe | +| 2026-07-15 | Submit IAPs, subscriptions and groups from the In-App Purchases and Subscriptions sections with **Add for Review** | ASC release notes | +| 2026-08-19 | The first consumable, non-consumable, auto-renewable and non-renewing item must be submitted with a new app version; later items of the same type do not, while the app has an approved version | ASC release notes | +| 2026-09-16 | **Bundles and Suites** (iOS/iPadOS/macOS/tvOS 27 or later, "later this year"): Bundles give access to several subscriptions in one purchase (one app, several apps of a developer, or several developers); Suites give one subscription across a set of apps of one developer. Access by request form; apps must use StoreKit 2 | https://developer.apple.com/news/?id=likeohx4 | +| 2026-10-22 | **Multiseat purchasing**: Volume Purchasing for Apple Business and Apple School Manager (launched 2026-10-22) and Group Purchases ("this winter"); enabled by default for subscriptions in App Store Connect, can be disabled or limited per channel | https://developer.apple.com/news/?id=yfo21auu, likeohx4 | +| 2026-11-04 | **Retention messages** in the cancellation flow (text, image or offer), configured in App Store Connect with eligibility and wait time between offers; Retention Messaging API access by request | https://developer.apple.com/news/?id=fk9ps3gv | + +Not verified: "expiring consumables". No Apple page in the news feed, App Store Connect release notes or guidelines (read 2026-11-13) states such a feature; guideline 3.1.1 still says purchased credits and in-game currencies may not expire. Do not build on it without a source. + +## Verified StoreKit symbols + +Checked on the Apple documentation JSON, 2026-11-13. + +| Need | Symbol | Notes | +|------|--------|-------| +| Redeem offer codes in SwiftUI (27.0+) | `offerCodeRedemption(options:isPresented:onCompletion:)`; `options` is `Set`, completion gets `Result, any Error>` | iOS, iPadOS, Mac Catalyst, macOS, visionOS 27.0 | +| Redeem offer codes in UIKit (27.0+) | `AppStore.presentOfferCodeRedeemSheet(from: UIViewController, options: Set = [])` returns `VerificationResult` | iOS, iPadOS, Mac Catalyst, visionOS 27.0 | +| Redeem offer codes in AppKit (27.0+) | `AppStore.presentOfferCodeRedeemSheet(from: NSWindow, options: Set = [])` returns `VerificationResult` | macOS 27.0 | +| Deprecated 27.0 (keep only for targets below 27) | SwiftUI `offerCodeRedemption(isPresented:onCompletion:)`; `AppStore.presentOfferCodeRedeemSheet(in: UIWindowScene)` (iOS 16+, visionOS 1+); `AppStore.presentOfferCodeRedeemSheet(from:)` (macOS 15+) | Apple marks each "deprecated 27.0" with "Use `presentOfferCodeRedeemSheet(from:options:)` / `offerCodeRedemption(options:isPresented:onCompletion:)` instead" | +| Detect an offer-code purchase | `Transaction.offerID` / `Transaction.offerType` (value `code`); same fields on `Product.SubscriptionInfo.RenewalInfo` | Server: `offerType` 3 in the signed payload; `OFFER_REDEEMED` notification for active subscribers | +| Offer kinds | `Product.SubscriptionOffer.OfferType`: `introductory`, `promotional`, `winBack` | | +| Win-back at purchase | `Product.PurchaseOption.winBackOffer(_:)` | | +| App Store messages | `Message`, `Message.Reason` (`billingIssue`, `generic`, `priceIncreaseConsent`, `winBackOffer`) | Delay or suppress with the `messages` sequence and `display(in:)` / `DisplayMessageAction` | +| Entitlements | `Transaction.currentEntitlements`, `Transaction.updates` | Start a listener at launch so out-of-app redemptions arrive | + +Source for offer codes: https://developer.apple.com/documentation/storekit/supporting-subscription-offer-codes-in-your-app. Offer-code limits there: up to 10 active offers per subscription; up to 1,000,000 redemptions per app per quarter. + +Retention messages are server-to-server (https://developer.apple.com/documentation/retentionmessaging): the Retention Messaging API selects the message when a subscriber taps Cancel Subscription; four message types (text, text with image, switch-plan, promotional offer); visible on iOS/iPadOS 15.1+, visionOS 1+, macOS 14+; the production real-time URL needs a passed performance test; configuring default messages is the simplest route and the documented fallback if the real-time response fails. Called a "pre-release" with request-based access. + +## Bundles, Suites, multiseat, billing plans: client symbols + +Each symbol below was read on its Apple JSON page on 2026-11-13 (`https://developer.apple.com/tutorials/data/documentation/storekit/.json`; `introducedAt` shown, `b` = beta). Configure the products in App Store Connect and test with Xcode's StoreKit testing. + +| Need | Symbol | Availability | +|------|--------|--------------| +| Bundle / Suite product types | `Product.ProductType.subscriptionBundle`, `.subscriptionSuite` | 27.0 | +| Merchandise subscriptions inside a Bundle | `Product.SubscriptionInfo.bundledSubscriptions` of type `[BundledSubscription]` (`displayName`, `displayPrice`, `price`, `subscriptionGroupID`, `isFamilyShareable`...) | 27.0 | +| Bundle fields on purchases | `Transaction.bundleProductID`, `bundleTransactionID`, `bundleOriginalTransactionID`, `bundleSubscriptionGroupID`; on `RenewalInfo` also `willUnbundle` | all of these `@backDeployed(before: 27.0)` (introducedAt 15.0) | +| Monthly plan with 12-month commitment: read terms | `Product.SubscriptionInfo.pricingTerms` of type `[PricingTerms]`; `PricingTerms.billingPlanType`, `.subscriptionOffers`, `.pricingModel` (`SinglePrice`, `SeatBasedPricing`) | 26.4 (`SeatBasedPricing` 27.3b) | +| Billing plan values | `Product.SubscriptionInfo.BillingPlanType`: `monthly`, `upFront` | 26.4 | +| Buy a billing plan | `Product.PurchaseOption.billingPlanType(_:)` | 26.4 | +| Commitment state | `Transaction.commitmentInfo` (`billingPeriodNumber`, `totalBillingPeriods`, `expirationDate`, `price`); `RenewalInfo.commitmentInfo`, `RenewalInfo.renewalBillingPlanType`, `Transaction.billingPlanType` | 26.4. `PricingTerms.commitmentInfo` and `.billingPrice` are marked Deprecated | +| Pick pricing terms in the built-in store views | `View.preferredSubscriptionPricingTerms(_:)` (closure `(Product, SubscriptionInfo) -> SubscriptionInfo.PricingTerms?`) | 26.4; iOS 26.5 notes describe it | +| Multiseat | `Product.supportsMultiSeatPurchase`, `Product.PurchaseOption.seats(_:)`, `multiSeatInvitationSheetSuppressed(_:)`, `RenewalInfo.renewalQuantity` / `multiSeatInfo`, `SubscriptionInfo.multiSeatDataSharingConsentEligibility` | `supportsMultiSeatPurchase` 27.3b; `seats(_:)` `@backDeployed(before: 27.3)` | +| Volume purchase ownership and refunds | `Transaction.OwnershipType.assigned`; `Transaction.revocationType` of type `Transaction.RevocationType?` (`fullRefund`, `proratedRefund`, `familyRevocation`, `assignmentRevocation`); `revocationPercentage` | 26.4 (`assigned`: iOS 27 notes). The iOS 27 notes name the case `assignmentRevoked`, the symbol page lists `assignmentRevocation`: trust the symbol page | +| Promotional offers signed with JWS | `Product.PurchaseOption.promotionalOffer(_:compactJWS:)` (returns `[PurchaseOption]`) | `@backDeployed(before: 26.0)` | +| Merchandise an offer in SwiftUI | `SubscriptionOfferView` (configurable by `SubscriptionOfferViewStyleConfiguration`) | 26.0 iOS, iPadOS, visionOS | +| Detect an age-rating change | `AppStore.ageRatingCode`, `Int?`, `async` getter | 26.2 | + +Sources: Apple iOS 26.5 notes ("PricingTerms", "CommitmentInfo", `preferredSubscriptionPricingTerms(_:)`), iOS 27 notes (Bundles, Suites, volume purchases) and iOS 27.3 beta notes (`supportsMultiSeatPurchase`), https://developer.apple.com/documentation/ios-ipados-release-notes, read 2026-11-13. Guides: `supporting-multiseat-purchases-in-your-app`, `testing-multiseat-subscriptions` (named in the `supportsMultiSeatPurchase` page; not read). + +## Checklist + +- [ ] Promo-code campaigns migrated to offer codes +- [ ] Transaction listener starts at launch (offer codes redeemed outside the app) +- [ ] Multiseat setting reviewed per subscription (default is on) +- [ ] Bundles/Suites access requested early if needed for iOS 27 diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/storekit2.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/storekit2.md index c674838..d6e4bc1 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/storekit2.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/storekit2.md @@ -4,11 +4,13 @@ description: StoreKit 2 in-app purchases, subscriptions, transaction management, when-to-use: implementing purchases, subscriptions, restoring transactions keywords: StoreKit, in-app purchase, subscription, Product, Transaction priority: high -related: app-store.md, testflight.md +related: app-store.md, testflight.md, storekit-2026-updates.md --- # StoreKit 2 +2025-2026 changes (offer codes for all IAP types, promo codes removed, Bundles/Suites, multiseat, retention messages) and verified symbols: [storekit-2026-updates.md](storekit-2026-updates.md). + ## Product Types | Type | Description | diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/testflight.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/testflight.md index 62d9e3b..dc23b16 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/testflight.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/build-distribution/references/testflight.md @@ -5,7 +5,7 @@ when-to-use: beta testing apps, distributing to testers, collecting feedback keywords: TestFlight, beta, testing, internal tester, external tester, App Store Connect priority: high requires: code-signing.md -related: app-store.md +related: app-store.md, app-store-connect-2026.md --- # TestFlight Beta Testing @@ -20,30 +20,32 @@ related: app-store.md ## Key Concepts +Source for all limits below: https://developer.apple.com/help/app-store-connect/test-a-beta-version/testflight-overview (read 2026-11-13). + ### Internal Testers -App Store Connect users (up to 100). +App Store Connect users with access to your content (up to 100). **Key Points:** -- No review required -- Immediate access -- All builds available -- Must have App Store Connect role +- Must have an App Store Connect role +- Builds are assigned through groups ### External Testers -Public beta (up to 10,000). +Up to 10,000 people, invited by email or public link. **Key Points:** -- Beta App Review required (first build) -- Public link option +- The first build added to a group is sent to App Review; subsequent builds may not require a full review, and testing starts once a build is approved +- Public link invitations: criteria you set can limit the number of testers +- A build can be tested for up to 90 days - Groups for organization -- 90-day expiration ### Build Distribution -| Channel | Review | Limit | Speed | -|---------|--------|-------|-------| -| Internal | None | 100 | Immediate | -| External | First build | 10,000 | 24-48h first | +| Channel | Review | Limit | +|---------|--------|-------| +| Internal | None stated | 100 App Store Connect users | +| External | First build of the app | 10,000 testers | + +macOS builds for TestFlight and the App Store must not carry the `com.apple.quarantine` extended attribute (see [app-store.md](app-store.md)). --- @@ -56,21 +58,20 @@ Public beta (up to 10,000). 3. Select Upload 4. Wait for processing -### Via CLI +### Via CLI and API + +Supported upload paths for an iOS/iPadOS/tvOS/visionOS/watchOS build: Xcode (Organizer), Swift Playground, Transporter, `altool`, the App Store Connect API (`POST /v1/buildUploads`), or Xcode Cloud. Source: https://developer.apple.com/help/app-store-connect/manage-builds/upload-builds (read 2026-11-13). Upload for all target types is supported by Transporter and altool. Uploading with Xcode needs Xcode 14 or later (Xcode 15 or later for visionOS). ```bash -# Upload via altool -xcrun altool --upload-app \ - -f MyApp.ipa \ - -t ios \ - -u "dev@company.com" \ - -p "@keychain:AC_PASSWORD" - -# Or via xcrun -xcrun notarytool submit MyApp.ipa \ - --keychain-profile "profile" +# Validate, then upload with altool (invoked through xcrun) +xcrun altool --validate-app -f MyApp.ipa -t ios -u "dev@company.com" -p "@keychain:AC_PASSWORD" +xcrun altool --upload-app -f MyApp.ipa -t ios -u "dev@company.com" -p "@keychain:AC_PASSWORD" ``` +- For API-driven pipelines Apple suggests uploading the binary with the Transporter command-line tool and the same JWTs you use for the App Store Connect API; the REST route is "Create a Build Upload" (https://developer.apple.com/documentation/appstoreconnectapi/post-v1-builduploads, read 2026-11-13). +- `xcrun notarytool` is **not** an upload path for builds: it submits macOS software (apps, disk images, flat packages) to the Apple notary service for Developer ID distribution. See `macos` skill `references/notarization.md`. +- Build status and warnings are visible in App Store Connect; webhooks can notify your server when a build upload or beta build changes status (see [app-store-connect-2026.md](app-store-connect-2026.md)). + ### Via fastlane ```ruby @@ -84,11 +85,7 @@ end ## Build Processing -**Timeline:** -- Upload: Few minutes -- Processing: 15-30 minutes -- Internal: Immediate after processing -- External review: 24-48 hours (first build) +A build must finish processing in Apple's system before it appears in App Store Connect; you get an email when it is done. No duration is published, so rely on the email or a build-status webhook, not a fixed wait (https://developer.apple.com/help/app-store-connect/manage-builds/upload-builds, read 2026-11-13). --- diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/SKILL.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/SKILL.md new file mode 100644 index 0000000..78efdd6 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/SKILL.md @@ -0,0 +1,91 @@ +--- +name: graphics-games +description: Use when building GPU rendering or games on Apple platforms — Metal 4 (command model, ML command encoder, tensors), MetalFX upscaling and frame interpolation, GameKit activities and challenges, Game Controller input, Game Porting Toolkit 4 — or when choosing between Metal, RealityKit, SpriteKit and SceneKit. +versions: + metal: 4 + ios: 27.2 +user-invocable: false +references: references/metal4.md, references/metalfx.md, references/gamekit.md, references/game-controller.md, references/engines-and-porting.md +related-skills: swift-core, swiftui-core, solid-swift, ios, macos, ipados, tvos, visionos, apple-intelligence, media-vision +--- + + +Covers the graphics and game surface of the Apple SDKs, verified against Apple's documentation JSON on 2026-11-13: the Metal 4 command model (MTL4CommandQueue, MTL4CommandBuffer, MTL4CommandAllocator, MTL4ArgumentTable, MTL4MachineLearningCommandEncoder, tensors), MetalFX (MTL4FXSpatialScaler, MTL4FXFrameInterpolator, MTL4FXTemporalDenoisedScaler), GameKit (GKGameActivity, GKChallengeDefinition, the deprecation of GKChallenge), Game Controller (GCController, GCControllerLiveInput, the 27.0 Home button settings manager), Game Porting Toolkit 4, the Apple Games app, and a decision table for Metal vs RealityKit vs SpriteKit vs SceneKit (deprecated 26.0). + +Every symbol cites its JSON page and availability; symbols known only from a WWDC26 session are labelled as session claims. RealityKit and visionOS 3D content are not duplicated: the table links to the visionos references. + + +# Graphics and Games + +Metal, MetalFX, GameKit, Game Controller and porting for iOS, iPadOS, macOS, tvOS and visionOS. + +## Agent Workflow (MANDATORY) + +Before ANY implementation, delegate via `Task` — spawn 3 agents in parallel (single message, 3 `Task` calls): + +1. **fuse-ai-pilot:explore-codebase** - Find existing Metal, MetalFX, GameKit and GameController usage and which Metal family the renderer targets +2. **fuse-ai-pilot:research-expert** - Re-verify every symbol on its Apple JSON page (`https://developer.apple.com/tutorials/data/documentation/.json`); the apple-docs MCP search is unreliable, never conclude absence from it +3. **mcp__apple-docs__search_apple_docs** - Cross-check only; confirm availability on the JSON page + +After implementation, run **fuse-ai-pilot:sniper** for validation. + +--- + +## Overview + +### When to Use + +- Writing or porting a renderer, adding ML to the frame, upscaling or frame generation +- Adding Game Center activities, challenges, or Games app visibility +- Supporting game controllers, virtual controllers, spatial controllers +- Choosing between Metal, RealityKit, SpriteKit and SceneKit + +### Why this skill + +| Feature | Benefit | +|---------|---------| +| Verified availability per symbol | No Metal 4 or 27.x API used on a target that lacks it | +| SceneKit deprecation (26.0) | No new 3D work started on a deprecated framework | +| Session claims labelled | Session-only facts are never presented as API fact | + +--- + +## Key Concepts + +### Metal 4 +New `MTL4*` command types, argument tables instead of per-encoder binding, and explicit barriers. Gate on `device.supportsFamily(.metal4)`. + +### MetalFX +Descriptors create scalers and the interpolator; Metal 4 variants take an `MTL4Compiler`. Always check `supportsMetal4FX(_:)`. + +### GameKit +`GKGameActivity` (26.0) and `GKChallengeDefinition` (26.0) are configured in the GameKit Configuration file; `GKChallenge` is deprecated since 26.0. + +### Game Controller +Poll `GCControllerLiveInput` in the game loop; keep non-controller input paths playable. + +--- + +## Reference Guide + +| Need | Reference | +|------|-----------| +| Metal 4 command model, ML encoder, tensors, profiling | [metal4.md](references/metal4.md) | +| Spatial scaler, frame interpolator, denoised scaler | [metalfx.md](references/metalfx.md) | +| Game Center activities, challenges, Games app | [gamekit.md](references/gamekit.md) | +| GCController, virtual and spatial controllers, Home button settings | [game-controller.md](references/game-controller.md) | +| Metal vs RealityKit vs SpriteKit vs SceneKit, Game Porting Toolkit 4 | [engines-and-porting.md](references/engines-and-porting.md) | +| RealityKit entities and RealityKit 27 | [../visionos/references/realitykit.md](../visionos/references/realitykit.md), [../visionos/references/realitykit-27.md](../visionos/references/realitykit-27.md) | +| Foundation Models, Core AI language model | `apple-intelligence` skill | + +--- + +## Best Practices + +1. **Gate by capability** - `supportsFamily(.metal4)`, `supportsMetal4FX(_:)`, never by OS version alone +2. **One allocator per frame in flight** - reset it only after the GPU finished that frame +3. **Barriers are yours** - Metal 4 resources are untracked +4. **No new SceneKit code** - deprecated 26.0 on every platform +5. **Configure activities and challenges in Xcode** - not in code; use `GKGameActivity` and `GKChallengeDefinition` +6. **Keep a non-controller path** - keyboard, touch or `GCVirtualController` where the platform has it +7. **Label session claims** - cite session number and say symbols were not checked diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/references/engines-and-porting.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/references/engines-and-porting.md new file mode 100644 index 0000000..7ff0bf9 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/references/engines-and-porting.md @@ -0,0 +1,46 @@ +# Choosing a rendering stack, and Game Porting Toolkit 4 + +Verified 2026-11-13: symbol JSON pages (`scenekit`, `spritekit`, `realitykit`, `metal`), https://developer.apple.com/games/game-porting-toolkit/, https://developer.apple.com/games/, session https://developer.apple.com/videos/play/wwdc2026/357/. + +## Which framework + +| Framework | Platform status (landing page JSON) | Pick it when | +|-----------|-------------------------------------|--------------| +| Metal 4 / Metal | iOS 8.0, macOS 10.11, tvOS 9.0, visionOS 1.0 | You own the renderer: custom pipelines, ML in the frame, ports from DirectX/Vulkan. See [metal4.md](metal4.md) | +| RealityKit | iOS 13.0, macOS 10.15, tvOS 26.0, visionOS 1.0 | 3D scenes with entities, components, physics and no renderer to write; the path for 3D on visionOS. See [visionos realitykit.md](../../visionos/references/realitykit.md) and [realitykit-27.md](../../visionos/references/realitykit-27.md) | +| SpriteKit | iOS 7.0, macOS 10.9, tvOS 9.0, visionOS 1.0, watchOS 10.0; no deprecation flag | 2D games, particles, simple physics, `SKView` embedded in UIKit/SwiftUI | +| SceneKit | **deprecated 26.0 on every platform** (introduced iOS 8.0) | Maintaining an existing app only; do not start new 3D work on it | + +SceneKit page note (visionOS): SceneKit content shows only in 2D views and textures there; use RealityKit for immersive 3D. + +Rules of thumb: + +- New 3D game or app, no custom renderer: RealityKit. +- New 3D with its own look, ML or heavy compute: Metal 4. +- 2D: SpriteKit; drop to Metal only when profiling says so. +- Existing SceneKit app: the framework is deprecated since 26.0 on every platform (symbol page flag); plan a move to RealityKit or Metal. Apple's page does not name a replacement. + +## Game Porting Toolkit 4 + +Page read 2026-11-13: https://developer.apple.com/games/game-porting-toolkit/. + +| Piece | What Apple states | +|-------|-------------------| +| Agent skills | Companion repository https://github.com/apple/game-porting-toolkit/ with open-source agent skills and sample code: DirectX to Metal, Metal command-line debugging, game controller support, polish, optimization | +| Metal command-line tools | Agents can capture, debug and profile Metal workloads from the command line | +| Evaluation environment for Windows games | Runs the unmodified Windows executable on Apple silicon; now supports Metal 4; works with Metal HUD, Metal GPU capture, Metal System Trace | +| Metal shader converter, metal-cpp | Convert HLSL to Metal; C++ interface to Metal | +| Metal Developer Tools for Windows, Mac Remote Developer Tools | Build and debug on a Mac from Visual Studio on PC | + +Session 357 chapters (page text): porting assistant workflow, windowing and frame pacing, scene rendering with Metal 4, debugging with GPU command-line tools, game controllers and MetalFX. Related WWDC25: 211 "Go further with Metal 4 games". Session content beyond the chapter list is not verified here. + +## Distribution and discovery + +The Apple Games app and Game Center integration are in [gamekit.md](gamekit.md). Human Interface Guidelines for games: https://developer.apple.com/design/human-interface-guidelines/designing-for-games (linked from the Game Porting Toolkit page). + +## Workflow + +1. Evaluate the Windows build in the evaluation environment for a baseline. +2. Port rendering to Metal 4; add MetalFX ([metalfx.md](metalfx.md)). +3. Add controller support ([game-controller.md](game-controller.md)). +4. Profile with Metal tools ([metal4.md](metal4.md), session 388). diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/references/game-controller.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/references/game-controller.md new file mode 100644 index 0000000..7260697 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/references/game-controller.md @@ -0,0 +1,62 @@ +# Game Controller + +Verified 2026-11-13: `https://developer.apple.com/tutorials/data/documentation/gamecontroller/.json`, `.../updates/gamecontroller.json`, iOS 27 release notes (https://developer.apple.com/documentation/ios-ipados-release-notes/ios-ipados-27-release-notes). + +## Overview + +| Symbol | Availability (symbol page) | Note | +|--------|----------------------------|------| +| `GCController` | iOS 7.0, macOS 10.9, tvOS 9.0, visionOS 1.0 | `controllers()`, `current` (14.0), `extendedGamepad`, `input` (17.0) | +| `GCControllerLiveInput` | iOS 17.0, macOS 14.0, tvOS 17.0, visionOS 1.0 | Poll in your game loop: `nextInputState()`, `capture()` | +| `GCController.DidConnectMessage` | 26.0 | Message type with the connected `controller`; the classic `NSNotification.Name.GCControllerDidConnect` also exists | +| `GCVirtualController` | iOS 15.0, iPadOS 15.0, Mac Catalyst 15.0 only | On-screen controls for games that support controllers (`connect(replyHandler:)`, `disconnect()`) | +| `GCStylus` | visionOS 26.0 | Physical stylus (`styli`, `input`, `haptics`) | +| `GCSpatialAccessory` | visionOS 27.0 | No abstract on its page; see [visionos arkit-spatial.md](../../visionos/references/arkit-spatial.md) for spatial accessories | +| `GCControllerHomeButtonSettingsManager` | iOS/iPadOS/macOS/visionOS 27.0 | Reads the system Home button settings: `controllerHomeButtonInAppAction`, `controllerHomeButtonSystemAction`, `settingsUpdates`, `openControllerHomeButtonSettings(for:)` | +| `GCRacingWheel` | macOS 13.0, Mac Catalyst 16.0 | Racing wheels | + +Info.plist keys (landing page `gamecontroller`): `GCSupportedGameControllers`, `GCSupportsControllerUserInteraction`, `GCSupportsMultipleMicroGamepads`. Apple's June 2025 entry adds spatial controller support (product category check), `GCStylus`, and `NSAccessoryTrackingUsageDescription` when you need accessory-tracking data; its `GCSupportedGameControllers` value for spatial controllers is `SpatialGamepad`. + +## Connect and poll (Swift 6) + +```swift +import GameController + +/// Observes controller connections and exposes the current controller. +@MainActor +final class ControllerMonitor { + private var token: (any NSObjectProtocol)? + + func start() { + token = NotificationCenter.default.addObserver( + forName: .GCControllerDidConnect, object: nil, queue: .main + ) { note in + guard let controller = note.object as? GCController else { return } + // Capture only Sendable values; read input from the game loop, not here. + _ = controller.vendorName + } + GCController.startWirelessControllerDiscovery() + } + + /// Called once per frame by the game loop. + func poll() { + guard let input = GCController.current?.input else { return } + if let state = input.nextInputState() { _ = state } // read buttons and sticks from the state + } +} +``` + +Use `GCController.controllers()` for controllers that are already connected at launch. `startWirelessControllerDiscovery(completionHandler:)` has an optional handler (verified). + +## Changes to know + +| Change | Source | +|--------|--------| +| PlayStation Access controller supported on macOS, iPadOS and iOS; players can save custom input profiles in game controller settings | iOS 27 release notes, Game Controller section | +| Home button settings API (27.0) | symbol page above | +| visionOS: game controller events can be delivered through Game Controller instead of the responder chain by adding a user interaction (June 2024 entry) | `updates/gamecontroller` | + +## Rules + +- Never assume a controller: keyboard, mouse, touch or `GCVirtualController` must stay playable. +- tvOS focus-driven menus: see the `tvos` skill; this file covers gameplay input only. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/references/gamekit.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/references/gamekit.md new file mode 100644 index 0000000..4e6bf06 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/references/gamekit.md @@ -0,0 +1,55 @@ +# GameKit: Game Center activities and challenges, the Games app + +Verified 2026-11-13: symbol JSON pages under `https://developer.apple.com/tutorials/data/documentation/gamekit/`, `.../updates/gamekit.json` (newest entry June 2025), https://developer.apple.com/games-app/ and https://developer.apple.com/games/. + +## Overview + +| Symbol | Availability (symbol page) | Role | +|--------|----------------------------|------| +| `GKGameActivity` | iOS/iPadOS/macOS/tvOS/visionOS 26.0 (no watchOS) | A running activity that players can join; carries scores, achievements, party code | +| `GKGameActivityDefinition` | 26.0, same platforms | Static metadata you configure (title, `playStyle`, `supportsPartyCode`, `playerRange`, `fallbackURL`) | +| `GKChallengeDefinition` | 26.0 incl. watchOS | Static metadata of a challenge (`durationOptions`, `isRepeatable`, `leaderboard`) | +| `GKChallenge`, `GKScoreChallenge` | deprecated 26.0 (introduced iOS 6.0) | Old player-issued challenge classes; do not start new code on them | +| `GKAccessPoint`, `GKLocalPlayer` | long-standing | Entry point UI, authentication | + +Apple's June 2025 update list: configure Game Activities and Challenges in a GameKit Configuration file in Xcode (challenges also in App Store Connect); `GKChallengeDefinition` retrieves the metadata you define; leaderboard score submissions can be observed through Settings > Developer > Notify About Score Submissions on iOS. Voice chat should use SharePlay, `GKVoiceChat` is deprecated (June 2024 entry). + +## Activity lifecycle + +```swift +import GameKit + +/// Starts a Game Center activity for a definition configured in the GameKit Configuration file. +func startActivity() async throws -> GKGameActivity { + let definitions = try await withCheckedThrowingContinuation { (c: CheckedContinuation<[GKGameActivityDefinition], Error>) in + GKGameActivityDefinition.loadGameActivityDefinitions { defs, error in + if let defs { c.resume(returning: defs) } else { c.resume(throwing: error ?? CancellationError()) } + } + } + guard let definition = definitions.first else { throw CancellationError() } + return try GKGameActivity.start(definition: definition) // or start(definition:partyCode:) +} +``` + +| Need | API (all verified on `gkgameactivity`) | +|------|----------------------------------------| +| States | `start()`, `pause()`, `resume()`, `end()`, `state` | +| Scores and progress | `setScore(on:to:)`, `setScore(on:to:context:)`, `setProgress(on:to:)`, `setAchievementCompleted(_:)`, `leaderboardScores`, `achievements` | +| Party codes | `partyCode`, `partyURL`, `GKGameActivity.isValidPartyCode(_:)`, `validPartyCodeAlphabet` | +| Matchmaking from an activity | `makeMatchRequest()`, `findMatch(completionHandler:)`, `findPlayersForHostedMatch(completionHandler:)` | +| Launch handling | `checkPendingGameActivityExistence(completionHandler:)` | +| Custom data | `properties` (`[String: String]`) | + +`GKGameActivityPlayStyle` has `asynchronous`, `synchronous`, `unspecified`. Authenticate first: `GKLocalPlayer.local.authenticateHandler` (the `local` class property and `authenticateHandler` are long-standing and verified). + +## Challenges + +`GKChallengeDefinition.loadChallengeDefinitions(completionHandler:)` (26.0) loads definitions; `hasActiveChallenges(completionHandler:)` reports active ones. Challenge rules, durations and the linked leaderboard are configured in Xcode or App Store Connect, not in code. Do not copy older tutorials that issue challenges through `GKChallenge` (deprecated 26.0). + +## The Games app + +Pre-installed on iOS 26, iPadOS 26 and macOS 26 or later (https://developer.apple.com/games-app/). Your game appears automatically; Game Center achievements, leaderboards, challenges, multiplayer activities and In-App Events raise its visibility. Session: WWDC25 215 "Engage players with the Apple Games app" (linked from that page). + +## Not verified + +iOS 27 release notes, Game Center section: "Fixed: When you trigger the Access Point, its completion handler is never invoked" (https://developer.apple.com/documentation/ios-ipados-release-notes/ios-ipados-27-release-notes, read 2026-11-13). No new GameKit symbol dated 2026 was found; the updates page stops at June 2025, which is not proof of no change. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/references/metal4.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/references/metal4.md new file mode 100644 index 0000000..a2768f8 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/references/metal4.md @@ -0,0 +1,81 @@ +# Metal 4: command model, ML encoder, tensors + +Verified 2026-11-13 on Apple's documentation JSON (`https://developer.apple.com/tutorials/data/documentation/.json`). Overview source: `metal/understanding-the-metal-4-core-api`. + +## Overview + +Metal 4 adds `MTL4*` types that are independent of the classic `MTL*` command types. All below are iOS/iPadOS/macOS/tvOS/visionOS 26.0 unless noted. + +| Concept | Metal 4 type | Replaces / differs from | +|---------|--------------|-------------------------| +| Queue | `MTL4CommandQueue` (`commit(_:options:)` takes an array of buffers) | `MTLCommandQueue` (iOS 8.0) | +| Command buffer | `MTL4CommandBuffer`, reusable after commit via `beginCommandBuffer(allocator:)` | transient single-use `MTLCommandBuffer` | +| Memory for commands | `MTL4CommandAllocator` (`reset()` when the frame's GPU work is done) | implicit | +| Resource binding | `MTL4ArgumentTable` (bound per encoder stage) | per-encoder `setBuffer` / `setTexture` calls | +| Encoders | `MTL4RenderCommandEncoder`, `MTL4ComputeCommandEncoder` (compute + blit + acceleration structures in one pass), `MTL4MachineLearningCommandEncoder` | separate render / compute / blit / ML encoders | +| Compilation | `MTL4Compiler` via `device.makeCompiler(descriptor:)` | | +| Hazards | all resources untracked: you add `barrier(afterEncoderStages:beforeEncoderStages:visibilityOptions:)` or fences / events | automatic hazard tracking | + +Detect support at runtime: `device.supportsFamily(.metal4)` (`MTLGPUFamily.metal4`, 26.0). Create an `MTL4CommandQueue` when supported, otherwise a classic queue; you can adopt Metal 4 incrementally and synchronize both queue kinds with `MTLEvent` (`signalEvent(_:value:)` / `waitForEvent(_:value:)`). + +## Minimal frame skeleton (Swift 6) + +```swift +import Metal + +enum MetalSetupError: Error { case unsupported } + +/// Encodes one empty compute pass and submits it on a Metal 4 queue. +func submitEmptyPass() throws { + guard let device = MTLCreateSystemDefaultDevice(), device.supportsFamily(.metal4), + let queue = device.makeMTL4CommandQueue(), + let allocator = device.makeCommandAllocator(), + let commandBuffer = device.makeCommandBuffer() else { throw MetalSetupError.unsupported } + + commandBuffer.beginCommandBuffer(allocator: allocator) + let encoder = commandBuffer.makeComputeCommandEncoder() + // bind an MTL4ArgumentTable, set a pipeline, call dispatchThreads(threadsPerGrid:threadsPerThreadgroup:) + encoder?.endEncoding() + commandBuffer.endCommandBuffer() + queue.commit([commandBuffer], options: nil) +} +``` + +Keep one allocator per frame in flight; call `allocator.reset()` only after the GPU finished that frame (signal an event on the queue and wait for it). + +## Machine learning command encoder (26.0) + +`MTL4MachineLearningCommandEncoder` runs a pre-trained network inside the command buffer, between your render and compute work. + +| Step | API (all verified) | +|------|--------------------| +| Create encoder | `commandBuffer.makeMachineLearningCommandEncoder()` | +| Pipeline | `MTL4Compiler.makeMachineLearningPipelineState(descriptor:)` with an `MTL4MachineLearningPipelineDescriptor` (`machineLearningFunctionDescriptor`, `setInputDimensions(_:bufferIndex:)`) | +| Configure pass | `setPipelineState(_:)`, `setArgumentTable(_:)` | +| Run | `dispatchNetwork(intermediatesHeap:)` with an `MTLHeap` for intermediates | + +Pages: `metal/mtl4machinelearningcommandencoder`, `metal/mtl4machinelearningpipelinestate`, `metal/machine-learning-passes`. Add a barrier between the ML pass and the pass that consumes its output. + +## Tensors and Metal Performance Primitives + +| Item | Status | +|------|--------| +| `MTLTensor`, `MTLTensorDescriptor`, `MTLTensorDataType`, `MTLDevice.makeTensor(descriptor:)` | 26.0, verified | +| Inline ML in a shader (tensor ops from Metal Performance Primitives, MSL side) | article `metal/running-inline-ml-operations-in-a-shader-with-metal-4` (macOS 26.0, Xcode 26.0) | +| Quantized data, multi-plane tensors, custom ops for Core AI on M5/A19 Neural Accelerators | session 330 only; no symbol checked here | +| Neural rendering: MetalFX neural denoising, learned tone mapper via the ML encoder, tensor API in shaders | session 359 only; sample `metal/training-a-neural-network-to-render-irradiance-in-real-time` | + +Sessions (read 2026-11-13): 330 https://developer.apple.com/videos/play/wwdc2026/330/ (MPP Programming Guide PDF linked there); 359 https://developer.apple.com/videos/play/wwdc2026/359/. Related WWDC25: 262 "Combine Metal 4 machine learning and graphics", 211 "Go further with Metal 4 games". The MPP tensor-ops library is MSL, not a Swift symbol: do not invent Swift names for it. + +## Profiling (session 388, WWDC26) + +Game Performance Overview in Instruments, `metalperftrace` on macOS, Control Center capture on iOS, the `StateReporting` framework (iOS/macOS/tvOS/visionOS/watchOS 27.0, verified landing) to tag metrics with game state, MetricKit for field data. Source: https://developer.apple.com/videos/play/wwdc2026/388/ (session claims, symbols not individually checked). + +## Decision guide + +| Need | Choose | +|------|--------| +| New renderer, ML in the frame, ports from DirectX/Vulkan | Metal 4 (`MTL4*`) | +| Existing classic Metal renderer | keep it; adopt `MTL4CommandQueue` for one subsystem at a time | +| Upscaling / frame generation / denoising | MetalFX, see [metalfx.md](metalfx.md) | +| 3D scene without writing a renderer | RealityKit, see [engines-and-porting.md](engines-and-porting.md) | diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/references/metalfx.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/references/metalfx.md new file mode 100644 index 0000000..036f206 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/graphics-games/references/metalfx.md @@ -0,0 +1,67 @@ +# MetalFX: upscaling, frame interpolation, denoising + +Verified 2026-11-13 on `https://developer.apple.com/tutorials/data/documentation/metalfx/.json`. + +## Overview + +MetalFX works with both classic Metal and Metal 4 ([metal4.md](metal4.md)). The Metal 4 variants take an `MTL4Compiler` at creation and encode into an `MTL4CommandBuffer`. + +| Effect | Descriptor (creates the effect) | Metal 4 protocol | Availability (symbol pages) | +|--------|---------------------------------|------------------|-----------------------------| +| Spatial upscale | `MTLFXSpatialScalerDescriptor` (iOS 16.0, macOS 13.0, visionOS 1.0, tvOS 27.1) | `MTL4FXSpatialScaler` | iOS/iPadOS/macOS/visionOS 26.0, tvOS 27.1 | +| Frame interpolation | `MTLFXFrameInterpolatorDescriptor` (iOS/macOS 26.0, tvOS 27.1, no visionOS) | `MTL4FXFrameInterpolator` | iOS/iPadOS/macOS 26.0, tvOS 27.1 | +| Temporal denoised upscale | `MTLFXTemporalDenoisedScalerDescriptor` (iOS 18.0, macOS 26.0, tvOS 27.1) | `MTL4FXTemporalDenoisedScaler` | iOS/iPadOS/macOS 26.0, tvOS 27.1 | + +Every descriptor exposes `supportsDevice(_:)` and `supportsMetal4FX(_:)` class methods. Check them before creating anything; fall back to native-resolution rendering when false. + +## Creation and encoding + +| Task | API | +|------|-----| +| Classic Metal | `descriptor.makeSpatialScaler(device:)`, `makeFrameInterpolator(device:)`, `makeTemporalDenoisedScaler(device:)` | +| Metal 4 | `descriptor.makeSpatialScaler(device:compiler:)`, `makeFrameInterpolator(device:compiler:)`, `makeTemporalDenoisedScaler(device:compiler:)` | +| Encode (Metal 4) | `scaler.encode(commandBuffer:)` with an `MTL4CommandBuffer` | + +Set every texture-format property on the descriptor to the exact format of the texture you later assign to the effect instance (Apple's note on `MTLFXFrameInterpolatorDescriptor`). + +```swift +import Metal +import MetalFX + +/// Builds a Metal 4 spatial upscaler, or nil when the device cannot run it. +func makeUpscaler(device: any MTLDevice, compiler: any MTL4Compiler, + input: (width: Int, height: Int), output: (width: Int, height: Int)) -> (any MTL4FXSpatialScaler)? { + guard MTLFXSpatialScalerDescriptor.supportsMetal4FX(device) else { return nil } + let descriptor = MTLFXSpatialScalerDescriptor() + descriptor.inputWidth = input.width + descriptor.inputHeight = input.height + descriptor.outputWidth = output.width + descriptor.outputHeight = output.height + descriptor.colorTextureFormat = .rgba16Float + descriptor.outputTextureFormat = .rgba16Float + descriptor.colorProcessingMode = .linear // also .perceptual, .hdr + return descriptor.makeSpatialScaler(device: device, compiler: compiler) +} +// Per frame: scaler.colorTexture = rendered; scaler.outputTexture = target; scaler.encode(commandBuffer: cb) +``` + +## Frame interpolation inputs + +`MTLFXFrameInterpolatorDescriptor` has a `scaler` (an `MTLFXFrameInterpolatableScaler`, such as the temporal denoised scaler) plus formats for color, depth, motion and UI textures, `isDistortionTextureEnabled`, `requiresPrevColorTexture`. The interpolator base protocol carries per-frame inputs: `colorTexture`, `depthTexture`, `motionTexture`, `deltaTime`, `jitterOffsetX/Y`, `fieldOfView`, `farPlane`, `isDepthReversed`, `isUITextureComposited`. The temporal scalers `MTLFXTemporalScaler` (iOS 16.0, macOS 13.0, tvOS 27.1) and `MTL4FXTemporalScaler` (26.0, tvOS 27.1) also exist; the interpolator's `scaler` property is typed `MTLFXFrameInterpolatableScaler`. + +## Neural denoising (WWDC26) + +Session 359 (https://developer.apple.com/videos/play/wwdc2026/359/, read 2026-11-13) covers MetalFX neural denoising with Maxon's Redshift Live as the case study. The class is `MTL4FXTemporalDenoisedScaler`; the session-level tuning advice is not verified symbol by symbol. + +## tvOS note + +The tvOS 27.1 availability above comes straight from the symbol JSON pages. The `tvos` skill does not cover MetalFX; use this reference. + +## Decision guide + +| Goal | Use | +|------|-----| +| Cheaper pixels, no motion data | `MTLFXSpatialScaler` | +| Upscale with motion + depth inputs | `MTLFXTemporalScaler` / `MTL4FXTemporalScaler` | +| Upscale plus denoise the frame | `MTL4FXTemporalDenoisedScaler` | +| Higher displayed frame rate | `MTLFXFrameInterpolator`, which takes a scaler plus motion and depth data | diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ios/SKILL.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ios/SKILL.md index c5fa0af..e40ed83 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ios/SKILL.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ios/SKILL.md @@ -5,8 +5,8 @@ versions: ios: 27.2 xcode: 27.2 user-invocable: false -references: references/simulator-tools.md, references/device-tools.md, references/ui-automation.md, references/debugging.md, references/uikit-integration.md -related-skills: swift-core, swiftui-core, ipados, mcp-tools +references: references/simulator-tools.md, references/device-tools.md, references/ui-automation.md, references/debugging.md, references/uikit-integration.md, references/uikit-26-27.md +related-skills: swift-core, swiftui-core, ipados, mcp-tools, apple-frameworks --- @@ -83,7 +83,21 @@ After implementation, run **fuse-ai-pilot:sniper** for validation. | Device deployment | [device-tools.md](references/device-tools.md) | | Touch automation | [ui-automation.md](references/ui-automation.md) | | LLDB debugging | [debugging.md](references/debugging.md) | -| UIKit in SwiftUI | [uikit-integration.md](references/uikit-integration.md) | +| UIKit in SwiftUI (native `Map` / `WebView` first) | [uikit-integration.md](references/uikit-integration.md) | +| UIKit 26-27: automatic Observable tracking, iPhone Duo hinge and vertical bars, state restoration, TextKit tables, menu images | [uikit-26-27.md](references/uikit-26-27.md) | +| Passkeys, MapKit, CloudKit, TipKit, notifications, background tasks, HealthKit, CarPlay, Chart3D | [apple-frameworks](../apple-frameworks/SKILL.md) | +| Toolbars, search as a tab, tab bar minimize, scroll edge effects, menu icons | [toolbars-navigation.md](../swiftui-core/references/toolbars-navigation.md) | + +--- + +## Liquid Glass on iOS + +API table and rules live in [liquid-glass.md](../swiftui-core/references/liquid-glass.md); do not duplicate them here. iOS specifics (HIG, read 2026-11-13): + +- The tab bar floats above content at the bottom ([HIG tab-bars](https://developer.apple.com/design/human-interface-guidelines/tab-bars), 2026-06-08); with an accessory (MiniPlayer) it can minimize on scroll (`tabBarMinimizeBehavior(_:)`, `tabViewBottomAccessory(content:)`, iOS 26.0). A dedicated search tab (`Tab(role: .search)`) can sit at the trailing end; alternatives are search in a bottom or top toolbar ([HIG search-fields](https://developer.apple.com/design/human-interface-guidelines/search-fields)). +- Toolbars ([HIG toolbars](https://developer.apple.com/design/human-interface-guidelines/toolbars), 2025-12-16): space is limited, so put essential actions first and the rest in a More menu; group items with `ToolbarSpacer`; do not paint custom bar backgrounds. +- Scroll edge effects under bars ([HIG scroll-views](https://developer.apple.com/design/human-interface-guidelines/scroll-views), 2026-06-08): keep `.automatic`; `.soft` needs legibility testing. Standard bars, sheets and menus take glass from the system ([HIG materials](https://developer.apple.com/design/human-interface-guidelines/materials)). +- Live Activities: limited-width compact/minimal layouts (landscape, iPhone Duo, many activities) - [hig-system-surfaces.md](../swiftui-core/references/hig-system-surfaces.md). --- diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ios/references/uikit-26-27.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ios/references/uikit-26-27.md new file mode 100644 index 0000000..ee8ffdb --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ios/references/uikit-26-27.md @@ -0,0 +1,79 @@ +--- +name: uikit-26-27 +description: UIKit 26 and 27 additions verified on Apple docs - automatic Observable tracking, iPhone Duo hinge and vertical bar APIs, state restoration extension, TextKit tables and viewport, menu image visibility, navigation bar minimization +when-to-use: writing or migrating UIKit code for iOS 26/27, reacting to Observable models in views, supporting iPhone Duo, extending state restoration, building rich text with tables +keywords: UIHingeInteraction, UIHinge, preferredVerticalBarBehavior, verticalBarEdge, axisBehavior, UIScene.extendStateRestoration, updateProperties, UIObservationTrackingEnabled, NSTextTable, NSTextViewportLayoutControllerDelegate, UITextAttachmentViewProviderReusePolicy, preferredImageVisibility, navigationBarMinimization +priority: high +related: uikit-integration.md, ../../ipados/references/menu-bar-windows.md, ../../ipados/references/resizing-and-mirroring.md, ../../swiftui-core/references/hig-iphone-duo.md +--- + +# UIKit 26 and 27 + +Sources, all read 2026-11-13: UIKit updates page https://developer.apple.com/documentation/updates/uikit (JSON `.../tutorials/data/documentation/updates/UIKit.json`), iOS and iPadOS 27 release notes https://developer.apple.com/documentation/ios-ipados-release-notes/ios-ipados-27-release-notes, symbol pages `developer.apple.com/tutorials/data/documentation/uikit/.json` (`introducedAt` quoted). Version `27.1` APIs are above the iOS 27.0 floor: gate with `#available`. + +## Automatic Observable tracking (iOS 26.0) + +Source: https://developer.apple.com/documentation/uikit/updating-views-automatically-with-observation-tracking-in-uikit. + +- Read `@Observable` properties inside `updateProperties()` (view controller or view, iOS 26.0 per `setNeedsUpdateProperties()`) or `layoutSubviews()`: UIKit tracks what you read and re-runs the method when it changes. No manual `setNeedsLayout()` bookkeeping. +- `updateProperties()` runs after trait collection updates and before `layoutSubviews()`: put text, colors and visibility there; keep geometry in `layoutSubviews()`. Call `setNeedsUpdateProperties()` to force a pass. +- Cells: `cell.configurationUpdateHandler` is tracked too (read the model inside the handler). +- `UICollectionViewCompositionalLayoutSectionProvider` closures take part in tracking (June 2026), so a model change invalidates the compositional layout. +- iOS 18 needs Info.plist `UIObservationTrackingEnabled` = YES; "In iOS 26 and later, this key isn't required" (https://developer.apple.com/documentation/bundleresources/information-property-list/uiobservationtrackingenabled). + +```swift +@Observable final class MessageModel { var showStatus = false; var statusText = "" } + +final class InboxViewController: UIViewController { + let model = MessageModel() + private let statusLabel = UILabel() + + override func updateProperties() { + super.updateProperties() + statusLabel.alpha = model.showStatus ? 1 : 0 // tracked read + statusLabel.text = model.statusText + } +} +``` + +## iPhone Duo: hinge and vertical bars (iOS 27.1) + +Layout types (`UIArrangementViewController`, `UIView.ReservedRegion`) are in [hig-iphone-duo.md](../../swiftui-core/references/hig-iphone-duo.md). Additional UIKit symbols, all `introducedAt` 27.1: + +| Need | Symbol | +|------|--------| +| Observe the hinge | `UIHingeInteraction(updateHandler:)` on a view; `isEnabled`; handler gets `UIHingeInteraction.Update` whose `hinge` is `nil` when the view leaves a hierarchy that provides hinge updates | +| Read the hinge | `UIHinge.angle` (`CGFloat`), `UIHinge.status`: `closed`, `partiallyOpen`, `fullyOpen`, `unknown` | +| Opt out of vertical bars | override `UIViewController.preferredVerticalBarBehavior` (`UIVerticalBarBehavior`: `automatic`, `disabled`); `childForPreferredVerticalBarBehavior`; `setNeedsUpdateOfVerticalBarConfiguration()` | +| Where vertical bars go | `UITraitCollection.verticalBarEdge` (`UIVerticalBarEdge`: leading or trailing); React via `systemTraitsAffectingVerticalBarEdge` | +| Bar item axis | `UIBarButtonItem.axisBehavior` (`UIBarButtonItem.AxisBehavior`: `automatic`, `horizontalOnly`, `verticalPreferred`); `UINavigationItem.verticalBarCompressionBehavior` (`UIVerticalBarCompressionBehavior`, e.g. `.prefersBarItems`, `.prefersTabBar`) | +| Query reserved regions | `UIView.reservedRegions(kind:options:)` | +| Outer display while capturing | `UISceneAccessory.cameraCapture(sceneConfiguration:)` (27.1), registered with `UIViewController.registerSceneAccessory(_:)` (27.0) | + +Apple's guidance for `preferredVerticalBarBehavior`: disable the vertical bar only for UIs better served by horizontal bars (full-screen video player, non-scrolling layout such as a calculator); treat it as a stable choice, not a per-state toggle. + +## App life cycle and state + +- `UIScene.extendStateRestoration()` / `completeStateRestoration()`: with the iOS 27 SDK use them to extend state restoration across the background-to-foreground activation transition (iOS 27 notes; the symbols list `introducedAt` 15.0, the extension behavior is tied to linking against the 27 SDK). +- Scene-based life cycle is mandatory with the 27 SDK; a launch screen key is required; `canOpenURL:` is deprecated: see `swift-core/references/sdk-27-changes.md`. + +## Menus and bars + +- `UIMenuElement.preferredImageVisibility` (27.0; `UIMenuElement.ImageVisibility`: `automatic`, `hidden`, `visible`; also on `UIMenu`, `UIAction`, `UICommand`, `UIKeyCommand` initializers): iPadOS and macOS menu bar and context menus hide menu element images by default; system items (Settings, Share, Print) stay visible. +- `UINavigationItem.navigationBarMinimization` (27.0, `UIBarMinimization`) replaces `barMinimizeBehavior` and `barMinimizationSafeAreaAdjustment`. +- Tab bar (WWDC26 session 278): `UITabBarController.prominentTabIdentifier` (27.0) makes any tab the always-visible prominent tab; iPhone apps can opt into a sidebar with `tabBarController.sidebar.preferredPlacement = .sidebar` (an app choice, no user toggle; check `sidebar.isAvailable`). Navigation bar: `navigationItem.navigationBarMinimization.minimizationBehavior` (e.g. `.onScrollDown`) and `.safeAreaAdjustment` (e.g. `.disabled`). Scroll edge effect `.automatic` no longer switches between soft and hard: re-evaluate overrides, especially `.soft`. +- `UISearchController` with center placement shows the scope bar inline beside the search field (27 SDK). +- Siri can load content from `UIDragInteractionDelegate` (27.0): no animation or modal UI in `dragInteraction(_:sessionWillBegin:)`; do it in `dragInteraction(_:sessionDidMove:)`. +- `UIDragInteraction.allowsPointerDragBeforeLiftDelay`: independent lift timing for pointer drags. +- Presented view controllers inherit traits through the superview chain of the presentation (27 SDK): custom `UIPresentationController` trait propagation may need a review. + +## TextKit (iOS 27.0 unless noted) + +| Need | Symbol | +|------|--------| +| Tables in attributed strings | `NSTextTable`, `NSTextBlock`, `NSTextTableBlock` ("represent table structures in attributed strings", UIKit updates June 2026; the symbol pages show `introducedAt` 6.0, so test table rendering on the iOS 27 runtime before relying on it), `NSParagraphStyle.textBlocks` | +| Override viewport layout in a `UITextView` subclass | conform to `NSTextViewportLayoutControllerDelegate` (`textViewportLayoutControllerWillLayout(_:)`, `...DidLayout(_:)`, `textViewportLayoutController(_:configureRenderingSurfaceFor:)`) | +| Custom drawing surfaces | `NSTextViewportRenderingSurface` (protocol, 27.0) | +| Keep attachment views alive | `UITextView.register(_:forTextAttachmentViewProviderType:)` with `UITextAttachmentViewProviderReusePolicy` (`onScrollingOutOfViewport`, `onEditingInlineParagraphs`): avoids flicker and keeps view state | + +Not covered here: Liquid Glass types (`UIGlassEffect`, `UIScrollEdgeEffect`, `UIBackgroundExtensionView`) live in [liquid-glass.md](../../swiftui-core/references/liquid-glass.md). diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ios/references/uikit-integration.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ios/references/uikit-integration.md index 7815c3a..45a08a9 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ios/references/uikit-integration.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ios/references/uikit-integration.md @@ -4,14 +4,14 @@ description: UIKit integration in SwiftUI with UIViewRepresentable, UIViewContro when-to-use: using UIKit views in SwiftUI, accessing UIKit-only features, wrapping third-party UIKit libraries keywords: UIViewRepresentable, UIViewControllerRepresentable, UIKit, coordinator, bridge priority: medium -related: views-modifiers.md +related: uikit-26-27.md, ../../swiftui-core/references/views-modifiers.md --- # UIKit Integration ## When to Use -- UIKit-only components (MKMapView, WKWebView) +- UIKit-only components (not maps or web content: SwiftUI has native views for both, see "Native SwiftUI first") - Third-party UIKit libraries - Complex gesture handling - Features not yet in SwiftUI @@ -74,15 +74,45 @@ Environment and coordinator access. --- -## Common UIKit Wrappers +## Native SwiftUI first -| Component | Protocol | Notes | -|-----------|----------|-------| -| MKMapView | UIViewRepresentable | Maps | -| WKWebView | UIViewRepresentable | Web content | -| UIImagePickerController | UIViewControllerRepresentable | Camera/photos | -| UIDocumentPickerViewController | UIViewControllerRepresentable | File picker | -| UIActivityViewController | UIViewControllerRepresentable | Share sheet | +Apple ships SwiftUI views for what used to need a wrapper. Verified on `developer.apple.com/tutorials/data/documentation/.json`, read 2026-11-13: + +| Need | Native SwiftUI (availability) | Wrap UIKit only when | +|------|-------------------------------|----------------------| +| Map | `Map` with `@MapContentBuilder` content, `MapCameraPosition` (`mapkit/map`, content initializers iOS 17.0; MapKit for SwiftUI) | you need `MKMapView`-only behavior with no `Map` equivalent, or must support iOS 16 or earlier | +| Web content | `WebView` + `WebPage` (`webkit/webview-swift.struct`, `webkit/webpage`, iOS 26.0, iPadOS, macOS 26.0, visionOS 26.0; `WebView(url:)` or `WebView(page)`) | you support iOS 18 or earlier, or need `WKWebView` API that `WebPage` does not expose (`webkit/wkwebview` iOS 8.0) | +| Photo picking | `PhotosPicker` (iOS 16.0) | never for photo library picking | +| File picking | `fileImporter(isPresented:allowedContentTypes:allowsMultipleSelection:onCompletion:)` (iOS 14.0) | custom document browser | +| Share sheet | `ShareLink` (iOS 16.0) | activity items or excluded types beyond `ShareLink` | +| UIKit gesture recognizers in SwiftUI | `UIGestureRecognizerRepresentable` (iOS 18.0) | | +| SwiftUI inside UIKit cells | `UIHostingConfiguration` (iOS 16.0) | | + +Still wrapped: third-party UIKit libraries and any framework view for which the symbol search on developer.apple.com finds no SwiftUI type. + +Minimal wrapper (the pattern for a UIKit view with no SwiftUI twin): + +```swift +struct LegacyGauge: UIViewRepresentable { + @Binding var value: Double + + func makeUIView(context: Context) -> UISlider { + let slider = UISlider() + slider.addTarget(context.coordinator, action: #selector(Coordinator.changed(_:)), for: .valueChanged) + return slider + } + func updateUIView(_ slider: UISlider, context: Context) { slider.value = Float(value) } + func makeCoordinator() -> Coordinator { Coordinator(self) } + + final class Coordinator: NSObject { + var parent: LegacyGauge + init(_ parent: LegacyGauge) { self.parent = parent } + @objc func changed(_ sender: UISlider) { parent.value = Double(sender.value) } + } +} +``` + +Reacting to `@Observable` models inside UIKit views, hinge and vertical bars: [uikit-26-27.md](uikit-26-27.md). --- @@ -96,5 +126,3 @@ Environment and coordinator access. - ❌ Don't store state in representable - ❌ Don't access UIKit from main SwiftUI views - ❌ Don't forget dismantleUIView when needed - -→ See `templates/uiview-representable.md` for code examples diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ipados/SKILL.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ipados/SKILL.md index aa81d95..5bb3cc5 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ipados/SKILL.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ipados/SKILL.md @@ -4,7 +4,7 @@ description: Use when building iPad apps — split views, external keyboard supp versions: ipados: 27.2 user-invocable: false -references: references/adaptive-layouts.md, references/keyboard-shortcuts.md, references/multitasking.md +references: references/adaptive-layouts.md, references/keyboard-shortcuts.md, references/multitasking.md, references/menu-bar-windows.md, references/resizing-and-mirroring.md related-skills: swift-core, swiftui-core, ios, mcp-tools --- @@ -61,6 +61,19 @@ After implementation, run **fuse-ai-pilot:sniper** for validation. | Size classes, split views | [adaptive-layouts.md](references/adaptive-layouts.md) | | External keyboard support | [keyboard-shortcuts.md](references/keyboard-shortcuts.md) | | Slide Over, Stage Manager | [multitasking.md](references/multitasking.md) | +| Menu bar (`.commands`, `UIMainMenuSystem`, shortcuts), windowed iPadOS, new-window gestures, window size | [menu-bar-windows.md](references/menu-bar-windows.md) | +| iOS 27 SDK resizing rules (orientations, `UIRequiresFullScreen`, `UIScreen`) and iPhone Mirroring | [resizing-and-mirroring.md](references/resizing-and-mirroring.md) | +| Toolbars + tab bar coexisting, `ToolbarSpacer`, search tab, scroll edge effects | [toolbars-navigation.md](../swiftui-core/references/toolbars-navigation.md) | + +--- + +## Liquid Glass on iPadOS + +API table and rules live in [liquid-glass.md](../swiftui-core/references/liquid-glass.md); do not duplicate them here. iPadOS specifics (HIG, read 2026-11-13): + +- Toolbar and tab bar can share the top of the view ([HIG toolbars](https://developer.apple.com/design/human-interface-guidelines/toolbars), 2025-12-16); the tab bar can convert to a sidebar (`TabViewStyle.sidebarAdaptable`) per [HIG tab-bars](https://developer.apple.com/design/human-interface-guidelines/tab-bars) (2026-06-08). Use `NavigationSplitView` for a sidebar that must not convert. +- Sidebars float in the glass layer; extend content beneath with `backgroundExtensionEffect()` ([HIG sidebars](https://developer.apple.com/design/human-interface-guidelines/sidebars), 2026-06-08). Each split-view pane can have its own scroll edge effect; keep heights consistent ([HIG scroll-views](https://developer.apple.com/design/human-interface-guidelines/scroll-views)). +- macOS/iPadOS add the toolbar overflow menu automatically: never build one by hand. Standard bars and sheets get glass from the system ([HIG materials](https://developer.apple.com/design/human-interface-guidelines/materials)). --- @@ -70,5 +83,6 @@ After implementation, run **fuse-ai-pilot:sniper** for validation. 2. **Keyboard shortcuts** - ⌘ shortcuts for productivity 3. **Drag and drop** - Enable data transfer 4. **Pointer support** - Mouse/trackpad cursors -5. **Multi-window** - Support multiple instances +5. **Multi-window** - Support multiple instances; adapt to any window size (full screen or windowed) and keep leading toolbar buttons clear of window controls +5b. **Menu bar** - Declare `.commands`; every command also reachable from the UI ([menu-bar-windows.md](references/menu-bar-windows.md)) 6. **External display** - UIScreen support; with the 27 SDK non-interactive external scenes are no longer offered automatically: register `UISceneAccessory.externalNonInteractive` (UIKit) or use `.sceneAccessory` (SwiftUI). UIKit apps need the scene-based life cycle (`swift-core/references/sdk-27-changes.md`) diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ipados/references/menu-bar-windows.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ipados/references/menu-bar-windows.md new file mode 100644 index 0000000..0f6ff3c --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ipados/references/menu-bar-windows.md @@ -0,0 +1,50 @@ +--- +name: menu-bar-windows +description: iPadOS menu bar (SwiftUI commands, keyboard shortcuts, UIMenuBuilder) and windowing (full screen vs windowed, multiple scenes, window size) +when-to-use: adding menus and shortcuts to an iPad app, supporting windowed iPadOS, opening content in a new window, setting a minimum window size +keywords: commands, CommandMenu, CommandGroup, keyboardShortcut, UIMenuBuilder, UIKeyCommand, windowed, openWindow, UISceneSizeRestrictions, ActivationInteraction +priority: high +related: keyboard-shortcuts.md, multitasking.md, adaptive-layouts.md +--- + +# iPadOS Menu Bar and Windowing + +Sources (read 2026-11-13): HIG the-menu-bar, windows, multitasking, menus; UIKit article `uikit/multitasking-on-ipad-mac-and-apple-vision-pro`. Symbol availability read on `developer.apple.com/tutorials/data/documentation/.json`. + +## Menu bar (HIG the-menu-bar > iPadOS) + +- Hidden until revealed (pointer to the top edge, or swipe down from it); centered; occupies the status bar space. No Apple menu, no menu bar extras; no About/Services/app-visibility items in the app menu. +- It is often hidden, so **every function must be reachable from the UI**. Dynamic menu items exist only with a hardware keyboard: always offer another route. Do not use the menu bar as a catch-all. +- Reserve `YourApp > Settings` for the app's page in iPadOS Settings; link in-app preferences with a separate item beneath it. +- Tab-style apps: add each tab as a View menu item and consider key bindings per tab. +- Rows are taller than on Mac: group related items into submenus sooner. Menu item icons: all items of a group or none ([toolbars-navigation.md](../../swiftui-core/references/toolbars-navigation.md#menu-item-icons-hig-menus-updated-2026-06-08)). + +| API | Availability | Use | +|---|---|---| +| `Scene.commands(content:)`, `Commands` | iOS/iPadOS 14.0 | Declare menu bar commands on a scene | +| `CommandMenu`, `CommandGroup(after:/before:/replacing:addition:)`, `CommandGroupPlacement` (`.newItem`, `.toolbar`, `.sidebar`, `.windowArrangement`, `.help`, ...) | iOS/iPadOS 14.0 | New menus / extend system menus | +| `View.keyboardShortcut(_:modifiers:)` (default `.command`) | iOS/iPadOS 14.0 | Shortcut shown in the menu and the hold-⌘ overlay | +| `Scene.commandsRemoved()` | iOS/iPadOS 16.0 | Drop default commands | +| `FocusedValue` / `focusedValue(_:_:)` | iOS/iPadOS 14.0 | Menu commands acting on the focused window's content | +| `UIMenuBuilder`, `UIKeyCommand` | iOS/iPadOS 13.0 / 7.0 | UIKit equivalents (see Apple's "Adding menus and shortcuts to the menu bar and user interface") | +| `UIMainMenuSystem.shared`, `setBuildConfiguration(_:buildHandler:)`, `UIMainMenuSystem.Configuration` | iOS/iPadOS 26.0 (`uikit/uimainmenusystem`, read 2026-11-13) | Configure the main menu in UIKit; `Configuration` holds per-area preferences (`documentPreference`, `findingPreference`, `inspectorPreference`, `newScenePreference`, `printingPreference`, `sidebarPreference`, `textFormattingPreference`, `toolbarPreference`, `findingConfiguration`), then customize with the `UIMenuBuilder` handler | +| `UIMenuElement.preferredImageVisibility` | iOS/iPadOS 27.0 | Menu bar and context menus hide menu element images by default on iPadOS 27 and macOS 27; `UIMenuElement.ImageVisibility` is `automatic`, `hidden` or `visible`; use `.visible` only where the HIG wants an icon (iOS 27 release notes) | + +```swift +WindowGroup { ContentView() } + .commands { + CommandGroup(after: .newItem) { + Button("New Note", systemImage: "square.and.pencil") { } // icon: all items or none + .keyboardShortcut("n", modifiers: [.command, .shift]) + } + } +``` + +## Windowing (HIG windows > iPadOS, multitasking > iPadOS) + +- Two presentations, chosen by the person in Multitasking & Gestures settings: **full screen** (windows fill the screen, app switcher between windows) and **windowed** (freely resizable, several on screen, system remembers size and placement). Apps get no indication of the chosen configuration: adapt to any window size ([adaptive-layouts.md](adaptive-layouts.md)). Slide Over / Split View / Stage Manager rows in `multitasking.md` are legacy terms; the HIG now describes full screen and windowed. +- Windowed windows show window controls at the leading edge of the toolbar: move your own leading toolbar buttons inward so they are not hidden. +- Let people open content in a new window by gesture (Notes pinch): `collectionView(_:sceneActivationConfigurationForItemAt:point:)` (iOS/iPadOS 15.0) for collection items, `UIWindowScene.ActivationInteraction` (15.0) for other views. Single-file viewing without your own window: `QLPreviewSceneActivationConfiguration` (15.0) - multiple-window support is still required. +- Multiple scenes: Info.plist `UIApplicationSupportsMultipleScenes`; SwiftUI `openWindow` (`OpenWindowAction`, iOS/iPadOS 16.0) and `supportsMultipleWindows` environment value (16.0). +- Minimum window size: `UISceneSizeRestrictions`; observe geometry with `windowScene(_:didUpdateEffectiveGeometry:)` (iOS/iPadOS 26.0) and defer heavy updates while the scene is interactively resizing. SwiftUI: `defaultSize(width:height:)`, `windowResizability(_:)` (iOS/iPadOS 17.0). +- Multitasking duties (HIG multitasking): save/restore context at any time, pause attention-demanding activity on switch-away, handle audio interruptions, finish user-started tasks in the background, notifications sparingly. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ipados/references/multitasking.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ipados/references/multitasking.md index 81d2c8a..4347646 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ipados/references/multitasking.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ipados/references/multitasking.md @@ -10,6 +10,8 @@ related: keyboard-shortcuts.md # iPadOS Multitasking +> Current HIG model (multitasking, windows; read 2026-11-13): people choose **full screen** or **windowed** apps; apps are not told which. The mode table below uses legacy terms. Menu bar, window controls and scene APIs: [menu-bar-windows.md](menu-bar-windows.md). + ## When to Use - Supporting Split View diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ipados/references/resizing-and-mirroring.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ipados/references/resizing-and-mirroring.md new file mode 100644 index 0000000..12212e3 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/ipados/references/resizing-and-mirroring.md @@ -0,0 +1,47 @@ +--- +name: resizing-and-mirroring +description: iPad window resizing and iPhone Mirroring rules for apps built with the iOS 27 SDK - orientation handling, UIRequiresFullScreen, UIScreen bounds, resize delivery +when-to-use: an app misbehaves when an iPad window is resized, an iPhone-only app runs on iPad, testing iPhone Mirroring on a Mac, deciding whether to keep UIRequiresFullScreen +keywords: UIRequiresFullScreen, UISupportedInterfaceOrientations, UIScreen.main, continuous resize, iPhone Mirroring, supportedInterfaceOrientations, windowed +priority: high +related: multitasking.md, adaptive-layouts.md, menu-bar-windows.md +--- + +# iPad Resizing and iPhone Mirroring (iOS 27 SDK) + +Source: iPadOS and iOS 27 release notes, UIKit "Resolved Issues" (https://developer.apple.com/documentation/ios-ipados-release-notes/ios-ipados-27-release-notes, JSON `.../tutorials/data/documentation/ios-ipados-release-notes/ios-ipados-27-release-notes.json`, read 2026-11-13). Each rule applies to apps **built with the iOS 27 SDK**; radar numbers are Apple's. + +## Resizing on iPad + +| Situation | Rule from Apple's notes | Radar | +|-----------|-------------------------|-------| +| iPad app whose `UISupportedInterfaceOrientations` lacks some of the four orientations | No longer treated as non-continuously resizable: "supported interface orientations should no longer be a condition for continuous resizability" | 166422120 | +| iPhone-only app on iPad | After the first resize the scene ignores supported interface orientations | 178561952 | +| iPhone-only app limited to portrait or landscape | Layout no longer breaks when the iPad sits in an unsupported orientation | 178573319 | +| App sets `UIRequiresFullScreen` | Each resize is delivered as a discrete change to a **new `UIScreen`** with updated bounds, not as continuous resize updates; `UIScreen.main.bounds` stays fixed once the screen connects | 178560235, 178562971, 178559386 | + +## WWDC26 session 278 "Modernize your UIKit app" (https://developer.apple.com/videos/play/wwdc2026/278/, transcript and code read 2026-11-13) + +- iPhone Mirroring windows are fully resizable; an iPhone-only app on iPad is fully resizable but still runs under the **phone idiom**. Apps must adapt to any scene size at runtime. +- Scene life cycle is required with the latest SDKs (no launch otherwise). +- Do not reference the main screen: use `window?.windowScene?.screen`, or pass a screen in. Replace screen scale with `traitCollection.displayScale` (tracked automatically inside `layoutSubviews`, `updateProperties`, `draw`; elsewhere `registerForTraitChanges`). +- Do not use screen bounds: read `windowScene.effectiveGeometry.coordinateSpace.bounds`, observe `windowScene(_:didUpdateEffectiveGeometry:)`, and inside views use the view's own size. +- `UIRequiresFullScreen` is honored on iPhone in resizable environments from iOS 27 and no longer opts out of resizing: it enables **discrete resizing**, each size change moves the scene to a new screen configuration and honors the supported orientations (meant for games). +- The user-interface idiom is no longer meaningful for layout: use size classes. Supported interface orientation is only a preference and is ignored in resizable environments; in iPhone Mirroring the app always reports portrait whatever the scene's aspect ratio. +- `UIView` conforms to the new Core Location and Core Motion body protocols: `motionManager.deviceMotionBody = view`, `locationManager.headingBody = view` (iOS 27.0). +- Testing: Device Hub and Xcode Previews have a resize mode; still test iPhone Mirroring and iPad on real devices. Xcode 27 ships an app-modernization agent skill (`xcrun agent skills export` exports Xcode's skills as markdown). + +Consequences for code: + +- Never derive layout from `UIScreen.main.bounds` or device orientation; read the window or scene geometry (size classes, `windowScene(_:didUpdateEffectiveGeometry:)` iOS 26.0, see [menu-bar-windows.md](menu-bar-windows.md)). Under `UIRequiresFullScreen`, Apple's notes say a resize arrives as a change to a new `UIScreen`, not as a continuous resize; verify your resize handling on that path on a device. +- Do not use `UISupportedInterfaceOrientations` to keep an iPad app from resizing; design the layout for any size ([adaptive-layouts.md](adaptive-layouts.md)). + +## iPhone Mirroring (Mac showing an iPhone app) + +| Situation | Rule from Apple's notes | Radar | +|-----------|-------------------------|-------| +| Supported orientations | Fixed behavior: the declared orientations are honored until the user starts resizing the window, after which the scene supports all orientations regardless of `UISupportedInterfaceOrientations` / `supportedInterfaceOrientations` | 178555304 | +| `UIRequiresFullScreen` | Same discrete-`UIScreen` resize delivery as on iPad | 178558224 | +| Initial screen | The scene starts on `UIScreen.main` (before, it connected to another screen) | 178558897 | + +Other fixes the same notes list under "iPhone Mirroring": resizing may fail after pressing Home in the mirrored app (180961142), restarting an app while mirroring could freeze the screen and disable resizing (181023494), iPhone Mini did not resize properly (181057810). Test the mirrored window at several sizes; do not assume a fixed iPhone size. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/SKILL.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/SKILL.md index 91b3ee4..460179c 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/SKILL.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/SKILL.md @@ -5,8 +5,8 @@ versions: macos: 27.2 xcode: 27.2 user-invocable: false -references: references/app-structure.md, references/build-tools.md, references/appkit-integration.md, references/notarization.md -related-skills: swift-core, swiftui-core, mcp-tools, build-distribution +references: references/app-structure.md, references/build-tools.md, references/appkit-integration.md, references/appkit-27.md, references/notarization.md, references/touch-input.md +related-skills: swift-core, swiftui-core, mcp-tools, build-distribution, apple-frameworks --- @@ -72,8 +72,22 @@ After implementation, run **fuse-ai-pilot:sniper** for validation. |------|-----------| | MenuBarExtra, Settings, Windows | [app-structure.md](references/app-structure.md) | | XcodeBuildMCP macOS tools | [build-tools.md](references/build-tools.md) | -| NSViewRepresentable, menus | [appkit-integration.md](references/appkit-integration.md) | +| NSViewRepresentable, menus (native `Map` / `WebView` first) | [appkit-integration.md](references/appkit-integration.md) | +| AppKit 26-27: Observable tracking, `NSRefreshController`, `NSControl.Events`, tab-role segmented control, `NSTextSelectionManager`, menu images | [appkit-27.md](references/appkit-27.md) | +| App Attest, notifications, CloudKit, MapKit and other app frameworks on Mac | [apple-frameworks](../apple-frameworks/SKILL.md) | | Code signing, notarization | [notarization.md](references/notarization.md) | +| Touch on Mac (touch display, Sidecar), gesture recognizers, hidden controls | [touch-input.md](references/touch-input.md) | +| Toolbars (`ToolbarSpacer`, shared glass background), scroll edge effects, menu item icons | [toolbars-navigation.md](../swiftui-core/references/toolbars-navigation.md) | + +--- + +## Liquid Glass on macOS + +API table and rules live in [liquid-glass.md](../swiftui-core/references/liquid-glass.md); do not duplicate them here. macOS specifics (HIG, read 2026-11-13): + +- Toolbars, sidebars and tab-style controls float in the glass layer; standard components adopt it automatically ([HIG toolbars](https://developer.apple.com/design/human-interface-guidelines/toolbars), updated 2025-12-16). Toolbar items have no bezel on macOS; people can customize or hide the toolbar, so it is never the only home of a command. +- Sidebars ([HIG sidebars](https://developer.apple.com/design/human-interface-guidelines/sidebars), 2026-06-08): let content extend beneath (`backgroundExtensionEffect()`); sidebar icons follow the system accent color; offer Show/Hide Sidebar in the View menu. +- Materials ([HIG materials](https://developer.apple.com/design/human-interface-guidelines/materials)): macOS keeps `NSVisualEffectView` materials with vibrancy and two blend modes (behind window, within window) for the content layer; glass is for controls and navigation only. --- @@ -85,3 +99,4 @@ After implementation, run **fuse-ai-pilot:sniper** for validation. 4. **Settings window** - Use Settings scene 5. **Notarization** - Required for distribution 6. **Sandbox** - Enable for App Store +7. **Touch is secondary** - Macs with a touch display and Sidecar iPads send touch: use standard controls and gesture recognizers, enlarge tap targets not controls, give hover-only controls a touch path ([touch-input.md](references/touch-input.md); HIG 2026-10-28) diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/references/appkit-27.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/references/appkit-27.md new file mode 100644 index 0000000..4d4550c --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/references/appkit-27.md @@ -0,0 +1,83 @@ +--- +name: appkit-27 +description: AppKit 26 and 27 additions verified on Apple docs - automatic Observable tracking, NSRefreshController, NSControl.Events, tab-role segmented controls, NSTextSelectionManager, menu image visibility, titlebar accessories +when-to-use: writing or migrating AppKit code for macOS 26/27, binding views to @Observable models, adding pull-to-refresh, building tab-style segmented controls or custom text views +keywords: NSRefreshController, NSControl.Events, addTarget, NSSegmentedControl.Role, tabs, NSToolbarItemGroup.Role, NSTextSelectionManager, observation tracking, viewWillLayout, preferredImageVisibility, NSTitlebarAccessoryViewController +priority: high +related: appkit-integration.md, touch-input.md, app-structure.md +--- + +# AppKit 26 and 27 + +Sources, all read 2026-11-13: AppKit updates page https://developer.apple.com/documentation/updates/appkit (JSON `.../tutorials/data/documentation/updates/AppKit.json`), macOS 27 release notes https://developer.apple.com/documentation/macos-release-notes/macos-27-release-notes, symbol pages `developer.apple.com/tutorials/data/documentation/appkit/.json` (`introducedAt` quoted). Touch, Sidecar and gesture recognizers: [touch-input.md](touch-input.md). + +## Automatic Observable tracking + +Source: https://developer.apple.com/documentation/appkit/updating-views-automatically-with-observation-tracking-in-appkit. + +- AppKit tracks `@Observable` reads inside `viewWillLayout()` (view controller), `layout()`, `updateConstraints()` and `draw(_:)` (view), and re-runs the method when a read property changes. No manual `needsLayout` / `needsDisplay` bookkeeping. +- Drawing overrides called from `draw(_:)` are covered, including cell overrides such as `drawKnob(_:)` and `drawBar(inside:flipped:)`. +- Same idea as UIKit's `updateProperties()` ([uikit-26-27.md](../../ios/references/uikit-26-27.md)); AppKit's article names `viewWillLayout()` as the place for property updates. + +```swift +@Observable final class MessageModel { var showStatus = false; var statusText = "" } + +final class InboxViewController: NSViewController { + let model = MessageModel() + private let statusLabel = NSTextField(labelWithString: "") + + override func viewWillLayout() { + super.viewWillLayout() + statusLabel.alphaValue = model.showStatus ? 1 : 0 // tracked read + statusLabel.stringValue = model.statusText + } +} +``` + +## New controls and events (macOS 27.0) + +| Need | Symbol | Notes | +|------|--------|-------| +| Pull to refresh | `NSRefreshController` assigned to `NSScrollView.refreshController` | Members: `action`, `target`, `attributedTitle`, `tintColor`, `isRefreshing`, `beginRefreshing()`, `endRefreshing()`. Call `endRefreshing()` when the work completes (macOS 27 notes) | +| Control events like `UIControl` | `NSControl.Events` + `addTarget(_:action:for:)` / `removeTarget(_:action:for:)` | Events: tracking (`trackingBegan`, `trackingEndedInside`, ...), semantic (`valueChanged`, `primaryActionTriggered`, `menuActionTriggered`), aggregate (`allEvents`). The type and `addTarget` pages show macOS 11.0 while event members such as `valueChanged` show 27.0 and the June 2026 updates list them as new: gate on your deployment target | +| Tab-style segmented control | `NSSegmentedControl.role = .tabs` (`NSSegmentedControl.Role`: `automatic`, `tabs`, `valueSelection`) | VoiceOver reads it as "tabs" with a distinct look; keep `valueSelection` for value pickers like text alignment (macOS 27 notes) | +| Toolbar group semantic role | `NSToolbarItemGroup.role` (`NSToolbarItemGroup.Role`) | Also iOS 13.0 / Mac Catalyst 27.0 per the symbol page | +| Custom text selection | `NSTextSelectionManager` | Click, drag, shift-click and word/line/paragraph selection through gesture recognizers instead of overriding `mouseDown:`; `NSTextView` now uses it; subclasses that override `mouseDown:` keep working through a fallback | +| Drag from a gesture | `NSView.beginDraggingSession(items:gesture:source:)` | Returns `NSDraggingSession?` | +| Menu item images | `NSMenuItem.preferredImageVisibility` (`automatic`, `hidden`, `visible`) | macOS 27: menu bar and context menus hide symbol images by default for apps linked on macOS 26 or later; system items (Settings, Share, Print) keep theirs; a menu item with no title and only an image is hidden in the 27 SDK unless you set `.visible` | +| Titlebar accessories | `NSTitlebarAccessoryViewController` | Linked on macOS 27: may draw outside its bounds (shadows, interactive glass); reveal animations may clip it | + +```swift +final class ListViewController: NSViewController { + private let refresh = NSRefreshController() + @IBOutlet var scrollView: NSScrollView! + + override func viewDidLoad() { + super.viewDidLoad() + refresh.target = self + refresh.action = #selector(reload(_:)) + scrollView.refreshController = refresh + } + + @objc func reload(_ sender: Any?) { + Task { + try? await Task.sleep(for: .seconds(1)) // replace with your async data load + refresh.endRefreshing() + } + } +} +``` + +`action` is typed `Selector?` and `target` `AnyObject?` (symbol pages); Apple documents no parameter form for the action method, so the sample takes `Any?` and ends refreshing through its own reference. + +## macOS 26 additions still current + +| Need | Symbol | +|------|--------| +| Old control metrics | `NSView.prefersCompactControlSizeMetrics` (metrics consistent with macOS 15 and earlier) | +| Largest control size | `NSControl.ControlSize.extraLarge` (cases: `mini`, `small`, `regular`, `large`, `extraLarge`) | +| Split view accessories | `NSSplitViewItemAccessoryViewController` (macOS 26.0) in `NSSplitViewItem.topAlignedAccessoryViewControllers` / `bottomAlignedAccessoryViewControllers` | +| Prominent toolbar item | `NSToolbarItem.Style.prominent` (26.0) with `backgroundTintColor` (26.0) | +| Extend content under sidebars | `NSBackgroundExtensionView` (26.0) | + +Liquid Glass types (`NSGlassEffectView`, `NSGlassEffectContainerView`, `.glass` bezel) are in [liquid-glass.md](../../swiftui-core/references/liquid-glass.md). diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/references/appkit-integration.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/references/appkit-integration.md index fe77695..0c8f361 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/references/appkit-integration.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/references/appkit-integration.md @@ -4,11 +4,13 @@ description: AppKit integration in SwiftUI with NSViewRepresentable, menus, tool when-to-use: using AppKit views in SwiftUI, accessing macOS-specific features, custom menus keywords: NSViewRepresentable, NSViewControllerRepresentable, AppKit, NSMenu, NSToolbar priority: medium -related: app-structure.md +related: appkit-27.md, touch-input.md, app-structure.md --- # AppKit Integration +Check SwiftUI first (read on `developer.apple.com/tutorials/data/documentation/.json`, 2026-11-13): maps are `Map` (content initializers macOS 14.0, `mapkit/map`) and web content is `WebView` + `WebPage` (macOS 26.0, `webkit/webview`, `webkit/webpage`); wrapping `MKMapView` or `WKWebView` in `NSViewRepresentable` is for older deployment targets or API those types do not cover. New AppKit APIs for macOS 26 and 27 (Observable tracking, `NSRefreshController`, `NSControl.Events`, tab-role segmented controls, `NSTextSelectionManager`): [appkit-27.md](appkit-27.md). + ## When to Use - AppKit-only components diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/references/notarization.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/references/notarization.md index 591be75..d01c3fa 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/references/notarization.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/references/notarization.md @@ -37,6 +37,15 @@ Apple scans and approves app for Gatekeeper. 4. Receive notarization ticket 5. Staple ticket to app +**Preconditions the notary service enforces** (https://developer.apple.com/documentation/security/notarizing-macos-software-before-distribution, read 2026-11-13): +- Developer ID application, kernel/system extension or installer certificate (not Mac Distribution, ad hoc or development) +- Hardened Runtime enabled for app and command-line targets +- Secure timestamp in the signature (Xcode's distribution workflow adds it; custom workflows must pass it) +- No `com.apple.security.get-task-allow` entitlement set to true +- Linked against the macOS 10.9 SDK or later; well-formed XML, ASCII entitlements + +Notarization is not App Review, and Mac App Store software does not need it. `altool` and Xcode 13 or earlier have been rejected by the notary service since 2023-11-01; use `notarytool` (Xcode 13+) or the Notary API. + ### Stapling Attach notarization ticket to app bundle. @@ -69,6 +78,34 @@ xcrun notarytool submit ./MyApp.dmg \ xcrun stapler staple ./MyApp.dmg ``` +### What you can submit + +| Deliverable | How | +|-------------|-----| +| `.app` | The service does not take a bare bundle: `ditto -c -k --keepParent MyApp.app MyApp.zip`, submit the ZIP | +| Disk image | UDIF `.dmg`, submit directly | +| Flat installer package | A **signed** flat `.pkg` (Developer ID Installer certificate), submit directly, then `xcrun stapler staple ./MyApp.pkg` | + +The service processes nested containers (pkg inside dmg) and issues a ticket per nested item. A custom third-party installer needs two rounds: notarize and staple the payload, build it into the installer, then notarize the installer. Source: https://developer.apple.com/documentation/security/customizing-the-notarization-workflow (read 2026-11-13). + +--- + +## Developer ID certificate expiry (2027-02-01) + +Certificates issued by the original Developer ID Sub-CA stop working on **2027-02-01**; renew from **Developer ID Certification Authority (G2)** (choose "G2 Sub-CA" as intermediary; G2 certificates last one year). +- `.pkg` files signed with an affected certificate **no longer install** from that date: re-sign every package. +- Apps already signed and notarized with a secure timestamp keep working; sign updates with the new certificate and a secure timestamp. + +Procedure: `build-distribution` skill `references/code-signing.md`. Source: https://developer.apple.com/news/?id=w4atic4c (2026-10-01, read 2026-11-13). + +--- + +## Mac App Store and TestFlight builds + +- Do not ship `com.apple.quarantine` in macOS apps for TestFlight or the App Store; since 2025-02-18 the attribute must be removed from every file in the app to upload (https://developer.apple.com/news/upcoming-requirements/, read 2026-11-13). Targeted removal (`xattr(1)`: `-d` deletes one attribute, `-r` recurses): `xattr -dr com.apple.quarantine MyApp.app`; verify with `xattr -lr MyApp.app | grep quarantine`. +- Intel: Apple's posts differ in wording. News k1mtkt1k (2026-09-09): "macOS 26 is the final release supporting Intel Mac computers and Rosetta — macOS 27 will be Apple silicon only". News w5ngl9k2 (2026-09-01): "macOS 27: Final release to support Rosetta — Intel-only apps will no longer run on Mac computers with Apple silicon after this update". Either way, ship an arm64 slice. A universal app with minimum macOS 13+ may drop `x86_64` and upload to the Mac App Store (App Store Connect release notes, 2026-06-18). To limit an app to Apple silicon set the build architecture to `arm64` only. +- Rosetta remains for older Intel-framework gaming titles only (news w5ngl9k2). + --- ## DMG Creation @@ -109,6 +146,8 @@ stapler validate MyApp.dmg - ✅ Notarize before distribution - ✅ Staple for offline verification - ✅ Test on clean Mac +- ✅ Replace Developer ID certificates issued from the old Sub-CA before 2027-02-01 +- ✅ Ship arm64 (universal while you still support Intel on macOS 26 and earlier) - ❌ Don't skip notarization - ❌ Don't distribute unsigned apps - ❌ Don't ignore Gatekeeper warnings diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/references/touch-input.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/references/touch-input.md new file mode 100644 index 0000000..096a485 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/macos/references/touch-input.md @@ -0,0 +1,60 @@ +--- +name: touch-input +description: Touch on Mac (Mac with a touch display, Sidecar iPad) - HIG guidance and the AppKit gesture recognizer APIs to support it +when-to-use: supporting touch on macOS 27, migrating mouse tracking loops, sizing tap targets, revealing hover-only controls +keywords: touch display, Sidecar, NSGestureRecognizer, NSClickGestureRecognizer, touchCapabilities, allowedTouchTypes, hidden controls, hover +priority: high +related: app-structure.md, appkit-integration.md +--- + +# Touch on Mac + +Sources (read 2026-11-13): HIG designing-for-macos (alert 2026-10-28), gestures (2026-10-28), pointing-devices (2026-10-28) at `developer.apple.com/design/human-interface-guidelines/`; AppKit articles `appkit/adopting-gesture-recognizers-in-your-app` and `appkit/handling-appkit-gestures` on `developer.apple.com/documentation/`. + +## HIG rules + +- Touch is **secondary** to keyboard and pointing device. People use it for "brief, intentional interactions" (reach forward to a stationary Mac). Keep the interface stable and predictable whatever the input. +- Keep control size and density as is (optimized for keyboard and pointer). Enlarge the **tap target** beyond the visual bounds instead; standard framework controls already do. For small or dense controls, show a temporary touch-sized variant while touched and keep it briefly after release (system steppers, sliders, dials do this). +- Every function stays reachable by keyboard and pointer; add touch equivalents for pointer-only actions (modifier-drag, hover menus). +- Preserve existing iPhone/iPad/trackpad gestures; test for conflicts with macOS system gestures. Support direct and indirect touch; use modifier keys where a gesture must work for all touch inputs. + +| Action | Trackpad | Touch display | +|---|---|---| +| Select | Primary click | Tap | +| Open | Double click | Double tap | +| Scroll | Two fingers | One finger | +| Zoom / Rotate | Pinch / two-finger rotate | Pinch / two-finger rotate | +| Context menu | Secondary click | Touch and hold | +| Drag | Click and drag | Touch and hold, then drag | + +### Hidden controls (pointing-devices > Touch support for hidden controls) + +- Controls shown only on hover need a touch path; reserve it for **essential** controls (not tooltips, not what scroll/swipe already offers). Do not keep them permanently visible. +- Reveal only controls for the touched content; hide again when done or after a few seconds. Sidebars and the tab close button are exceptions: keep visible until touch leaves the sidebar or the pointer is used again; after closing the selected tab by touch, show the close button on the new selected tab. +- A tap on a hidden control's area reveals it without activating; it acts on the next tap. Keep the current selection through both taps. +- Offer a short context menu (touch and hold) as the dependable route. + +## AppKit APIs (read on developer.apple.com JSON, 2026-11-13) + +| API | Availability | Use | +|---|---|---| +| `NSClickGestureRecognizer`, `NSPressGestureRecognizer`, `NSPanGestureRecognizer`, `NSMagnificationGestureRecognizer`, `NSRotationGestureRecognizer` | macOS 10.10 | Standard recognizers: one model for mouse, trackpad, touch. Prefer them over custom ones | +| `NSGestureRecognizer.allowedTouchTypes` (`NSTouch.TouchTypeMask`, e.g. `.direct`) | macOS 10.12.2 | Restrict a recognizer to direct touch; for a touch-only pan also set `buttonMask = 0` | +| `NSScreen.touchCapabilities` (`NSScreen.TouchCapabilities`, `.multiTouch`) | macOS 27.0 | Detect a touch screen only to offer a touch-specific option (e.g. signature capture); otherwise write input-agnostic code | +| `NSEvent.isTouchSwipeNavigationEnabled` | macOS 27.0 | Check before page-navigation swipes (user can disable in System Settings); AppKit does not translate swipes for you | +| `NSView.exclusiveGestureBehavior` (`.inherit` default, `.exclusive`, `.notExclusive`) | macOS 27.0 | Only one view's recognizers are active at a time by default; Info.plist `NSViewGestureRecognizerIsExclusive` (YES when the key is absent; Xcode writes NO into new macOS app projects, so new apps are not exclusive unless changed) sets it app-wide | +| `NSWindow.disablesDirectTouchSystemGestures` | **macOS 27.3 (beta in Apple's docs on 2026-11-13; above the 27.2 target)** | Let a window claim 3+ simultaneous touches before system Multi-Touch gestures; use sparingly | +| Info.plist `NSIsTouchNative` (macOS 27.0) | | Only for apps embedding a non-AppKit input stack with its own touch pipeline; skips AppKit's mouse-emulation recognizers | +| `NSGestureRecognizerDelegate` `gestureRecognizer(_:shouldReceive:)` (touch) / `gestureRecognizer(_:shouldAttemptToRecognizeWith:)` (pointer) | | Filter by location, e.g. a resize grip inside a large view | + +### Migration checklist + +1. Standard AppKit controls and recognizers work with touch unchanged; test every window, sheet and popover (tap, one-finger drag/scroll/text selection, pinch/rotate, small grips). +2. `mouseDown/Dragged/Up` overrides and tracking loops still run (AppKit emulates a single-finger tap/drag) but miss multi-finger gestures: replace them with recognizers or target-action. +3. Custom `NSGestureRecognizer` subclasses must reach a terminal state (ended, failed, cancelled) and handle `touchesCancelled`/`mouseCancelled`; otherwise the app looks frozen. +4. `NSApplication.currentEvent` no longer reliably holds the initiating event in control actions: use `NSEvent.modifierFlags` and `NSEvent.pressedMouseButtons` (a touch is not a pressed button). +5. Hover (`NSTrackingArea`, SwiftUI `onHover`) is pointer-only; give touch another route (above). Keyboard and scroll-wheel events behave the same on every input source. +6. Context menus: override `NSView.menu(for:)` instead of `rightMouseDown`; in SwiftUI use `contextMenu(menuItems:)` (touch and hold opens it). +7. No Mac with a touch display? Connect an iPad via Sidecar: AppKit routes its touches the same way. + +SwiftUI: no touch-specific API appears in these HIG pages; the AppKit article states gesture recognizers are a shared input model across AppKit, SwiftUI and Mac Catalyst. Enlarge hit areas with `contentShape(_:eoFill:)` (macOS 10.15) when a custom control is small. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/mcp-tools/SKILL.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/mcp-tools/SKILL.md index 5dd7f7b..3714d25 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/mcp-tools/SKILL.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/mcp-tools/SKILL.md @@ -1,8 +1,8 @@ --- name: mcp-tools -description: Use when needing Xcode build automation or Apple API/WWDC documentation lookup via XcodeBuildMCP or apple-docs MCP servers. +description: Use when needing Xcode build automation, Apple API/WWDC documentation lookup, or Xcode 27's own agent features and MCP server (xcrun mcpbridge, plan mode, plug-ins, RenderPreview) via XcodeBuildMCP, apple-docs MCP or Xcode. user-invocable: false -references: references/xcodebuild-mcp.md, references/xcodebuild-mcp-ui-verification.md, references/apple-docs-mcp.md, references/apple-docs-mcp-workflows.md +references: references/xcodebuild-mcp.md, references/xcodebuild-mcp-ui-verification.md, references/apple-docs-mcp.md, references/apple-docs-mcp-workflows.md, references/xcode-agents.md related-skills: swift-core, ios, macos --- @@ -11,6 +11,8 @@ Documents the two MCP servers that power the Swift/Apple workflow: XcodeBuildMCP Defines the mandatory research-first priority order (Apple Docs MCP first, then Context7 for third-party libraries, then Exa web search) and the mandatory build-validation loop after every code change (build, read errors, fix, rebuild, only commit on zero errors). +Also covers Xcode 27's own coding intelligence and MCP server for external agents (`xcrun mcpbridge`, preview `xcrun mcp-server`, plan mode, plug-ins with skills/MCP servers/ACP agents, `lldb-mcp`, RenderPreview). + Includes installation snippets for both servers and a quick-reference table mapping tasks to the right tool. @@ -86,6 +88,24 @@ Includes installation snippets for both servers and a quick-reference table mapp --- +### 3. Xcode's own MCP server (Xcode 27) +**Purpose**: give an external agent (Cursor, or any MCP client) access to a project open in Xcode, and configure the agents that run inside Xcode + +**Documentation**: [xcode-agents.md](references/xcode-agents.md) + +**Setup** (Apple's page documents the command for Claude Code, https://developer.apple.com/documentation/xcode/giving-external-agents-access-to-xcode, read 2026-11-13): allow external agents in Xcode > Settings > Intelligence, then register a stdio MCP server named `xcode` in Cursor's MCP settings, same server command as Apple's: +```json +{ "mcpServers": { "xcode": { "type": "stdio", "command": "xcrun", "args": ["mcpbridge"] } } } +``` +Open the project in Xcode before prompting. `sudo xcrun mcp-server enable` is a beta-5 preview of a workspace-less server (details and caveats in the reference). + +**Use when**: +- Rendering SwiftUI previews to images (RenderPreview), editing String Catalogs, using the Xcode debugger or `lldb-mcp` +- Reviewing a plan first (plan mode, `/plan`) or installing Xcode agent plug-ins (skills, MCP servers, ACP agents) +- XcodeBuildMCP stays the default for build, test and UI evidence in this workflow + +--- + ## Workflow Integration ### Research-First (MANDATORY) @@ -150,6 +170,7 @@ After EVERY code change: ✅ WWDC sessions offline (2014-2025 bundled) ✅ Deprecation and availability info ⚠️ No HIG pages and no post-2025 WWDC: use developer.apple.com via `browser_fetch` +⚠️ Search is unreliable (0 results for the real `ToolbarSpacer`): never conclude an API is absent from it. Verify on the complete reference: `https://developer.apple.com/tutorials/data/documentation//.json` (lowercase, e.g. `swiftui/toolbarspacer.json`) and HIG `https://developer.apple.com/tutorials/data/design/human-interface-guidelines/.json`; dated HIG changes: https://developer.apple.com/design/whats-new/ --- @@ -158,7 +179,7 @@ After EVERY code change: **XcodeBuildMCP**: - [Website](https://www.xcodebuildmcp.com) (repository moved to getsentry) - [npm](https://www.npmjs.com/package/xcodebuildmcp) -- Version: 2.7.0 (npm) +- Version: 2.7.0 (npm `xcodebuildmcp`; project now also published as `mobilebuildmcp` 2.7.1 - see [xcodebuild-mcp.md](references/xcodebuild-mcp.md)). Tool minimum Xcode 16.x; this plugin targets Xcode 27.2 **Apple Docs MCP**: - [GitHub](https://github.com/kimsungwhee/apple-docs-mcp) @@ -179,3 +200,6 @@ After EVERY code change: | Clean build | `XcodeBuildMCP` | `xcodebuild-mcp.md` | | Create project | `XcodeBuildMCP` | `xcodebuild-mcp.md` | | Verify UI (HIG gate) | `XcodeBuildMCP` | `xcodebuild-mcp-ui-verification.md` | +| Connect an external agent to Xcode | `xcrun mcpbridge` | `xcode-agents.md` | +| Render a SwiftUI preview | Xcode MCP `RenderPreview` | `xcode-agents.md` | +| Plan mode, Xcode plug-ins, ACP | Xcode coding intelligence | `xcode-agents.md` | diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/mcp-tools/references/xcode-agents.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/mcp-tools/references/xcode-agents.md new file mode 100644 index 0000000..60f44dd --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/mcp-tools/references/xcode-agents.md @@ -0,0 +1,79 @@ +--- +name: xcode-agents +description: Xcode 27 coding intelligence and Xcode's own MCP server - plan mode, plug-ins (skills, MCP servers, ACP), xcrun mcpbridge, xcrun mcp-server, lldb-mcp, RenderPreview +when-to-use: connecting Cursor or another external agent to Xcode, configuring agents inside Xcode, deciding between Xcode's MCP tools and XcodeBuildMCP, rendering SwiftUI previews from an agent +keywords: Xcode 27, coding intelligence, plan mode, ACP, Agent Client Protocol, mcpbridge, mcp-server, lldb-mcp, RenderPreview, plug-ins, skills, Copilot, Gemini +priority: high +related: xcodebuild-mcp.md, xcodebuild-mcp-ui-verification.md, ../../swift-core/references/sdk-27-changes.md +--- + +# Xcode 27 Agents and Xcode's MCP Server + +Xcode 27 has its own coding intelligence (agents inside Xcode) and its own MCP server (for agents running outside Xcode). Both are independent of XcodeBuildMCP, which stays the default build/test/UI-evidence tool in this plugin. + +Sources (read 2026-11-13): +- Xcode 27, 27.2, 27.3 release notes: https://developer.apple.com/documentation/xcode-release-notes/xcode-27-release-notes (and `-27_2-`, `-27_3-`) +- https://developer.apple.com/documentation/xcode/giving-external-agents-access-to-xcode +- https://developer.apple.com/documentation/xcode/extending-and-customizing-agents +- https://developer.apple.com/documentation/xcode/setting-up-coding-intelligence + +## Connect an external agent (Cursor) to Xcode + +1. Xcode > Settings > Intelligence > Model Context Protocol > "Allow External Agents to Use Xcode Tools": **Always** or **While Xcode is Open** (**Never** turns it off). +2. Register the bridge in Cursor's `mcp.json` (same server command as Apple's): + +```json +{ "mcpServers": { "xcode": { "type": "stdio", "command": "xcrun", "args": ["mcpbridge"] } } } +``` + +Other agents, as Apple documents: `claude mcp add --transport stdio xcode -- xcrun mcpbridge` (verify with `claude mcp list`) and `codex mcp add xcode -- xcrun mcpbridge`. +3. Open the project in Xcode **before** prompting the agent; Xcode alerts when an external agent connects and is active. +4. Optional: put hints about Xcode and the project in `AGENTS.md` or a `.cursor/rules` rule. + +## Workspace-less MCP server (preview) + +Xcode 27 beta 5 added a preview MCP server experience that runs **without an open Xcode workspace** and lets you grant code-signed agents access to a directory tree for extended periods: + +```bash +sudo xcrun mcp-server enable +xcrun mcp-server status +sudo xcrun mcp-server enable --unsafe-always-allow-all-agents # unattended environments only +``` + +`--unsafe-always-allow-all-agents` approves all permissions upfront; Apple says it is not recommended for at-desk use. Early preview: some `xcrun mcp-server` behavior may not work in every configuration, and settings or permissions may need an Xcode relaunch or a reboot (release note 181836944). Treat as beta; keep `xcrun mcpbridge` as the documented path. + +## What Xcode's MCP tools cover (Xcode 27 release notes) + +| Area | Tools | +|------|-------| +| Build and test | Build and test tools; activity status is sent dynamically to external clients (181078347) | +| Debugging | Manipulate the active run state, read and use the debugger console | +| Project | List and switch schemes and run destinations; inspect and modify build settings, compiler flags, entitlements, `Info.plist` keys | +| Simulator | Boot simulators, install and launch apps, synthesize touch events, capture screenshots (175179787); agents can also verify watchOS (Digital Crown, side and Action buttons) and tvOS (Siri Remote focus, select, Home, text entry) apps | +| Localization | Read, plan and edit translations in String Catalog files (176376425) | +| Insights | Project insights: crashes, disk writes, energy, hangs, launch issues (177568662) | +| Previews | **RenderPreview** (called "Preview Snapshot" in the first release note): variants (light/dark, orientation, type size overrides), timelines for widgets, toggle states for Live Activities; returns platform, device type and OS of the rendering simulator; supports preview groups, returns display name and line number; 27.2 returns the available render destinations and accepts one; 27.3 beta adds applied overrides to snapshot filenames and metadata, and interactive delayed snapshots for macOS previews | + +**lldb-mcp**: "LLDB now ships with an MCP server (lldb-mcp). See mcp.html for examples" (Xcode 27 release notes, Debugging, 176901842). Read that page in the LLDB documentation before wiring it; this skill does not restate its flags. + +Other LLDB additions in 27: `language swift task tree` (prints all Swift tasks the debugger knows), explicit-module import from DerivedData for bridging-header projects, inspection of `~Copyable` fields. + +## Agents inside Xcode + +- **Providers**: Claude Sonnet & Opus and ChatGPT (sign in under Intelligence settings), Google Gemini (27.0), Google Antigravity (27.0), GitHub Copilot (**27.3 beta**), any provider with a Chat Completions API (`/v1/models`, `/v1/chat/completions`), and any agent that speaks the **Agent Client Protocol (ACP)** (Add an Agent). +- **Plan mode**: a prompt that asks to plan enters plan mode automatically; invoke explicitly with `/plan`, leave with `/exit` then `/exit-plan`. Plans are editable Markdown artifacts beside the conversation to review, annotate and approve before the agent proceeds. This explores ideas without modifying code. +- **Coding assistant UI**: conversations sidebar with real-time status, artifacts (diffs, plans, preview snapshots) next to the transcript, inline annotations. +- **Specialists**: Apple-built subagents for localization, UIKit resizing and accessibility, used automatically from the prompt. +- **Plug-ins** (Intelligence settings > Agents > Plug-ins): bundles of subagents, MCP servers, skills and ACP agent configurations; skills are slash commands with completion (type `/` to list them). MCP servers in a plug-in JSON can set `_meta` fields (`ideToolIconPath`, `ideToolIconRendersAsTemplate`, `ideToolTitles`) for custom icons and tool names. +- **Per-agent config**: files live in `~/Library/Developer/Xcode/CodingAssistant/ClaudeAgentConfig`, `.../codex`, `.../gemini`; they affect agents only when launched inside Xcode (default model, extra MCP servers, own skills). +- **Permissions**: Intelligence settings > Agents > Permissions: Allowed Commands and Allowed Tools. A filesystem-access security layer (enable in Coding Intelligence settings) monitors and controls file access by agents and the processes they spawn (178289431). +- **MDM**: set `CodingAssistantAllowExternalIntegrations` to `false` in a profile to turn the coding assistant off on managed devices. + +## Choosing the tool + +| Need | Use | +|------|-----| +| Build, test, simulator screenshots and `snapshot_ui` evidence from this plugin's workflow | XcodeBuildMCP (xcodebuild-mcp.md) | +| Render SwiftUI previews as images, edit String Catalogs, read project insights (crashes, hangs), drive the Xcode debugger | Xcode's MCP server via `xcrun mcpbridge` (project open in Xcode) | +| Review a plan before code changes inside Xcode | Plan mode (`/plan`) | +| Official API docs and WWDC | Apple Docs MCP, then `browser_fetch` on developer.apple.com | diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/mcp-tools/references/xcodebuild-mcp.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/mcp-tools/references/xcodebuild-mcp.md index 7c93d95..6a8902d 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/mcp-tools/references/xcodebuild-mcp.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/mcp-tools/references/xcodebuild-mcp.md @@ -4,7 +4,7 @@ description: XcodeBuildMCP for Xcode project discovery, building, testing, runni when-to-use: building projects, validating code changes, running tests, launching on simulator, enabling extra workflows keywords: Xcode, build, build_run_sim, test_sim, scheme, simulator, session defaults, workflows, clean priority: high -related: xcodebuild-mcp-ui-verification.md, apple-docs-mcp.md +related: xcodebuild-mcp-ui-verification.md, apple-docs-mcp.md, xcode-agents.md --- # XcodeBuildMCP Usage Guide @@ -22,7 +22,9 @@ Tool names below were read from the `xcodebuildmcp@2.7.0` package manifests. } ``` -Homebrew alternative: `brew tap getsentry/xcodebuildmcp && brew install xcodebuildmcp`. Requires macOS 14.5+, Xcode 16+. +Homebrew alternative: `brew tap getsentry/xcodebuildmcp && brew install xcodebuildmcp`. Tool minimum (README read 2026-11-13): macOS 14.5+, Xcode 16.x or later, Node.js 18+ (npm install only) - this plugin targets Xcode 27.2 and the 27.2 SDKs, well above that floor, so no extra setup is needed for them. + +Rename notice: the `getsentry/XcodeBuildMCP` README (2026-11-13) now presents the project as **MobileBuildMCP** (npm package `mobilebuildmcp`, CLI `mobilebuildmcp`; `npx -y mobilebuildmcp@latest mcp`). npm registry on 2026-11-13: `mobilebuildmcp` 2.7.1 (published 2026-09-23), `xcodebuildmcp` 2.7.0 (2026-07-23, not deprecated). The `xcodebuildmcp` config above still works; check `npm view mobilebuildmcp version` before pinning. ## Workflows diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/SKILL.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/SKILL.md new file mode 100644 index 0000000..885cead --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/SKILL.md @@ -0,0 +1,93 @@ +--- +name: media-vision +description: Use when adding camera capture, media playback and Now Playing, photo library access, Vision image analysis, speech-to-text, translation, music analysis, or Core ML to an Apple-platform app — AVFoundation, AVKit, NowPlaying, MediaDevice, AVSystemRouting, PhotoKit, Vision, Speech, Core ML, Natural Language, Core Location, WeatherKit, EventKit. +versions: + avfoundation: 27.1 + vision: 27 + speech: 27 + ios: 27.2 +user-invocable: false +references: references/avfoundation-capture.md, references/now-playing-routing.md, references/photokit.md, references/vision.md, references/speech.md, references/ml-language-music.md, references/location-weather-eventkit.md +related-skills: swift-core, swiftui-core, solid-swift, ios, ipados, macos, watchos, visionos, tvos, apple-intelligence, graphics-games +--- + + +Covers the media, vision, speech and on-device ML surface of the Apple SDKs, verified against Apple's documentation JSON on 2026-11-13: AVFoundation capture (AVCaptureDeviceDirectionCoordinator 27.1 and its beta tvOS/visionOS 27.3 availability), the Now Playing framework (MediaSession, RemoteMediaSession), MediaDevice and AVSystemRouting (27.0), AVKit, PhotoKit (PHAssetResource.filename replacing the deprecated originalFilename in 27.0), Vision (RecognizeDocumentsRequest 26.0, GenerateIterativeSegmentationRequest 27.0, Vision on watchOS 27.0), Speech (SpeechAnalyzer and SpeechTranscriber 26.0, input providers 27.0), Core ML, Create ML, Translation, Natural Language, MusicUnderstanding (27.0), and Core Location, WeatherKit and EventKit briefly (no Apple-dated 2025-2026 change found). + +Every symbol cites its availability; facts known only from a WWDC26 session are labelled session claims. Foundation Models and the Core AI language model stay in the existing apple-intelligence skill and are linked, not repeated. + + +# Media and Vision + +Capture, playback, photos, image analysis, speech and language for iOS, iPadOS, macOS, watchOS, visionOS and tvOS. + +## Agent Workflow (MANDATORY) + +Before ANY implementation, delegate via `Task` — spawn 3 agents in parallel (single message, 3 `Task` calls): + +1. **fuse-ai-pilot:explore-codebase** - Find existing capture, playback, Vision and Speech usage and the deployment targets +2. **fuse-ai-pilot:research-expert** - Re-verify every symbol on its Apple JSON page (`https://developer.apple.com/tutorials/data/documentation/.json`); the apple-docs MCP search is unreliable, never conclude absence from it +3. **mcp__apple-docs__search_apple_docs** - Cross-check only; confirm availability on the JSON page + +After implementation, run **fuse-ai-pilot:sniper** for validation. + +--- + +## Overview + +### When to Use + +- Building a camera, scanner or capture pipeline +- Publishing playback to Lock Screen, Control Center, CarPlay or a third-party device +- Reading photo library metadata or letting people pick photos +- Recognizing documents, segmenting images, transcribing speech, translating text, analyzing music + +### Why this skill + +| Feature | Benefit | +|---------|---------| +| Per-symbol availability | 27.x APIs are not used on targets that lack them | +| Session claims labelled | Session-only advice is never presented as API fact | +| Foundation Models linked | No duplicate guidance with `apple-intelligence` | + +--- + +## Key Concepts + +### Availability gates +New frameworks (NowPlaying, MediaDevice, AVSystemRouting, MusicUnderstanding) are 27.0; the direction coordinator is 27.1 and beta on tvOS and visionOS 27.3. Gate with `#available`, never assume. + +### Swift-native Vision and Speech +Vision requests are structs with async `perform(on:orientation:)`; Speech uses an analyzer actor plus modules and input providers. + +### Stale update pages +Many Apple `updates/.json` pages stop in 2024 or 2025; a missing entry is not proof of no change. + +--- + +## Reference Guide + +| Need | Reference | +|------|-----------| +| Capture session, camera direction, WWDC26 camera sessions | [avfoundation-capture.md](references/avfoundation-capture.md) | +| Now Playing, remote sessions, Media Device, AVSystemRouting, AVKit | [now-playing-routing.md](references/now-playing-routing.md) | +| PHAssetResource filename change, PhotosPicker | [photokit.md](references/photokit.md) | +| Document recognition, segmentation, Vision on watchOS | [vision.md](references/vision.md) | +| SpeechAnalyzer, SpeechTranscriber, input providers | [speech.md](references/speech.md) | +| Core ML, Create ML, Translation, Natural Language, MusicUnderstanding | [ml-language-music.md](references/ml-language-music.md) | +| Core Location, WeatherKit, EventKit | [location-weather-eventkit.md](references/location-weather-eventkit.md) | +| Foundation Models, Core AI language model | `apple-intelligence` skill | +| Metal, MetalFX, games | `graphics-games` skill | +| tvOS playback UI | `tvos/references/media-playback.md` | + +--- + +## Best Practices + +1. **Capture off the main actor** - `startRunning()` is synchronous and blocking +2. **Never force-unwrap file names** - use `PHAssetResource.filename` on 27.0+ +3. **Consume Speech results concurrently** - with the analysis call +4. **Prefer the new Now Playing framework on 27.0+ targets** - keep legacy code for older targets +5. **Request least access** - write-only calendar, when-in-use location, `PhotosPicker` +6. **Verify before using a session API** - open its symbol page first +7. **Label unverified items** - session claims stay session claims diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/avfoundation-capture.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/avfoundation-capture.md new file mode 100644 index 0000000..e825229 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/avfoundation-capture.md @@ -0,0 +1,80 @@ +# AVFoundation capture + +Verified 2026-11-13 on `https://developer.apple.com/tutorials/data/documentation/.json`. The `updates/avfoundation.json` page stops at June 2024 and `updates/avkit.json` carries the September 2026 entry, so WWDC26 capture topics below are session claims unless a symbol page is cited. + +## Verified symbols + +| Symbol | Availability (symbol page) | Note | +|--------|----------------------------|------| +| `AVCaptureSession`, `AVCaptureDevice`, `AVCaptureDeviceInput`, `AVCapturePhotoOutput` | long-standing (iOS 4.0 / 10.0; tvOS 17.0; visionOS 1.0, photo output not on visionOS) | Core capture graph | +| `AVCaptureDevice.default(_:for:position:)`, `AVCaptureDevice.DiscoverySession` | iOS 10.0, visionOS 2.1 | Find cameras | +| `AVCaptureDevice.isCenterStageEnabled` | iOS 14.5, macOS 12.3, tvOS 17.0 | Class property | +| `AVCaptureDeviceDirectionCoordinator` | iOS/iPadOS/Mac Catalyst 27.1, tvOS 27.3 (beta), visionOS 27.3 (beta) | Tracks which direction each camera faces relative to a view | +| `AVCaptureDeviceDescriptor`, `AVCaptureDeviceDirectionMap` | same as the coordinator | Sendable camera identifier; `forwardFacingDeviceDescriptors` / `backwardFacingDeviceDescriptors` | +| `AVCaptureDevice.DeviceType.builtInOuterUltraWideCamera`, `.builtInInnerUltraWideCamera` | iOS/iPadOS/Mac Catalyst 27.1 | Used in Apple's coordinator sample | + +The coordinator, descriptor and direction map are `avkit` pages; the two device types are `avfoundation/avcapturedevice/devicetype-swift.struct/...` pages. The 27.3 platforms are beta at the date read. + +## Classic capture setup + +```swift +import AVFoundation + +enum CaptureError: Error { case noCamera, cannotAddInput } + +/// Builds a session with the back wide-angle camera as video input. +func makeSession() throws -> AVCaptureSession { + guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) + else { throw CaptureError.noCamera } + let session = AVCaptureSession() + let input = try AVCaptureDeviceInput(device: device) + guard session.canAddInput(input) else { throw CaptureError.cannotAddInput } + session.addInput(input) + return session +} +// startRunning() blocks: call it off the main actor, then publish state back to the UI. +``` + +## Direction-aware camera choice (Apple's pattern, 27.1) + +Create the coordinator on the main actor with the view that shows your preview and every device type you capture from, including rear cameras (a rear camera can face the person when the device opens or closes). Hold it strongly while the view is on screen. The change handler runs on the main actor soon after creation and on every change. Pass the `AVCaptureDeviceDescriptor` to the actor that owns the capture session and create the `AVCaptureDevice` there; capture configuration does not belong on the main actor. + +```swift +import AVKit + +@MainActor +final class DirectionObserver { + private var coordinator: AVCaptureDeviceDirectionCoordinator? + + func startObserving(previewView: UIView) { + coordinator = AVCaptureDeviceDirectionCoordinator( + view: previewView, + deviceTypes: [.builtInOuterUltraWideCamera, .builtInInnerUltraWideCamera] + ) { [weak self] directions in + guard let descriptor = directions.forwardFacingDeviceDescriptors.first else { return } + self?.selectCamera(with: descriptor) + } + } + + private func selectCamera(with descriptor: AVCaptureDeviceDescriptor) { /* hand to the session actor */ } +} +``` + +Source: `avkit/avcapturedevicedirectioncoordinator` (code adapted from the page). + +## WWDC26 session claims (symbols not checked here) + +| Session | Topic | URL | +|---------|-------|-----| +| 303 | Fast camera launch, deferred start, steady preview, deterministic file writing | https://developer.apple.com/videos/play/wwdc2026/303/ | +| 304 | 24MP / 48MP capture on Main, Tele, Ultra Wide; RAW, exposure-bracketed, processed; deferred photo processing | https://developer.apple.com/videos/play/wwdc2026/304/ | +| 341 | Center Stage front camera on iPhone 17, iPhone 17 Pro, iPhone Air; smart framing monitor; sensor orientation compensation | https://developer.apple.com/videos/play/wwdc2026/341/ | +| 256 | Generated subtitles and subtitle styles (AVKit, AVPlayerLayer, Media Accessibility) | https://developer.apple.com/videos/play/wwdc2026/256/ | + +Before using an API named in a session, open its symbol page: the article `avfoundation/build-a-responsive-camera-app-that-launches-quickly` returned 404 on the JSON endpoint when checked. + +## Rules + +- Capture configuration off the main actor; UI state back on it. +- Declare `NSCameraUsageDescription` and `NSMicrophoneUsageDescription` (both verified symbol pages) and request authorization before starting a session. +- Do not hardcode a physical camera as "front": use the direction coordinator on 27.1+ and the classic `position` below it. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/location-weather-eventkit.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/location-weather-eventkit.md new file mode 100644 index 0000000..5631742 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/location-weather-eventkit.md @@ -0,0 +1,40 @@ +# Core Location, WeatherKit, EventKit (brief) + +Verified 2026-11-13 on `https://developer.apple.com/tutorials/data/documentation/.json`. **No Apple-dated change for these three frameworks was found for June 2025 to today**: their `updates` pages stop at June 2024 (or are absent) and the 27 release notes have no section for them. That is inference from stale pages, not an Apple statement of "no change". The only 2026 item that touches weather is a first-party Weather Highlights feature (US English), not an API. + +## Verified symbols + +| Symbol | Availability | Use | +|--------|--------------|-----| +| `CLLocationUpdate` | iOS 17.0, macOS 14.0, tvOS 17.0, visionOS 1.0, watchOS 10.0 | `liveUpdates(_:)` returns an async sequence of updates; `location`, `isStationary` | +| `CLMonitor` (actor) | iOS 17.0, iPadOS 17.0, macOS 14.0 | Condition monitoring (geofencing-style), Swift concurrency | +| `CLServiceSession` | iOS 18.0, tvOS 18.0, visionOS 1.0 (Swift class), watchOS 11.0 | Declares that the app needs location services; authorization diagnostics via `CLLocationUpdate` flags such as `authorizationDenied`, `accuracyLimited` | +| `CLLocationManager` | iOS 2.0 and later, all platforms | Delegate-based API, still present | +| `WeatherService.shared`, `weather(for:)` (async, throws) | iOS 16.0, macOS 13.0, tvOS 16.0, visionOS 1.0, watchOS 9.0 | Needs the WeatherKit capability | +| `EKEventStore.requestFullAccessToEvents(completion:)`, `requestWriteOnlyAccessToEvents(completion:)` | iOS 17.0, macOS 14.0, visionOS 1.0, watchOS 10.0; no tvOS | Calendar access levels | + +## Patterns + +```swift +import CoreLocation +import WeatherKit + +/// Current weather at the latest live location. +func currentWeather() async throws -> Weather? { + for try await update in CLLocationUpdate.liveUpdates(.default) { + guard let location = update.location else { continue } + return try await WeatherService.shared.weather(for: location) + } + return nil +} +``` + +`CLLocationUpdate.LiveConfiguration` cases (verified): `default`, `airborne`, `automotiveNavigation`, `fitness`, `maritime`, `otherNavigation`. Hold a `CLServiceSession` for as long as the feature runs; check `CLLocationUpdate` authorization flags and show a localized explanation instead of failing silently. + +Calendar: choose write-only access when the app only adds events; full access only when it reads existing ones. Usage strings: `NSCalendarsWriteOnlyAccessUsageDescription`, `NSCalendarsFullAccessUsageDescription` (both iOS 17.0, verified). + +## Rules + +- Ask for the least access that works (write-only calendar access, when-in-use location). +- WeatherKit setup (capability, attribution) was not re-read here; check Apple's WeatherKit pages before release. +- Foundation Models tools can wrap these frameworks; see `apple-intelligence`. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/ml-language-music.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/ml-language-music.md new file mode 100644 index 0000000..af50d78 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/ml-language-music.md @@ -0,0 +1,73 @@ +# Core ML, Create ML, Translation, Natural Language, Music Understanding + +Verified 2026-11-13 on `https://developer.apple.com/tutorials/data/documentation/.json`. Core ML and Create ML (no Apple-dated change after June 2024 found; the `updates` page for Core ML stops there and the Create ML, Translation and Natural Language update pages return 404), Translation and Natural Language are stable: absence of a dated change is inferred, not stated by Apple. + +## Overview + +| Framework | Availability (landing / symbol pages) | Status | +|-----------|---------------------------------------|--------| +| Core ML (`MLModel`, `MLModelConfiguration`) | iOS 11.0 / 12.0, macOS 10.13, tvOS 11.0, visionOS 1.0, watchOS 4.0 | Present, not deprecated | +| Create ML | iOS 15.0, macOS 10.14, tvOS 16.0, visionOS 1.0 | Present | +| Core AI | 27.0, all platforms | New stack; language-model use is in the `apple-intelligence` skill, beyond that not checked here | +| Translation (`TranslationSession` iOS 18.0, `LanguageAvailability`) | framework iOS 17.4, macOS 14.4; Mac Catalyst 26.0 for session APIs; no tvOS, watchOS, visionOS | Stable | +| Natural Language (`NLTagger`, `NLLanguageRecognizer`, `NLEmbedding`) | iOS 12.0 / 13.0, macOS 10.14, tvOS 12.0, visionOS 1.0, watchOS 5.0 | Stable | +| Music Understanding (`MusicUnderstandingSession`, actor) | **27.0**, all platforms | New | + +Core AI facts verified: iOS 27 release notes (Core AI section) list "when Metal API Validation is enabled, CoreAI models might fail to execute" as fixed; session 330 shows custom Metal ops integrated into Core AI (see `graphics-games`). Other Core AI topics (MLX, specialization, entitlements) were not checked. + +## Translation (SwiftUI) + +Built-in UI: `translationPresentation(isPresented:text:attachmentAnchor:arrowEdge:replacementAction:)`. Custom flow: `translationTask(_:action:)` with a `TranslationSession.Configuration(source:target:)`; `TranslationSession` offers `translate(_:)` (the `String` overload is iOS 18.0 / macOS 15.0; the `AttributedString` overload is iOS, iPadOS, Mac Catalyst and macOS 26.4, so gate it) returning a `Response` with `sourceText` and `targetText`, and `translations(from:)` for batches. `LanguageAvailability.status(from:to:)` checks support before offering a translation. + +```swift +import SwiftUI +import Translation + +struct TranslateView: View { + @State private var configuration: TranslationSession.Configuration? + @State private var translated = "" + let source: String + + var body: some View { + VStack { + Text(translated.isEmpty ? source : translated) + Button("Translate") { + configuration = .init(source: nil, target: Locale.Language(identifier: "fr")) + } + } + .translationTask(configuration) { session in + if let response = try? await session.translate(source) { translated = response.targetText } + } + } +} +``` + +`translated` is a `@State` written from the task closure; keep it on the main actor. + +## Music Understanding (27.0) + +Create `MusicUnderstandingSession(asset:)` (async, throws) for a file or `init(audioProvider:)` for buffers, then `analyze()` or `analyze(for:)` with a set of `AnalysisType` (`.key`, `.rhythm`, `.structure`, `.pace`, `.instrumentActivity`, `.loudness`). `SessionResult` exposes optional `key`, `rhythm`, `structure`, `pace`, `instrumentActivity`, `loudness`. `loudnessResults` streams values while analysis runs; `cancel()` stops. + +```swift +import MusicUnderstanding +import AVFoundation + +/// Runs key and rhythm analysis on an audio asset. +func analyze(asset: AVAsset & Sendable) async throws -> MusicUnderstandingSession.SessionResult { + let session = try await MusicUnderstandingSession(asset: asset) + return try await session.analyze(for: [.key, .rhythm]) +} +``` + +Sources: `musicunderstanding/musicunderstandingsession`, session 253 https://developer.apple.com/videos/play/wwdc2026/253/ (six dimensions, on device, Music Understanding Lab sample), article `musicunderstanding/create-visuals-using-musicunderstanding-analysis-results`. + +## Decision guide + +| Need | Use | +|------|-----| +| Ship a trained model with classic vision or sound tasks | Core ML (`MLModel`) | +| Train a model on a Mac | Create ML | +| Text translation in a SwiftUI app | Translation | +| Tokenize, tag, detect language, sentence embeddings | Natural Language | +| Tempo, key, structure of a track | Music Understanding | +| Generative language or Apple Intelligence | `apple-intelligence` skill | diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/now-playing-routing.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/now-playing-routing.md new file mode 100644 index 0000000..5db87e2 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/now-playing-routing.md @@ -0,0 +1,70 @@ +# Now Playing, Media Device, AVSystemRouting, AVKit + +Verified 2026-11-13 on `https://developer.apple.com/tutorials/data/documentation/.json`. All four new frameworks are 27.0 and have no Apple "updates" page (404), so availability comes from each landing page and symbol page. + +## Overview + +| Framework | Availability (landing page) | Role | +|-----------|-----------------------------|------| +| `NowPlaying` | iOS/iPadOS/Mac Catalyst/macOS/tvOS/visionOS/watchOS 27.0 | Publish playback to Lock Screen, Control Center, Apple Watch, CarPlay | +| `MediaDevice` | iOS/iPadOS/Mac Catalyst 27.0 | A device extension that makes your playback hardware appear in the system media device picker | +| `AVSystemRouting` | iOS/iPadOS/Mac Catalyst 27.0 | App side: send media to third-party devices exposed by Media Device extensions | +| `MediaIntents` | 27.0, all platforms | Siri audio search (landing page only; not covered here) | + +Decision: your app plays media on this device, use `MediaSession`. Your app mirrors an external device's playback (speaker, TV), use `RemoteMediaSession`. You build the hardware's iOS side, use `MediaDeviceExtension`. Your app sends media to such a device, use `AVSystemRouting`. + +## Local session (`MediaSession`, 27.0, `@MainActor`) + +Pattern from Apple's article `nowplaying/publishing-media-sessions`: conform an `@Observable @MainActor` type to `MediaSessionRepresentable` (needs `id`, `content`, `playbackSnapshot`, `commands`), wrap it in `MediaSession`, then request primary status. + +```swift +import NowPlaying +import Observation + +@Observable +@MainActor +final class AudioPlayer: MediaSessionRepresentable { + let id = UUID().uuidString + var isPlaying = false + var elapsedTime: TimeInterval = 0 + var timestamp: Date = .now + var session: MediaSession? + + var content: (any MediaContentRepresentable)? { + MusicContent(id: "track-1", songTitle: "Title", artistName: "Artist", albumName: "Album", + type: .audio, duration: .finite(180), artwork: nil) + } + var playbackSnapshot: MediaPlaybackSnapshot? { + MediaPlaybackSnapshot(state: isPlaying ? .playing() : .paused, elapsedTime: elapsedTime, timestamp: timestamp) + } + var commands: [MediaCommand] { [.play { self.isPlaying = true }, .pause { self.isPlaying = false }] } + + func activate() async throws { + let session = MediaSession(self) + self.session = session + try await session.requestToBecomeApplicationPrimary() + } +} +``` + +Provide elapsed time and a timestamp so the system extrapolates the position between updates. Set `session = nil` when playback ends to remove it from the system. Other `MediaSession` members: `requestToBecomeSystemPrimary()`, `isApplicationPrimary`, `isSystemPrimary`, `canBecomeApplicationPrimary`. `MediaCommand.enabled(_:)` greys a control without removing it. Pages: `nowplaying/mediasession`, `.../musiccontent`, `.../mediaplaybacksnapshot`, `.../mediacommand`, `.../artwork` (all 27.0). + +## Remote session (`RemoteMediaSession`, iOS/iPadOS/Mac Catalyst 27.0) + +Uses an app extension conforming to `RemoteMediaSessionExtension`; your server sends push notifications to start and update sessions. Known issue (iOS 27 release notes, Now Playing): `RemoteMediaSession` and `RemoteMediaSessionRepresentable` always provision push tokens for the `production` APNs environment even when `aps-environment` is `development`. Workaround from Apple: use the `production` environment for testing and validation. + +## Media Device and AVSystemRouting (iOS/iPadOS 27.0) + +- `MediaDeviceExtension` (`@MainActor` protocol, an `AppExtension`): discovery, activation, playback; devices are reported through `MediaDeviceRoutingManager`; types `MediaOutputDevice`, `MediaOutputSession`. Real-time streaming (screen mirroring) also needs an audio server driver plug-in and `RealtimeSampleHandling`. +- `AVSystemRouteController` + `AVSystemRouteControllerObserver` receive `AVSystemRouteEvent`; start an `AVSystemRouteSession` on the `AVSystemRoute`; control playback with `AVSystemRouteMediaSession`; companion-app data through `AVSystemRoute.DataChannel` and `AVSystemRouteDataDelegate`. Supported protocols are declared in the Info pane. +- iOS 27 release notes, "Media Sharing Extensions": extensions using the new framework could build but not run on devices because of a runtime mismatch with the mandatory entitlement; listed as fixed. Re-test on your target build. + +Articles: `mediadevice/creating-a-media-device-extension`, `avsystemrouting/routing-media-to-third-party-devices`. + +## AVKit playback + +`AVPlayerViewController` (iOS 8.0, tvOS 9.0, visionOS 1.0, `@MainActor`) and SwiftUI `VideoPlayer` (iOS 14.0, macOS 11.0, tvOS 14.0, visionOS 1.0, watchOS 7.0) are long-standing and verified. Generated subtitles and subtitle style preview (WWDC26 session 256) are session claims: https://developer.apple.com/videos/play/wwdc2026/256/. tvOS playback details: `tvos/references/media-playback.md`. + +## Migration note + +The legacy MediaPlayer path (`MPNowPlayingInfoCenter`, `MPRemoteCommandCenter`) is not re-verified in this skill. For new 27.0+ targets Apple publishes the Now Playing framework as the path to system surfaces; for older deployment targets keep the existing code. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/photokit.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/photokit.md new file mode 100644 index 0000000..41ae154 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/photokit.md @@ -0,0 +1,34 @@ +# PhotoKit + +Verified 2026-11-13 on `https://developer.apple.com/tutorials/data/documentation/photos/.json` and the iOS/iPadOS 27 release notes (https://developer.apple.com/documentation/ios-ipados-release-notes/ios-ipados-27-release-notes, section PhotoKit). The `updates/photokit.json` page stops at June 2024. + +## Verified symbols + +| Symbol | Availability | Note | +|--------|--------------|------| +| `PHAssetResource.filename` | iOS/iPadOS/Mac Catalyst/macOS/tvOS/visionOS 27.0 | `String?` (nullable) | +| `PHAssetResource.originalFilename` | introduced iOS 9.0, **deprecated 27.0** | Declared `String` non-nullable | +| `PHAsset.addedDate` | iOS/iPadOS/macOS/tvOS/visionOS 26.0 | `Date?` | +| `PHAssetResource` | iOS 9.0, macOS 10.15, tvOS 10.0, visionOS 1.0 | | +| `PhotosPicker` (PhotosUI) | iOS 16.0, macOS 13.0, watchOS 9.0 | SwiftUI picker; no PhotoKit authorization needed for picking | + +## filename vs originalFilename (27 SDK) + +Apple's iOS 27 deprecation note: `originalFilename` is incorrectly marked non-nullable, which misrepresents the value; the new nullable `filename` property replaces it. Rebuilding on the 27 SDK shows a deprecation warning. + +```swift +import Photos + +/// Display name for a resource; never force-unwrap. +func displayName(of resource: PHAssetResource) -> String { + resource.filename ?? String(localized: "Untitled photo") +} +``` + +If your deployment target is below 27.0, `filename` is unavailable: wrap it in `if #available(iOS 27.0, *)` and fall back to `originalFilename`, treating an empty value as missing. iOS 27 notes, PhotoKit, Resolved Issues: "The `addedDate` property on `PHAsset` might return nil even though it's marked as non-nullable"; the 26.0 symbol page now types it `Date?`. Handle `nil` for every optional. + +## Rules + +- Prefer `PhotosPicker` when you only need the person's selection. +- Never assume a filename exists; show a localized fallback. +- No Apple-dated PhotoKit change other than the above was found for 2025-2026; the updates page being stale is not proof of absence. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/speech.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/speech.md new file mode 100644 index 0000000..62b82f0 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/speech.md @@ -0,0 +1,57 @@ +# Speech: SpeechAnalyzer, SpeechTranscriber, input providers + +Verified 2026-11-13 on `https://developer.apple.com/tutorials/data/documentation/speech/.json` and `.../updates/speech.json` (June 2026 entry). + +## Verified symbols + +| Symbol | Availability (symbol page) | Role | +|--------|----------------------------|------| +| `SpeechAnalyzer` (actor) | iOS/iPadOS/Mac Catalyst/macOS/tvOS/visionOS 26.0 | Manages one analysis session over modules | +| `SpeechTranscriber` | 26.0 | Speech-to-text module; `Preset`, `results`, `isAvailable`, `supportedLocales`, `installedLocales` | +| `AssetInventory`, `AssetInstallationRequest` | 26.0 | Check and install on-device models | +| `AnalyzerInput` | 26.0 | One chunk of audio for the analyzer | +| `AssetInputSequenceProvider` | **27.0** | Audio from a file or `AVAsset` as `analyzerInputs` | +| `CaptureInputSequenceProvider` | **27.0** | Audio from an `AVCaptureDevice` such as a microphone | +| `AnalyzerInputConverter` | **27.0** | Converts `AVAudioBuffer` to `[AnalyzerInput]` | +| `SFSpeechRecognizer` | iOS 10.0, macOS 10.15, visionOS 1.0; no deprecation flag | Legacy recognizer, still present | + +Apple's June 2026 update line: access audio from a file, asset or capture device with `AssetInputSequenceProvider` or `CaptureInputSequenceProvider`, and convert buffers with `AnalyzerInputConverter`. `DictationTranscriber` and `SpeechDetector` also exist as modules (landing page). + +## Transcribe a file (26.0 API) + +Use the preset constants: `.transcription`, `.transcriptionWithAlternatives`, `.timeIndexedTranscriptionWithAlternatives`, `.progressiveTranscription`, `.timeIndexedProgressiveTranscription`. + +```swift +import Speech +import AVFoundation + +/// Transcribes an audio file with the on-device transcriber. +func transcribe(file url: URL, locale: Locale) async throws -> String { + let transcriber = SpeechTranscriber(locale: locale, preset: .transcription) + if let request = try await AssetInventory.assetInstallationRequest(supporting: [transcriber]) { + try await request.downloadAndInstall() + } + let analyzer = SpeechAnalyzer(modules: [transcriber], options: nil) + + async let text: String = transcriber.results.reduce(into: "") { partial, result in + partial += String(result.text.characters) + } + let audio = try AVAudioFile(forReading: url) + if let last = try await analyzer.analyzeSequence(from: audio) { + try await analyzer.finalizeAndFinish(through: last) + } else { + await analyzer.cancelAndFinishNow() + } + return try await text +} +``` + +Consume `results` concurrently with the analysis; it is an `AsyncSequence` of `SpeechTranscriber.Result` (`text` is an `AttributedString`, `alternatives`, `range`). Check `SpeechTranscriber.isAvailable` and `supportedLocales` first; if the device is unsupported, disable the feature or fall back to `DictationTranscriber` or `SFSpeechRecognizer` (the page names a fallback type but its name is stripped in the JSON; confirm in Xcode). Neither fallback exists on tvOS: `SpeechTranscriber` is tvOS 26.0, `DictationTranscriber` is iOS, iPadOS, Mac Catalyst, macOS and visionOS 26.0, `SFSpeechRecognizer` is iOS, macOS and visionOS only. + +## Live capture (27.0) + +`CaptureInputSequenceProvider.providerWithSession(from:compatibleWith:priority:)` (async, throws) or `provider(from:in:compatibleWith:priority:)` returns a provider whose `analyzerInputs` you pass to `SpeechAnalyzer.start(inputSequence:)`; it exposes `captureSession` and `captureAudioDataOutput`. For raw buffers you already own, `AnalyzerInputConverter.converter(compatibleWith:)` then `convert(_:at:)` / `flush()`. Pair with [avfoundation-capture.md](avfoundation-capture.md) for authorization and session rules. On 26.x deployment targets build the `AnalyzerInput` stream yourself; the providers do not exist there. + +## Not verified + +The sample above was not compiled in this task. `AnalyzerInput` construction from `AVAudioPCMBuffer` was not checked; session-level tuning advice for Speech at WWDC26 was not read. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/vision.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/vision.md new file mode 100644 index 0000000..15acf71 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/media-vision/references/vision.md @@ -0,0 +1,42 @@ +# Vision + +Verified 2026-11-13 on `https://developer.apple.com/tutorials/data/documentation/vision/.json` and WWDC26 session 237 (https://developer.apple.com/videos/play/wwdc2026/237/). + +## Verified symbols (Swift-native async API) + +| Symbol | Availability | Note | +|--------|--------------|------| +| `RecognizeDocumentsRequest` | iOS/iPadOS/Mac Catalyst/macOS/tvOS/visionOS 26.0 | Document structure: text, tables, lists, barcodes; result `DocumentObservation` | +| `DetectLensSmudgeRequest` | 26.0, watchOS 27.0 | Detects lens smudge | +| `GenerateIterativeSegmentationRequest` | 27.0 (all but watchOS) | Mask from a point, rectangle or scribble, then refine | +| `RecognizeTextRequest`, `ImageRequestHandler`, `VisionRequest`, `ImageProcessingRequest` | iOS 18.0 / macOS 15.0, ImageRequestHandler and the protocols also watchOS 27.0 | Base types | + +Vision runs on watchOS from 27.0 (session 237 and the watchOS availability on `ImageRequestHandler`, `VisionRequest`, `ImageProcessingRequest`, `DetectLensSmudgeRequest`). Not every request exists on watchOS: check each symbol page. + +## Recognize a document (26.0) + +`RecognizeDocumentsRequest` conforms to `ImageProcessingRequest`, whose `perform(on:orientation:)` accepts `URL`, `Data`, `CGImage`, `CVPixelBuffer`, `CMSampleBuffer` or `CIImage` and returns `Self.Result`. + +```swift +import Vision + +/// Returns the plain transcript of the first document found in an image file. +func transcript(of imageURL: URL) async throws -> String? { + let request = RecognizeDocumentsRequest() + let observations = try await request.perform(on: imageURL, orientation: nil) + return observations.first?.document.text.transcript +} +``` + +`DocumentObservation.document` is a `Container` with `text`, `title`, `paragraphs`, `lists`, `tables`, `barcodes` (all 26.0). Configure `textRecognitionOptions` and `barcodeDetectionOptions`; `supportedRecognitionLanguages` lists languages. Use it for receipts, forms, labels and textbook pages; `RecognizeTextRequest` stays the lighter choice for plain text. WWDC25 session 272 (https://developer.apple.com/videos/play/wwdc2025/272/, read 2026-11-13): Vision returns one `DocumentObservation` per image, text is readable as `transcript`, lines, paragraphs or words (words unsupported for Chinese, Japanese, Korean, Thai), and tables expose cells by row and column. The `Result` typealias is not shown on the symbol page; the `observations.first` call shape above was not compiled here, so build it before relying on it. + +## Iterative segmentation (27.0) + +Initializers (verified): `init(seedPoint:_:)`, `init(seedBox:_:)`, `init(seedScribbleBuffer:_:)`; refine with `addIncludedPoint(_:)` / `addExcludedPoint(_:)` (both throwing). Apple's limit: at most 13 points when seeded with a point or scribble, 11 when seeded with a box. `qualityLevel` and `revision` exist; the request conforms to `DownloadableAssetsRequest`, so model assets may need downloading before first use. Sample project: `vision/segmenting-objects-using-taps-scribbles-or-rectangles` (its JSON page has no inline code). + +## Rules + +- Run requests off the main actor; update UI from the result. +- Handle an empty observation array. +- Foundation Models image input and Vision tools belong to the `apple-intelligence` skill; session 237 also covers them. +- Core Image RAW and `CIRAWFilter` (WWDC26 session 305) were not symbol-checked: session claim only. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/SKILL.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/SKILL.md index dde8b1b..0835938 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/SKILL.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/SKILL.md @@ -10,7 +10,7 @@ related-skills: swiftui-core, solid-swift, ios, macos, ipados, watchos, visionos --- -Covers Swift 6 language and platform fundamentals shared across iOS, macOS, iPadOS, watchOS, and visionOS: async/await and actors with strict concurrency checking, Sendable typing, app architecture (MVVM with @Observable as the recommended default, Clean Architecture for complex apps), async testing with XCTest, String Catalog-based localization, and performance profiling with Instruments. +Covers Swift 6 language and platform fundamentals shared across iOS, macOS, iPadOS, watchOS, and visionOS: async/await and actors with strict concurrency checking, Sendable typing, app architecture (MVVM with @Observable as the recommended default, Clean Architecture for complex apps), testing with Swift Testing first (XCTest as the legacy path), String Catalog-based localization, and performance profiling with Instruments. References cover each area in depth: concurrency, architecture/DI, testing, i18n, and performance. @@ -39,7 +39,7 @@ After implementation, run **fuse-ai-pilot:sniper** for validation. - Implementing async/await, actors, Sendable - Designing app architecture (MVVM, Clean Architecture) -- Writing async tests with XCTest +- Writing tests with Swift Testing (XCTest only for legacy and UI tests on Xcode 27.2 and earlier) - Localizing with String Catalogs - Profiling with Instruments @@ -63,7 +63,7 @@ Modern async/await with strict concurrency checking. Actors provide thread-safe MVVM with @Observable is the recommended pattern. Clean Architecture for complex apps with domain separation. ### Testing -XCTest with native async/await support. No need for expectations with async tests. +Swift Testing first: `@Test`, `#expect` / `#require`, exit tests (macOS only among Apple platforms), attachments, `Issue.record(severity:)`, `Test.cancel()`. UI tests in Swift Testing arrive with Xcode 27.3 (beta); XCTest stays the legacy and UI-test path on 27.2. Details in testing.md. ### Internationalization String Catalogs are mandatory. All user-facing text must be localized. @@ -79,11 +79,11 @@ Profile with Instruments. Use lazy loading, avoid heavy work in view body. |------|-----------| | Async/await, actors, Sendable | [concurrency.md](references/concurrency.md) | | MVVM, Clean Architecture, DI | [architecture.md](references/architecture.md) | -| XCTest, async tests, mocking | [testing.md](references/testing.md) | +| Swift Testing, exit tests, attachments, XCTest legacy, UI tests | [testing.md](references/testing.md) | | String Catalogs, localization | [i18n.md](references/i18n.md) | | Instruments, optimization | [performance.md](references/performance.md) | | Swift 6.4.x: Swift Build/SwiftPM, Subprocess 1.0, language additions | [swift-6-4.md](references/swift-6-4.md) | -| Xcode/OS 27.0-27.2: breaking changes, deprecations, 27.1/27.2 notes | [sdk-27-changes.md](references/sdk-27-changes.md) | +| Xcode/OS 27.0-27.2 (current) + 27.3 beta: breaking changes, deprecations, release notes | [sdk-27-changes.md](references/sdk-27-changes.md) | --- @@ -95,3 +95,5 @@ Profile with Instruments. Use lazy loading, avoid heavy work in view body. 4. **String Catalogs** - ALL user-facing text must be localized 5. **Profile in Release** - Always profile with `-O` optimization 6. **Value types** - Prefer structs over classes +7. **Swift Testing first** - New tests use `@Test` / `#expect`; XCTest only for legacy and, until Xcode 27.3 ships, UI tests +8. **Swift 6.2 defaults** - Decide default MainActor isolation and approachable concurrency per target (`SWIFT_DEFAULT_ACTOR_ISOLATION`, `SWIFT_APPROACHABLE_CONCURRENCY`), see concurrency.md diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/references/concurrency.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/references/concurrency.md index 4c14fcc..ab14b93 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/references/concurrency.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/references/concurrency.md @@ -1,8 +1,8 @@ --- name: concurrency -description: Swift 6.4.x (6.4.2 ships with Xcode 27.2) concurrency with async/await, actors, Sendable, nonisolated(nonsending), async defer, cancellation shields, InlineArray, Span +description: Swift 6.4.x (6.4.2 ships with Xcode 27.2) concurrency with async/await, actors, Sendable, default MainActor isolation, approachable concurrency, Observations, typed NotificationCenter messages, #bundle, strict memory safety, async defer, cancellation shields, InlineArray, Span when-to-use: implementing async operations, managing shared state, fixing data races, using Swift 6.2-6.4 features -keywords: async, await, actor, Sendable, Task, MainActor, nonisolated, TaskGroup, InlineArray, Span +keywords: async, await, actor, Sendable, Task, MainActor, nonisolated, TaskGroup, InlineArray, Span, Observations, MainActorMessage, SWIFT_DEFAULT_ACTOR_ISOLATION, SWIFT_APPROACHABLE_CONCURRENCY priority: high related: architecture.md, testing.md, performance.md --- @@ -39,19 +39,46 @@ func processFile(at url: URL) async throws { ## Swift 6.2 Features -### nonisolated(nonsending) - SE-0461 -Default behavior change: async functions stay on caller's executor. +### Default MainActor isolation +Run unannotated code on the main actor without writing `@MainActor` (suited to app targets, scripts and UI code). + +- Compiler flag `-default-isolation MainActor` (swift.org Swift 6.2 post, https://www.swift.org/blog/swift-6.2-released/, read 2026-11-13). +- Xcode build setting `SWIFT_DEFAULT_ACTOR_ISOLATION`, shown as "Default Actor Isolation": "Controls default actor isolation for unannotated code. When set to 'MainActor', @MainActor isolation will be inferred by default to mitigate false-positive data-race safety errors in sequential code" (Xcode build settings reference, https://developer.apple.com/documentation/xcode/build-settings-reference, read 2026-11-13). +- Effect on this plugin's patterns: with the setting on, `@MainActor` on view models is implicit; keep the explicit annotation in packages and non-UI targets where the setting is off. Use `nonisolated` to opt a declaration out and `@concurrent` for work that must run off the actor. + +### Approachable concurrency - nonisolated(nonsending) - SE-0461 +Async functions stay on the caller's executor instead of hopping to the global executor. + +- Xcode build setting `SWIFT_APPROACHABLE_CONCURRENCY` (name verified on the Xcode build settings reference, 2026-11-13). Apple's description: enables the upcoming features DisableOutwardActorInference, GlobalActorIsolatedTypesUsability, InferIsolatedConformances, InferSendableFromCaptures and NonisolatedNonsendingByDefault. +- Single feature, SwiftPM or compiler: `-enable-upcoming-feature NonisolatedNonsendingByDefault`. +- Async functions on classes can access `self` without data races, with fewer context switches; use `@concurrent` to opt into parallelism explicitly. + +### Observations async sequence +`Observations` (`struct Observations`, iOS 26.0, macOS 26.0 and the other 26.0 platforms) streams transactional changes of `@Observable` state: updates include all synchronous changes, and the transaction ends at the next `await` that suspends, so consumers never see torn state. + +```swift +for await count in Observations({ model.count }) { render(count) } +``` + +Initializer verified: `init(_ emit: @escaping @isolated(any) @Sendable () throws(Failure) -> Element)`. Source: https://developer.apple.com/documentation/observation/observations (read 2026-11-13). + +### Typed NotificationCenter messages +Notification payloads as concrete types instead of strings and `userInfo`. A type conforms to `NotificationCenter.MainActorMessage` (delivered synchronously on the main actor) or `NotificationCenter.AsyncMessage` (asynchronous); both iOS 26.0, macOS 26.0 and the other 26.0 platforms. -**Activation:** ```swift -// Build Setting: SWIFT_APPROACHABLE_CONCURRENCY = YES -// Or: -enable-upcoming-feature NonisolatedNonsendingByDefault +struct EventDidStart: NotificationCenter.MainActorMessage { typealias Subject = Event } +extension NotificationCenter.MessageIdentifier where Self == NotificationCenter.BaseMessageIdentifier { + static var didStart: Self { .init() } +} ``` -**Impact:** -- Async functions on classes can access `self` without data races -- Fewer context switches -- Use `@concurrent` for explicit parallelism opt-in +Conformance and identifier pattern from https://developer.apple.com/documentation/foundation/notificationcenter/mainactormessage (read 2026-11-13). Apple's page names `addObserver(of:for:using:)` for observing; its symbol page was not read, so check the exact signature on developer.apple.com before writing the observer call. + +### `#bundle` +Not listed in the Swift 6.2 post; availability is OS-based, below. `#bundle` resolves the `Bundle` of the current module (app, extension, framework or Swift package), e.g. `String(localized: "title", bundle: #bundle)`. Verified: `@freestanding(expression) macro bundle() -> Bundle`, iOS 15, macOS 12, tvOS 15, watchOS 8, visionOS 1 (https://developer.apple.com/documentation/foundation/bundle(), read 2026-11-13). + +### Strict memory safety (opt-in) +Flags every use of an unsafe construct (unsafe pointers, `@unsafe` APIs) not acknowledged with `unsafe`; the Swift 6.2 post keeps it for projects with the strongest security requirements. Xcode build setting `SWIFT_STRICT_MEMORY_SAFETY` (build settings reference, 2026-11-13: "Enable strict memory safety checking. This will produce warnings for each use of an unsafe language construct or API that isn't acknowledged with `unsafe` or `@unsafe`"). Prefer `Span` over unsafe buffer pointers to stay clear of it. ### InlineArray - SE-0453 Fixed-size stack-allocated arrays for performance. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/references/sdk-27-changes.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/references/sdk-27-changes.md index 806d018..dc9778c 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/references/sdk-27-changes.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/references/sdk-27-changes.md @@ -1,8 +1,8 @@ --- name: sdk-27-changes -description: Xcode 27.0-27.2 and OS 27.0-27.2 SDK changes that break or deprecate older guidance - scene lifecycle, launch screen, Intel, deprecations, 27.1/27.2 notes -when-to-use: migrating an app to the 27 SDK, debugging a 27.x build or launch failure, choosing deployment targets, replacing a deprecated API -keywords: Xcode 27.2, iOS 27.2, scene lifecycle, launch screen, Intel, ARCHS_STANDARD, ld64, FileDocument, PreviewProvider, On Demand Resources, WKExtension, Mac Catalyst +description: Xcode 27.0-27.2 (current release) and OS 27.0-27.2 SDK changes that break or deprecate older guidance - scene lifecycle, launch screen, Intel, deprecations, 27.1/27.2 notes - plus a clearly labelled 27.3 beta section +when-to-use: migrating an app to the 27 SDK, debugging a 27.x build or launch failure, choosing deployment targets, replacing a deprecated API, checking what the 27.3 beta adds +keywords: Xcode 27.2, Xcode 27.3 beta, iOS 27.2, XCUIHinge, supportsMultiSeatPurchase, scene lifecycle, launch screen, Intel, ARCHS_STANDARD, ld64, FileDocument, PreviewProvider, On Demand Resources, WKExtension, Mac Catalyst priority: high related: swift-6-4.md, ../../build-distribution/references/app-store.md --- @@ -11,6 +11,8 @@ related: swift-6-4.md, ../../build-distribution/references/app-store.md Xcode 27.2 ships Swift 6.4.2 and the iOS, iPadOS, macOS, tvOS, watchOS and visionOS 27.2 SDKs; it requires macOS Tahoe 26.6 or later and runs on Apple silicon only. Xcode 27.1 carried the iOS 27.1 SDK (iPhone Duo); 27.2 aligned every platform on 27.2. +Xcode 27.3 and the OS 27.3 SDKs are a **beta**; items from them are collected in the last section, never mixed with the 27.2 guidance. + Keep two things apart: the **SDK you build with** (27.2) and the **minimum deployment target** you support (your choice, often much lower). Deprecations below usually key off the SDK or off the deployment target, as stated. Sources: Xcode 27 / 27.1 / 27.2 and iOS, macOS, tvOS, watchOS, visionOS 27 / 27.2 release notes on https://developer.apple.com/documentation/xcode-release-notes and https://developer.apple.com/documentation/ios-ipados-release-notes (each platform has its own `*-release-notes` collection). @@ -47,10 +49,28 @@ Sources: Xcode 27 / 27.1 / 27.2 and iOS, macOS, tvOS, watchOS, visionOS 27 / 27. - **Mac Catalyst + iOS 27.1 API**: code using iOS 27.1-only APIs fails to compile for Mac Catalyst. Isolate with `#if !targetEnvironment(macCatalyst)` or set a Mac Catalyst 27.0 minimum deployment. - **iOS 27.2 ATT**: `AppTrackingTransparency` supports an alternative expanded prompt and yearly re-prompting for EU users; the alternative prompt is required for France, Germany, Italy, Poland and Romania. API: `requestTrackingAuthorization(preferExpandedInterface:additionalInformationAction:completionHandler:)` (renamed during the beta; verify the final signature on developer.apple.com before writing code). - **Xcode 27.2 JSON project format**: opt-in (File inspector), more merge-friendly and easier for agents to edit; such projects still open in earlier Xcode 27 releases. Convert only when every contributor is on Xcode 27.x. -- **iPhone Duo** (27.1 SDK): Duo simulator runtime lacks StandBy and most app extensions; a `CameraCaptureAccessory` app can use both displays without a capture session (known issue 190155353). `ArrangementView` is available from 27.1 on every platform (see swiftui-core/hig-iphone-duo.md). +- **iPhone Duo** (27.1 SDK): the Duo simulator runtime lacked StandBy and most app extensions in 27.1; 27.2 Device Hub adds StandBy in iPhone Duo. The 27.1 known issue that a `CameraCaptureAccessory` app could use both displays without an active capture session (190155353) is **fixed in Xcode 27.2** (Xcode 27.2 release notes, Simulator > Resolved Issues, https://developer.apple.com/documentation/xcode-release-notes/xcode-27_2-release-notes, read 2026-11-13). `ArrangementView` is available from 27.1 on every platform (see swiftui-core/hig-iphone-duo.md). - **Device Hub** (27.2): pinch/rotate via Sidecar or MacBook with Touch, input to iOS 17 simulators, Secure keyboard entry; CarPlay needs a USB-connected device. Previews: the RenderPreview MCP tool now returns render destinations and accepts one. - **StoreKit testing**: `SKTestSession.clearTransactions()` resets intro-offer eligibility, storefront/locale changes propagate through `Storefront.updates`, `dialogsDisabled` is honored (fixed in 27.2). Purchasing a subscription bundle member still allows unbundling instead of throwing (known issue). - **Simulator**: cloning a 27.2 runtime device can fail on file permissions; delete the `*.sb-????????-??????` files under the source device's `data` directory (workaround in the iOS 27.2 notes). - **Testing (Xcode 27)**: `XCUIVoiceOverService` drives VoiceOver from UI tests (focus, spoken output, navigation); a failed XCTest assertion inside a Swift Testing test (or vice versa) surfaces as a runtime-issue warning, controlled by the test plan's interoperability setting. - **Icon Composer 2.0** (Xcode 27): preview new sharper rendering (refractivity, outside specular, deeper shadows) for the 2027 OSes; one icon can serve both design generations. - **App Store upload minimum is still Xcode 26 / SDK 26** (https://developer.apple.com/news/upcoming-requirements/, checked 2026-11-08); building with Xcode 27.2 is allowed and the 27 SDK requirements above apply when you do. + +## Xcode 27.3 / OS 27.3 (BETA, not the current release) + +> **Beta.** Xcode 27.3 beta includes Swift 6.4 and the 27.3 SDKs for iOS, iPadOS, tvOS, watchOS, macOS and visionOS; it requires macOS Tahoe 26.6 or later. Behavior and APIs can change before release. Keep shipping on 27.2; use this list to plan, not to commit architecture. + +Sources (read 2026-11-13): https://developer.apple.com/documentation/xcode-release-notes/xcode-27_3-release-notes and https://developer.apple.com/documentation/ios-ipados-release-notes/ios-ipados-27_3-release-notes. + +| Beta item | Detail | +|-----------|--------| +| Device Hub drag and drop | Drop an `.app` or `.ipa` on a device to install it, drop a link to open it; on iOS simulators any other file is saved to the Files app. Option-drag simulates a two-finger touch on iPhone and iPad. Via Sidecar or a Mac with Touch only two touches reach the device (three or more are a macOS system gesture). CarPlay still needs a USB-connected device. | +| Swift Testing UI tests | Xcode supports UI tests written with Swift Testing and `XCUIAutomation` (95593221). See testing.md. | +| `XCUIHinge` | `XCUIDevice.hinge` returns `XCUIHinge?`; `angle` is settable to fold the iPhone Duo (187479559). See testing.md. | +| GitHub Copilot | Available in the coding assistant (185837709). See mcp-tools/references/xcode-agents.md. | +| RenderPreview MCP tool | Snapshot filenames and metadata include applied overrides; interactive delayed snapshots for macOS previews. | +| `Product.supportsMultiSeatPurchase` | StoreKit multiseat subscriptions; `Bool` on `Product` and `AdvancedCommerceProduct`, reflects the App Store Connect setting; the symbol page marks every platform 27.3 as beta (https://developer.apple.com/documentation/storekit/product/supportsmultiseatpurchase). | +| StoreKit Testing | Fixed: a purchase of a subscription-bundle member no longer lets the user unbundle (186018916); this closes the 27.2 known issue above. New known issue: first `SKTestSession` use may hang (186670057); workaround: set a StoreKit configuration file in the scheme's run options. | +| Xcode distribution | Xcode ships as an Apple Encrypted Archive (`.aea`), extracted from the command line with `archiveutil extractXcodeAEA`; 27.3 is the last release available as `.xip` (111337953). Matters for CI images that unpack Xcode. | +| SwiftUI | In apps built with the iOS 26 SDK, `ScrollEdgeEffectStyle.soft` rendered a fully transparent edge above a `safeAreaBar(edge:)` on iOS 27; on iOS 27.3 and later these apps get the iOS 27 soft edge effect (188312290). | diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/references/testing.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/references/testing.md index e1b6c3a..57b80f3 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/references/testing.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swift-core/references/testing.md @@ -1,148 +1,115 @@ --- name: testing -description: XCTest for Swift with async testing, UI tests, snapshot testing, mocking patterns -when-to-use: writing unit tests for ViewModels, UI automation tests, snapshot tests, testing async code -keywords: XCTest, async, await, mock, stub, UI testing, snapshot, TDD +description: Swift Testing first (@Test, #expect, exit tests, attachments, Issue severity, Test.cancel, CustomTestReflectable), Swift Testing UI tests with XCUIAutomation (27.3 beta), XCTest as the legacy path +when-to-use: writing unit or UI tests, migrating XCTest to Swift Testing, testing async code, attaching evidence to test results +keywords: Swift Testing, @Test, #expect, #require, exit test, Attachment, Issue.record, Test.cancel, CustomTestReflectable, XCUIAutomation, XCUIHinge, XCTest, XCUITest priority: high requires: architecture.md, concurrency.md -related: performance.md +related: performance.md, sdk-27-changes.md, swift-6-4.md --- -# Swift Testing +# Testing -## When to Use +Swift Testing is the default for new tests; XCTest stays for what Swift Testing does not cover yet (see "XCTest: legacy path"). Apple's Swift 6.4 post pushes migration: "Swift 6.4 makes it easier to migrate existing projects to use Swift Testing" (https://www.swift.org/blog/swift-6.4-released/, read 2026-11-13). -- Unit testing ViewModels and services -- Integration testing with dependencies -- UI automation testing -- Snapshot testing for visual regression -- Testing async/concurrent code +Sources (all read 2026-11-13): symbol pages under https://developer.apple.com/tutorials/data/documentation/testing/..., Xcode 27.3 release notes https://developer.apple.com/documentation/xcode-release-notes/xcode-27_3-release-notes, swift.org posts for 6.2 (2025-09-15), 6.3 (2026-03-24), 6.4 (2026-09-15). -## Key Concepts +## Core API (Swift 6.0 / Xcode 16.0) -### Async Testing (Native) -XCTest supports async/await natively. No expectations needed. - -**Key Points:** -- Mark test methods `async` or `async throws` -- Use `await` directly in tests -- Errors throw naturally -- Much cleaner than expectation-based tests - -### Mock Pattern -Create mock implementations of protocols for testing. - -**Key Points:** -- Mock implements same protocol as real dependency -- Stubbed return values for controlled tests -- Call tracking for verification -- Use `@unchecked Sendable` for mocks with mutable state - -### @MainActor Tests -For testing ViewModels that use @MainActor. +```swift +import Testing -**Key Points:** -- Mark test class or method `@MainActor` -- Tests run on main actor -- Required for @Observable ViewModels +@Suite(.serialized) struct CartTests { + @Test(.tags(.checkout), .timeLimit(.minutes(1))) + func total() async throws { + let cart = try #require(await Cart.load()) // unwraps or fails the test + #expect(cart.total == 42) + #expect(throws: CartError.self) { try cart.apply(code: "bad") } + } -### UI Testing -XCUITest for end-to-end UI automation. + @Test(arguments: [1, 2, 3]) func positive(value: Int) { #expect(value > 0) } +} +``` -**Key Points:** -- Use accessibility identifiers for element queries -- `waitForExistence(timeout:)` for async UI -- Launch arguments for test configuration -- Keep UI tests focused and fast +| Piece | Use | +|-------|-----| +| `@Test`, `@Suite` | Test and group; suite traits cascade to its tests | +| `#expect`, `#require` | Soft check; `#require` stops the test and unwraps optionals | +| `#expect(throws:)` | Error expectations | +| `@Test(arguments:)` | Parameterized tests | +| `confirmation(_:expectedCount:...)` | Callback or event based code (replaces `XCTestExpectation`) | +| `.serialized`, `.tags(_:)`, `.timeLimit(_:)`, `.enabled(if:)`, `.disabled(_:)` | Traits | -### Snapshot Testing -Visual regression testing with point-free/swift-snapshot-testing. +Symbol pages: `Suite(_:_:)`, `require(_:_:sourceLocation:)`, `confirmation(_:expectedCount:isolation:sourceLocation:_:)`, `Trait.serialized`, `Trait.tags(_:)`, `Trait.timeLimit(_:)`, each under `documentation/testing/` (Swift 6.0, Xcode 16.0; `timeLimit` needs iOS 16 / macOS 13). -**Key Points:** -- Test light/dark mode variants -- Test dynamic type sizes -- Test different device sizes -- Commit reference images to git +Async and actor code needs no special API: mark the test `async`, `await` directly, add `@MainActor` to the test or suite for `@MainActor` view models (see concurrency.md). ---- +## Swift 6.2 (Xcode 26.0) -## Swift 6 Async Testing Patterns +### Exit tests +Verify that code terminates (a failed `precondition`, `fatalError`). The body runs in a child process; the parent suspends until it exits. -### Testing Actors ```swift -func testActorMethod() async throws { - let actor = MyActor() - let value = await actor.getValue() - XCTAssertEqual(value, 42) +@Test func rejectsInvalidInput() async { + await #expect(processExitsWith: .failure) { Customer.current.eat(junkFood) } } ``` -### Testing Task Cancellation -```swift -func testCancellation() async throws { - let task = Task { try await longRunningOperation() } - task.cancel() - do { - _ = try await task.value - XCTFail("Should have been cancelled") - } catch is CancellationError { /* Expected */ } -} -``` +- Macro: `expect(processExitsWith:observing:_:sourceLocation:performing:)` and the `require` twin (Swift 6.2, Xcode 26.0). Conditions: `.success`, `.failure`, `.exitCode(_:)`, `.signal(_:)`. +- Platforms per Apple's article: macOS, Linux, FreeBSD, OpenBSD, Windows. **Not iOS, iPadOS, tvOS, watchOS or visionOS**: put exit tests in a macOS-capable target (e.g. a Swift package). +- Capturing parent values in the body (`{ [food] in ... }`) needs Swift 6.3+; captured values must be `Sendable` and `Codable`. Exit tests cannot nest. +- Source: https://developer.apple.com/documentation/testing/exit-testing -### Testing AsyncSequences -```swift -func testAsyncStream() async throws { - let stream = AsyncStream { c in c.yield(1); c.yield(2); c.finish() } - var values: [Int] = [] - for await value in stream { values.append(value) } - XCTAssertEqual(values, [1, 2]) -} -``` +### Attachments +Attach evidence to results: `Attachment.record(_:named:sourceLocation:)` (Swift 6.2, Xcode 26.0). `Array`, `ContiguousArray`, `ArraySlice`, `Data`, `String`, `Substring` attach as-is; `Encodable` / `NSSecureCoding` values need `Attachable` conformance (default implementation when the test target imports Foundation). Files and directories attach by URL: create `try await Attachment(contentsOf:named:)` (async, throwing), then record it. +Source: https://developer.apple.com/documentation/testing/attachments -### Swift Testing Framework (Modern) +## Swift 6.3 (Xcode 26.4) -```swift -import Testing +| API | Use | +|-----|-----| +| `Issue.record(_:severity:sourceLocation:)` with `Issue.Severity` | `.warning` shows in results without failing the test | +| `try Test.cancel(_:sourceLocation:)` (`throws -> Never`) | Cancel the running test and its task hierarchy, e.g. skip one argument of a parameterized test | +| `Attachment(_:named:as:sourceLocation:)`, `AttachableAsImage`, `AttachableImageFormat` | Image attachments on Apple and Windows platforms via cross-import overlays with UI frameworks such as UIKit | +| Exit test value capturing | See above | -// Basic test -@Test func asyncOperation() async throws { - #expect(await service.fetch().count == 10) -} +Symbol pages list Swift 6.3 / Xcode 26.4 for `Issue.record(_:severity:sourceLocation:)`, `Test.cancel`, `Attachment.init(_:named:as:sourceLocation:)`, `AttachableAsImage`, `AttachableImageFormat`. The Swift 6.3 post lists the Swift Testing proposals ST-0012, ST-0013, ST-0014, ST-0015, ST-0016, ST-0017 and ST-0020 without mapping each to a feature. Source: https://www.swift.org/blog/swift-6.3-released/ -// Test errors -@Test func throwsError() throws { - #expect(throws: ValidationError.self) { - try validate(invalid) - } -} +## Swift 6.4 (Xcode 27.0) -// Parameterized tests -@Test(arguments: [1, 2, 3]) -func testMultiple(value: Int) { - #expect(value > 0) -} -``` +- **`CustomTestReflectable`** (`var customTestMirror: Mirror { get }`, Swift 6.4 / Xcode 27.0, ST-0022): customize how a type appears in failed-expectation output. +- **`Transferable` attachments** (Apple platforms, ST-0023): `import CoreTransferable`, then `try await Attachment(exporting: value, as: .pdf)` (the `as:` content type is optional) and `Attachment.record(_:)`. The initializer exists only when the test target imports CoreTransferable. +- **Interop (ST-0021)**: `XCTAssert` works inside Swift Testing tests and `#expect` inside XCTests; a failed cross-framework assertion surfaces as a runtime warning, controlled by the test plan's "Swift Testing and XCTest Interoperability" setting. +- **`swift test` repetition** (ST-0024): see swift-6-4.md. +- Sources: https://www.swift.org/blog/swift-6.4-released/, https://developer.apple.com/documentation/testing/customtestreflectable -**Swift 6.4 / Xcode 27 migration:** `XCTAssert` works inside Swift Testing tests and `#expect` inside XCTests (ST-0021); a failed cross-framework assertion surfaces as a runtime warning, controlled by the test plan's "Swift Testing and XCTest Interoperability" setting. +## UI tests with Swift Testing (Xcode 27.3 beta) ---- +> **Beta.** Xcode 27.3 is a beta; verify before shipping a test architecture on it. Xcode 27.2 is the current release. -## Best Practices +Xcode 27.3 beta release notes: "Xcode now supports writing UI tests with Swift Testing and `XCUIAutomation`" (Swift Testing, 95593221) and "`XCUIAutomation` supports setting the hinge angle on iPhone Duo with a new `XCUIHinge` class" (UI Automation, 187479559). `XCUIDevice.hinge` returns `XCUIHinge?` (nil when the device has no hinge) and `XCUIHinge.angle` is `CGFloat { get set }`; setting it can switch displays, and opening the hinge programmatically on a closed physical device fails the test. The symbol pages carry no OS version (Xcode 16.3 only), so treat the 27.3 beta notes as the availability source. Pages: `documentation/xcuiautomation/xcuihinge`, `.../xcuidevice/hinge`. -- ✅ One assertion concept per test -- ✅ Use descriptive test names -- ✅ Test behavior, not implementation -- ✅ Mock external dependencies -- ✅ Use @MainActor for ViewModel tests -- ❌ Don't test private methods directly -- ❌ Don't sleep() - use async/await +Until 27.3 ships, write UI tests with XCUITest (below). `XCUIVoiceOverService` (iOS 27.0, `@MainActor class`) drives VoiceOver from UI tests. ---- +## XCTest: legacy path -## Naming Convention +Keep XCTest for UI tests on Xcode 27.2 and earlier, performance metrics (`measure`), and projects not yet migrated. Migrate one file at a time using ST-0021 interop; Apple's guide: https://developer.apple.com/documentation/testing/migratingfromxctest -``` -test_[methodName]_[scenario]_[expectedResult] -``` +- Async: mark methods `async` / `async throws`, `await` directly; no expectations needed. +- `@MainActor` on the class or method for `@MainActor` view models. +- Cancellation, actors and async sequences test the same way as in Swift Testing: `await` the actor, `task.cancel()` then expect `CancellationError`, iterate the stream with `for await`. +- XCUITest: accessibility identifiers for queries, `waitForExistence(timeout:)`, launch arguments for configuration, focused and fast tests. +- Snapshot testing (point-free `swift-snapshot-testing`): light/dark, Dynamic Type sizes, device sizes, reference images in git. + +## Mocks + +Mock the same protocol as the real dependency, stub return values, track calls. Use `@unchecked Sendable` only for mocks with mutable state guarded by a lock or actor. + +## Best Practices -→ See `templates/viewmodel-tests.md` for code examples +- One concept per test; test behavior, not implementation; mock external dependencies. +- Descriptive test names (Swift Testing accepts a display name or a raw identifier test name, Swift 6.2). +- Use `Issue.record(severity: .warning)` for non-failing diagnostics, `Test.cancel()` instead of silent early returns. +- Attach screenshots, JSON or logs on failure paths. +- Do not `sleep()`; use `confirmation`, `await`, or `waitForExistence`. +- Do not test private methods directly. diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/SKILL.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/SKILL.md index 5158883..95924d6 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/SKILL.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/SKILL.md @@ -5,7 +5,7 @@ versions: swiftui: 6 ios: 27.2 user-invocable: false -references: references/views-modifiers.md, references/navigation.md, references/data-swiftdata.md, references/state-management.md, references/liquid-glass.md, references/app-intents.md, references/hig-accessibility.md, references/hig-rtl.md, references/hig-modality.md, references/hig-system-surfaces.md, references/hig-iphone-duo.md +references: references/views-modifiers.md, references/navigation.md, references/data-swiftdata.md, references/state-management.md, references/liquid-glass.md, references/app-intents.md, references/hig-accessibility.md, references/hig-rtl.md, references/hig-modality.md, references/hig-system-surfaces.md, references/hig-iphone-duo.md, references/data-swiftdata-27.md, references/swiftui-26-27-apis.md, references/toolbars-navigation.md, references/widgetkit-activitykit.md related-skills: swift-core, solid-swift, ios, macos, ipados, watchos, visionos, tvos --- @@ -76,10 +76,14 @@ Modern persistence with @Model. Replaces Core Data for most use cases. |------|-----------| | Views, modifiers, layouts | [views-modifiers.md](references/views-modifiers.md) | | NavigationStack, deep linking | [navigation.md](references/navigation.md) | -| SwiftData, @Query, CloudKit | [data-swiftdata.md](references/data-swiftdata.md) | +| SwiftData, @Query, CloudKit, migrations | [data-swiftdata.md](references/data-swiftdata.md) | +| SwiftData 27: sectioned @Query, `codable`, ResultsObserver, HistoryObserver | [data-swiftdata-27.md](references/data-swiftdata-27.md) | +| WebView/WebPage, @Animatable, dragContainer, rich TextEditor, item alerts, status bar, TabsPickerStyle, 27.1 hinge toolbar | [swiftui-26-27-apis.md](references/swiftui-26-27-apis.md) | | @State, @Observable, Environment | [state-management.md](references/state-management.md) | | Liquid Glass all platforms | [liquid-glass.md](references/liquid-glass.md) | -| Siri, Shortcuts, App Intents | [app-intents.md](references/app-intents.md) | +| Siri, Shortcuts, App Intents, long-running/cancellable/snippet intents | [app-intents.md](references/app-intents.md) | +| WidgetKit push, controls, CarPlay/visionOS widgets, scheduled Live Activity | [widgetkit-activitykit.md](references/widgetkit-activitykit.md) | +| Toolbars (ToolbarSpacer, shared glass background), search as a tab, tab bar minimize, scroll edge effects, menu icons, SF Symbols 27 | [toolbars-navigation.md](references/toolbars-navigation.md) | ### HIG Rules (load for any UI task) @@ -101,3 +105,4 @@ Modern persistence with @Model. Replaces Core Data for most use cases. 4. **System colors** - Custom colors ship light, dark and increased-contrast variants ([HIG color](https://developer.apple.com/design/human-interface-guidelines/color)) 5. **Accessibility** - Label icon-only controls, layout survives AX5, targets >= 44 pt on iOS ([hig-accessibility.md](references/hig-accessibility.md)) 6. **Platform adaptation** - Size classes, never fixed widths or device checks ([HIG layout](https://developer.apple.com/design/human-interface-guidelines/layout)) +7. **Verify the symbol on the complete reference** - check name, signature and availability on `https://developer.apple.com/tutorials/data/documentation//.json` (e.g. `swiftui/toolbarspacer.json`, lowercase path); HIG pages: `.../tutorials/data/design/human-interface-guidelines/.json`. Never conclude an API is absent from the apple-docs MCP search alone (it returned 0 results for the real `ToolbarSpacer`) diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/app-intents.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/app-intents.md index f21ed19..a654965 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/app-intents.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/app-intents.md @@ -1,21 +1,23 @@ --- name: app-intents -description: App Intents framework for Siri, Shortcuts, and Spotlight integration -when-to-use: adding Siri voice commands, Shortcuts actions, Spotlight donations -keywords: AppIntent, Parameter, Siri, Shortcuts, AppShortcutsProvider +description: App Intents framework for Siri, Shortcuts, and Spotlight integration, plus the iOS 26/27 runtime APIs (foreground modes, long-running, cancellable, undoable, snippet, entity collections) +when-to-use: adding Siri voice commands, Shortcuts actions, Spotlight donations, long-running or cancellable intents, interactive snippets +keywords: AppIntent, Parameter, Siri, Shortcuts, AppShortcutsProvider, LongRunningIntent, supportedModes, UndoableIntent, CancellableIntent, SnippetIntent, EntityCollection, SyncableEntity, allowedExecutionTargets priority: medium -related: views-modifiers.md, navigation.md +related: views-modifiers.md, navigation.md, hig-system-surfaces.md --- # App Intents +Apple Intelligence app schemas, `IndexedEntity`, visual intelligence and assistant schemas live in the `apple-intelligence` skill (`apple-intelligence/references/system-features.md`); do not duplicate them here. + ## AppIntent Protocol ```swift import AppIntents struct OpenArticleIntent: AppIntent { - static var title: LocalizedStringResource = "Open Article" + static var title: LocalizedStringResource { "Open Article" } @Parameter(title: "Article") var article: ArticleEntity @@ -28,6 +30,10 @@ struct OpenArticleIntent: AppIntent { } ``` +### `static var` vs `static let` + +`title` is a protocol requirement `static var title: LocalizedStringResource { get }`. Apple's `AppIntent` page writes it as a computed property (`static var title: LocalizedStringResource { "Order Album" }`) and its `AppEntity` page writes `static let defaultQuery = TrailEntityQuery()`. Several Apple sample pages (`LongRunningIntent`, `CancellableIntent`, `EntityCollection`) still use a stored `static var title: LocalizedStringResource = "..."`; that is mutable global state, which Swift 6 language mode rejects (SE-0412, https://github.com/swiftlang/swift-evolution/blob/main/proposals/0412-strict-concurrency-for-global-variables.md). Use a computed `static var` or `static let` in this skill's code. Sources (read 2026-11-13): https://developer.apple.com/documentation/appintents/appintent, https://developer.apple.com/documentation/appintents/appentity, https://developer.apple.com/documentation/appintents/appintent/title + --- ## App Entity @@ -37,8 +43,8 @@ struct ArticleEntity: AppEntity { var id: String var title: String - static var defaultQuery = ArticleQuery() - static var typeDisplayRepresentation: TypeDisplayRepresentation = "Article" + static let defaultQuery = ArticleQuery() + static var typeDisplayRepresentation: TypeDisplayRepresentation { "Article" } var displayRepresentation: DisplayRepresentation { DisplayRepresentation(title: "\(title)") @@ -56,6 +62,8 @@ struct ArticleQuery: EntityQuery { } ``` +`TypeDisplayRepresentation` is `ExpressibleByStringLiteral`. + --- ## App Shortcuts Provider @@ -88,9 +96,68 @@ func perform() async throws -> some IntentResult & ReturnsValue { .resul --- +## Runtime: where and how an intent runs + +All sources read 2026-11-13 on `https://developer.apple.com/tutorials/data/documentation/appintents/.json`; change summary https://developer.apple.com/documentation/updates/appintents. + +| API | Availability | Use | +|-----|--------------|-----| +| `static var supportedModes: IntentModes` | 26.0 | Foreground/background requirement: `.background`, `.foreground`, `.foreground(_:)` with `.immediate`, `.dynamic`, `.deferred`; combinable | +| `systemContext.currentMode` (`IntentModes.Current`) | 26.0 | Inside `perform()`: compare with `.foreground`/`.background`; `canContinueInForeground` says whether a background run may switch | +| `UndoableIntent` | 26.0 | Register undoable work via `@MainActor var undoManager: UndoManager?` | +| `SnippetIntent` | 26.0 | Interactive snippet: `perform()` returns `some IntentResult & ShowsSnippetView`, `.result(view:)`; `ShowTodoListIntent.reload()` refreshes it | +| `CancellableIntent` | 26.4 | Graceful cancel: `withIntentCancellationHandler(operation:onCancel:)`; `IntentCancellationReason` separates a deliberate cancel from a timeout | +| `LongRunningIntent` (: `ProgressReportingIntent`) | 27.0 | Extended background time: `performBackgroundTask(options:operation:)`; report through `progress` | +| `static var allowedExecutionTargets: IntentExecutionTargets` | 27.0 | Which process runs it: `.main`, `.appIntentsExtension`, `.widgetKitExtension`, `.default` | +| `EntityCollection` | 27.0 | Parameter type holding identifiers only; `identifiers`, `resolvedEntities()`, `append`, `remove` | +| `SyncableEntity` (: `AppEntity`) | 27.0 | Entity id identical across devices; lets Siri continue a conversation on another device | +| `RunSystemShortcutIntent` | iOS/iPadOS/Mac Catalyst 27.0 | Widget-only: `init(shortcut:)` button that opens an app or runs an App Shortcut, custom shortcut or system action | + +```swift +struct UploadFileIntent: LongRunningIntent { + static var title: LocalizedStringResource { "Upload Large File" } + @Parameter(title: "File") var file: IntentFile + + func perform() async throws -> some IntentResult & ReturnsValue { + let result = try await performBackgroundTask { + progress.totalUnitCount = 100 + for chunk in 0..<100 { + try Task.checkCancellation() + await uploadChunk(chunk) + progress.completedUnitCount = Int64(chunk + 1) + } + return "Upload complete!" + } + return .result(value: result) + } +} + +struct DisableAlarmsIntent: AppIntent { + static var title: LocalizedStringResource { "Disable Alarms" } + @Parameter(title: "Alarms") var alarms: EntityCollection + + func perform() async throws -> some IntentResult { + try await AlarmService.disable(alarms.identifiers) // no hydration of every entity + return .result() + } +} +``` + +Both bodies follow Apple's `LongRunningIntent` and `EntityCollection` examples; the title is written in the computed form (see above). + +Notes: +- A snippet's `perform()` can run several times: fetch fresh state each call. +- `RunSystemShortcutIntent` does nothing outside a widget; the person chooses the action when configuring the widget. +- `SyncableEntity`: if the id is already stable (e.g. a server UUID) just adopt it; if local and stable ids differ, follow the identifier type on https://developer.apple.com/documentation/appintents/syncableentity. +- iOS 27 release notes (Resolved Issues): an `AppEntity` instance has a cumulative size limit of 10 MB including child properties (the app might crash and the exception is logged when exceeded); a widget extension whose `WidgetConfigurationIntent` has a `@UnionValue` property might not render its timeline (resolved in 27). + +--- + ## Best Practices -- Keep `perform()` fast — Siri has strict timeouts +- Keep `perform()` fast unless it adopts `LongRunningIntent` - Siri has strict timeouts - Use `@MainActor` when updating UI from intents - Provide `suggestedEntities()` for quick parameter selection - Use `AppShortcutsProvider` for automatic Spotlight/Siri exposure +- Declare `supportedModes` honestly; branch on `systemContext.currentMode` instead of assuming foreground +- Use `EntityCollection` for parameters that can hold many entities diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/data-swiftdata-27.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/data-swiftdata-27.md new file mode 100644 index 0000000..a201eae --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/data-swiftdata-27.md @@ -0,0 +1,72 @@ +--- +name: data-swiftdata-27 +description: SwiftData 27 additions - sectioned @Query, the codable attribute option, ResultsObserver and HistoryObserver +when-to-use: grouping query results into sections, storing a Codable type you do not control, observing models or remote history outside a view +keywords: SwiftData, sectionBy, SectionedResults, ResultsSection, Attribute codable, ResultsObserver, HistoryObserver, ModelActor +priority: medium +requires: data-swiftdata.md +related: state-management.md +--- + +# SwiftData 27 + +All symbols below are `iOS 27.0 / iPadOS / macOS 27.0 / tvOS / visionOS / watchOS 27.0`, checked on their Apple JSON pages (`https://developer.apple.com/tutorials/data/documentation/swiftdata/.json`) on 2026-11-13. Apple's summary of the changes: https://developer.apple.com/documentation/updates/swiftdata + +## Sectioned @Query + +Create the query with a macro that takes a `sectionBy` parameter (listed on https://developer.apple.com/documentation/swiftdata/query). The property type becomes `SectionedResults`; each section is a `ResultsSection` that is itself a random-access collection of models. + +```swift +@Query(sort: \.name, sectionBy: \.category) +var items: SectionedResults + +ForEach(items) { section in + Section(section.title) { + ForEach(section) { item in Text(item.name) } + } +} + +let workCount = items[sectionTitle: "Work"]?.count ?? 0 // O(1) lookup by section title +``` + +`SectionedResults` also exposes `sectionTitles`, `contains(sectionTitle:)` and `index(ofSectionTitled:)`. Source: https://developer.apple.com/documentation/swiftdata/sectionedresults + +## `codable` attribute option + +`Schema.Attribute.Option.codable` ("Uses the property's codable representation to store the property") lets a model store a `Codable` type, including one you do not control. Pass it to `@Attribute`: + +```swift +@Attribute(.codable) var address: Address // Address: Codable +``` + +Source: https://developer.apple.com/documentation/swiftdata/schema/attribute/option/codable (declaration `static var codable: Schema.Attribute.Option`). `codable` sits beside `externalStorage`, `unique`, `transformable(by:)` and `ephemeral` in `Schema.Attribute.Option`, and `@Attribute` accepts `Schema.Attribute.Option...` (https://developer.apple.com/documentation/swiftdata/attribute(_:originalname:hashmodifier:)). + +## ResultsObserver + +`final class ResultsObserver` observes a fetch outside a view (`@Observable`, so SwiftUI tracks it). It reacts to local changes, other contexts in the container, and external changes (other processes, CloudKit sync). Use `Never` as `SectionTitle` when not sectioning. + +```swift +let observer = try ResultsObserver( + filterBy: #Predicate { $0.isPublished }, + sortBy: [SortDescriptor(\.title)], + modelContext: context +) +let sectioned = try ResultsObserver(sectionBy: \.genre, modelContext: context) +``` + +Also available: `init(fetchDescriptor:modelContext:)`, `modelContainer:` variants, and the properties `results`, `sections`, `element(at:)`, `indexPath(for:)`. Source: https://developer.apple.com/documentation/swiftdata/resultsobserver + +## HistoryObserver + +`final class HistoryObserver` listens for `ModelContainer` remote-change notifications and bumps `eventCounter` when relevant history transactions arrive. It tracks its position in each store with `historyTokens`, so you process only new transactions. Scope it with `observedModels` (empty array = any change). + +```swift +let observer = try HistoryObserver(observedModels: [Trip.self], modelContainer: container) +// react to observer.eventCounter changing (it is @Observable) +``` + +Sources: https://developer.apple.com/documentation/swiftdata/historyobserver, https://developer.apple.com/documentation/swiftdata/historyobserver/eventcounter + +## Fixed in the iOS 27 SDK + +Deadlock when saving a `ModelContext` on a background actor while scheduling new async tasks for a `ModelActor`, with a `@Query` active. Source: iOS & iPadOS 27 release notes, SwiftData > Resolved Issues (https://developer.apple.com/documentation/ios-ipados-release-notes/ios-ipados-27-release-notes, read 2026-11-13). diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/data-swiftdata.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/data-swiftdata.md index aaf7583..c730b9f 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/data-swiftdata.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/data-swiftdata.md @@ -24,7 +24,7 @@ related: architecture.md Defines persistent model classes. Automatically generates schema. **Key Points:** -- Apply to `final class` +- Apply to a `class`. A base class you subclass cannot be `final`: Apple's inheritance article declares `@Model class Trip` and `@Model class BusinessTrip: Trip`. Mark leaf models `final` only when nothing subclasses them. Source: https://developer.apple.com/documentation/swiftdata/adopting-inheritance-in-swiftdata (read 2026-11-13) - Properties are automatically persisted - Use `@Attribute(.unique)` for unique constraints - Use `@Relationship` for associations @@ -111,14 +111,37 @@ SwiftData now supports class inheritance. **Use when:** Natural "is-a" relationships, shared properties. **Avoid when:** Single shared property (use protocols), leaf-only queries. -### Schema Migrations with Inheritance +### Schema Migrations + +There is no `@Schema` macro (`Schema` is a final class). A migration is a `VersionedSchema` per version, a `SchemaMigrationPlan` that orders them, and a `MigrationStage` per hop. Inheritance changes migrate the same way; each version lists its model types in `models`. ```swift -@Schema(version: 2, migratingFrom: .version(1)) { - // Migration logic +enum SchemaV1: VersionedSchema { + static var versionIdentifier: Schema.Version { Schema.Version(1, 0, 0) } + static var models: [any PersistentModel.Type] { [Vehicle.self] } // v1 model types +} + +enum SchemaV2: VersionedSchema { + static var versionIdentifier: Schema.Version { Schema.Version(2, 0, 0) } + static var models: [any PersistentModel.Type] { [Vehicle.self, Car.self] } +} + +enum AppMigrationPlan: SchemaMigrationPlan { + static var schemas: [any VersionedSchema.Type] { [SchemaV1.self, SchemaV2.self] } + static var stages: [MigrationStage] { + [.lightweight(fromVersion: SchemaV1.self, toVersion: SchemaV2.self)] + } } + +let container = try ModelContainer( + for: Schema(versionedSchema: SchemaV2.self), + migrationPlan: AppMigrationPlan.self, + configurations: [] +) ``` +`MigrationStage.custom(fromVersion:toVersion:willMigrate:didMigrate:)` takes optional `@Sendable (ModelContext) throws -> Void` closures for data transforms (all iOS 17.0+, verified on the JSON pages of `versionedschema`, `schemamigrationplan`, `migrationstage`, `modelcontainer`, `schema`; read 2026-11-13, e.g. https://developer.apple.com/documentation/swiftdata/schemamigrationplan). + ### Query Subclasses ```swift @@ -144,4 +167,5 @@ let sedans = try context.fetch( - ❌ Don't store large blobs (use FileManager) - ❌ Don't overuse inheritance (prefer composition) +→ SwiftData 27 (query sections, `codable` option, observers): [data-swiftdata-27.md](data-swiftdata-27.md) → See `templates/swiftdata-model.md` for code examples diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/hig-accessibility.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/hig-accessibility.md index 8ba6019..1277708 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/hig-accessibility.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/hig-accessibility.md @@ -22,6 +22,7 @@ Sources: - Layout must adapt to **all** sizes, including the largest accessibility size (`DynamicTypeSize.accessibility5`). - At accessibility sizes: show as much useful text as at the largest standard size; **never truncate in scrollable regions**; switch horizontal rows to a **stacked layout**; reduce column count; keep primary elements at the top. - Meaningful icons must scale with text (SF Symbols do automatically). +- Emphasized text styles (HIG typography, updated 2025-12-16; read 2026-11-13): system text styles have an emphasized variant (medium, semibold, bold or heavy depending on style and platform) applied through symbolic traits - SwiftUI `Text.bold()` (iOS 13.0+), UIKit `UIFontDescriptor.SymbolicTraits.traitBold`. The HIG type specification tables list the emphasized weight per style and platform. - Custom type minimums: iOS/iPadOS default 17 pt / min 11 pt; macOS 13/10; tvOS 29/23; visionOS 17/12; watchOS 16/12. macOS has no Dynamic Type. ```swift diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/hig-system-surfaces.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/hig-system-surfaces.md index 3efac1d..4a116c2 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/hig-system-surfaces.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/hig-system-surfaces.md @@ -9,7 +9,7 @@ related: app-intents.md, hig-accessibility.md # HIG System Surfaces -Code for intents lives in `app-intents.md`; this file holds the design rules. +Code for intents lives in `app-intents.md`; WidgetKit/ActivityKit APIs (push handler, controls, CarPlay/visionOS widgets, scheduled Live Activity start) in `widgetkit-activitykit.md`; this file holds the design rules. ## Widgets @@ -23,6 +23,8 @@ Source: https://developer.apple.com/design/human-interface-guidelines/widgets - Standard margins (16 pt for most widgets); use `ContainerRelativeShape` for concentric corners. - Rendering modes: full color, **accented** (tinted / clear Liquid Glass Home Screen), **vibrant** (Lock Screen, StandBy low light). Mark accent views with `widgetAccentable(_:)`; read `widgetRenderingMode`; set backgrounds with `containerBackground(_:for:)`. - watchOS complications are accessory widget families (`accessoryCircular`, `accessoryRectangular`, `accessoryInline`, `accessoryCorner`). +- **Apple HomeView** (HIG widgets, updated 2026-10-13; read 2026-11-13): widgets go on the Modular face and Home Screen, use the **small** system family and share the iPhone widget appearance (light, dark, clear, tinted); on the Modular face the widget is scaled up with the background removed. Each enrolled household member has a personal Home Screen. +- **watchOS Smart Stack widget sizes** (pt, HIG "watchOS dimensions"): 40mm 152x69.5; 41mm 165x72.5; 42mm 176x72.5; 44mm 173x76.5; 45mm 184x80.5; 46mm 194x80.5; 49mm Ultra 3/4 198x81.5; 49mm Ultra 1/2 191x81.5. Default Smart Stack background is black; use a custom color only when it adds meaning. ## Live Activities @@ -35,6 +37,7 @@ Source: https://developer.apple.com/design/human-interface-guidelines/live-activ - Animations max 2 s (none on reduced-luminance Always-On). Update only on new content; alert only for essential updates; never duplicate with push notifications. - Max one interactive element ideally; tap deep-links to the related screen. Let people stop it from inside the app; offer an App Shortcut to start it. - Types: `ActivityConfiguration`, `DynamicIsland`, `Activity.request(attributes:content:pushType:)`, `ActivityContent`. +- **Limited-width layouts** (HIG live-activities, updated 2026-10-13; read 2026-11-13): the HIG cites iPhone in landscape; the `isDynamicIslandLimitedInWidth` doc page adds iPhone Duo and iPhone 18 Pro with two or more active Live Activities, where the system renders compact and minimal presentations with reduced width. Fit compact/minimal inside a **28x28 pt circle** (short abbreviation or graphic, no full text). If both limited-width compact views do not make sense, provide the leading view and an empty trailing view; the system hides the trailing one. API: `EnvironmentValues.isDynamicIslandLimitedInWidth` (iOS/iPadOS 27.0; macOS 27.3 is beta in Apple's docs on 2026-11-13) - `@Environment(\.isDynamicIslandLimitedInWidth)`, branch the compact view on it. Live Activity size: `ActivityFamily` `.small` / `.medium` (iOS 18.0; `activityFamily` environment value). ## Notifications diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/swiftui-26-27-apis.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/swiftui-26-27-apis.md new file mode 100644 index 0000000..b3c787d --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/swiftui-26-27-apis.md @@ -0,0 +1,100 @@ +--- +name: swiftui-26-27-apis +description: Verified SwiftUI 26/27 APIs not covered elsewhere - WebView, Animatable macro, drag containers, rich TextEditor, item alerts, status bar toolbar, TabsPickerStyle, concentric radii, hosting scene delegate, 27.1 hinge and vertical-bar toolbar APIs, iOS 27 behaviour changes +when-to-use: embedding web content, animating custom views, multi-item drag, editing attributed text, presenting alerts from an item or error, hiding the status bar, tab-style pickers, folding-device toolbars +keywords: WebView, WebPage, Animatable, dragContainer, draggable, TextEditor, AttributedString, alert item, alert error, toolbarVisibility statusBar, TabsPickerStyle, concentricCornerRadii, UIHostingSceneDelegate, onHingeChange, toolbarVerticalBehavior, axisBehavior +priority: medium +related: views-modifiers.md, toolbars-navigation.md, hig-iphone-duo.md +--- + +# SwiftUI 26/27 APIs (verified) + +Every row was read on its Apple JSON page (`https://developer.apple.com/tutorials/data/documentation/.json`) on 2026-11-13; availability is the page's `introducedAt`. Change lists: https://developer.apple.com/documentation/updates/swiftui and the iOS & iPadOS 27 release notes (https://developer.apple.com/documentation/ios-ipados-release-notes/ios-ipados-27-release-notes). + +## Web content: `WebView` and `WebPage` (WebKit, iOS/iPadOS/Mac Catalyst/macOS/visionOS 26.0) + +SwiftUI-native web view; prefer it to wrapping `WKWebView`. Not available on tvOS or watchOS. + +```swift +import WebKit + +WebView(url: URL(string: "https://www.apple.com")) // init(url: URL?) + +@State private var page = WebPage() // @MainActor final class, init(configuration:) +WebView(page) // init(_ page: WebPage) +page.load(URLRequest(url: url)) // also load(_ url: URL?), load(html:baseURL:) +``` + +`load(...)` returns an `AsyncSequence` of `WebPage.NavigationEvent`. `WebPage` is observable state: `title`, `url`, `isLoading`, `estimatedProgress`, plus `callJavaScript(_:arguments:in:contentWorld:)`, `navigations`, `backForwardList`. Sources: https://developer.apple.com/documentation/webkit/webview-swift.struct, https://developer.apple.com/documentation/webkit/webpage + +## `@Animatable` macro (`Animatable()`, iOS 13.0 / macOS 10.15 back-deployed) + +Synthesizes `Animatable` conformance and `animatableData` from the type's animatable stored properties (struct, class or enum). Replace hand-written `animatableData` with it. Annotate properties that cannot animate with `@AnimatableIgnored`; no conformance is generated if the type already conforms, computed properties are excluded, and the type needs stored properties. Source: https://developer.apple.com/documentation/swiftui/animatable() + +## Multi-item drag: `dragContainer` + `draggable(containerItemID:)` (iOS/iPadOS/visionOS 27.0, macOS 26.0) + +```swift +VStack { + ForEach(fruits) { fruit in + FruitView(fruit).draggable(containerItemID: fruit.name) + } +} +.dragContainer(itemID: \Fruit.name) { ids in fruits(with: ids) } // Item: Transferable, ItemID: Hashable & Sendable +``` + +The payload closure receives the dragged ids and returns the `Transferable` items; supports lazy containers. Sources: https://developer.apple.com/documentation/swiftui/view/dragcontainer(for:itemid:in:_:), https://developer.apple.com/documentation/swiftui/view/draggable(containeritemid:containernamespace:) + +## Rich text: `TextEditor` with `AttributedString` (iOS/iPadOS/macOS/visionOS 26.0) + +`TextEditor(text: Binding, selection: Binding? = nil)`. Constrain allowed formatting with `AttributedTextFormattingDefinition` (iOS 26.0); `AttributedTextSelection` (iOS 26.0) carries the selection and its attributes. Source: https://developer.apple.com/documentation/swiftui/texteditor/init(text:selection:) + +## Alerts and dialogs from an item or an error (back-deployed to iOS 15 / macOS 12) + +```swift +.alert("Delete?", item: $pendingDelete) { item in // alert(_:item:actions:), Binding + Button("Delete", role: .destructive) { delete(item) } +} +.alert(error: $loadError) { Button("OK") {} } // alert(error:actions:), E: LocalizedError +.confirmationDialog("Share", item: $shareItem) { item in ... } // confirmationDialog(_:item:titleVisibility:actions:) +``` + +Actions use `@ContentBuilder`. Sources: https://developer.apple.com/documentation/swiftui/view/alert(_:item:actions:), https://developer.apple.com/documentation/swiftui/view/alert(error:actions:), https://developer.apple.com/documentation/swiftui/view/confirmationdialog(_:item:titlevisibility:actions:) + +## Status bar (iOS/iPadOS/Mac Catalyst 27.0) + +`ToolbarPlacement.statusBar` plugs into the existing bar modifiers: `.toolbarVisibility(hide ? .hidden : .automatic, for: .statusBar)` and `.toolbarColorScheme(scheme, for: .statusBar)` (iOS 27 release notes, SwiftUI > New Features; `ToolbarPlacement.statusBar` page: https://developer.apple.com/documentation/swiftui/toolbarplacement/statusbar). +## `TabsPickerStyle` (all platforms 27.0 except watchOS) + +`.pickerStyle(.tabs)`: like `.segmented`, but VoiceOver reads "tabs" and macOS draws a distinct look. Use it for pickers that switch content or navigation, not for value selection (e.g. text alignment). Source: https://developer.apple.com/documentation/swiftui/tabspickerstyle (release note rationale from the iOS 27 notes). + +## `GeometryProxy.concentricCornerRadii` (27.0, all platforms) + +`RectangleCornerRadii?` concentric with the container shape (and `concentricCornerRadii(in:)`), for custom drawing or layout without rendering a `ConcentricRectangle`. Source: https://developer.apple.com/documentation/swiftui/geometryproxy/concentriccornerradii + +## `UIHostingSceneDelegate` (iOS/iPadOS/Mac Catalyst/visionOS 26.0, tvOS 27.0) + +Bridges SwiftUI scenes into a UIKit lifecycle: declare SwiftUI scenes in the static `rootScene`, activate one by id or presented value with `UISceneSessionActivationRequest`, and return the class from `application(_:configurationForConnecting:options:)` via `UISceneConfiguration`. Source: https://developer.apple.com/documentation/swiftui/uihostingscenedelegate + +## iOS/iPadOS 27.1 hinge and vertical-bar APIs (all platforms 27.1) + +Foldable (iPhone Duo) support; layout rules in [hig-iphone-duo.md](hig-iphone-duo.md). + +| API | Role | +|-----|------| +| `onHingeChange(isEnabled:_:)` | Action receiving two `DeviceHingeContext` values when the hinge context changes | +| `DeviceHingeContext.hinge` | Current `DeviceHinge?`; `DeviceHinge` has `angle: Angle` and `status` | +| `toolbarVerticalBehavior(_:)` | `ToolbarVerticalBehavior`: `.automatic`, `.disabled` | +| `axisBehavior(_:)` on `ToolbarContent` | `ToolbarItemAxisBehavior`: `.automatic`, `.horizontalOnly`, `.verticalPreferred`; a `.horizontalOnly` item is hidden when no horizontal bar exists | +| `toolbarVerticalCompressionBehavior(_:)` | How bars compress when space is constrained | +| `EnvironmentValues.toolbarVerticalEdge` | `HorizontalEdge?` where the vertical bar sits | + +Sources: https://developer.apple.com/documentation/swiftui/view/onhingechange(isenabled:_:), https://developer.apple.com/documentation/swiftui/toolbaritemaxisbehavior, https://developer.apple.com/documentation/swiftui/toolbarverticalbehavior + +## iOS 27 behaviour changes (SDK 27 builds) + +- **Selectable `Text`** (`.textSelection(.enabled)`) now uses the system text selection UI (loupe, handles) instead of a callout menu; extra gestures may appear. Wrap custom gestures on such text in `.highPriorityGesture()`. A custom `TextRenderer` now applies to selectable text. +- **`TabView`** may crash if `selection` points at a hidden or unavailable tab: keep it on a visible tab. +- **Menus**: iPadOS/macOS menu bar and macOS context menus hide menu item symbol images by default; use `labelStyle(.titleAndIcon)` when the item stands for an object or concept. +- **`@Entry`** warns when the default value is a class instance or closure. + +Source: iOS & iPadOS 27 release notes, SwiftUI > New Features / Resolved Issues (read 2026-11-13). diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/toolbars-navigation.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/toolbars-navigation.md new file mode 100644 index 0000000..451e14c --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/toolbars-navigation.md @@ -0,0 +1,68 @@ +--- +name: toolbars-navigation +description: Liquid Glass toolbars, ToolbarSpacer, sharedBackgroundVisibility, search as a tab, tab bar minimize, scroll edge effects, menu item icons and SF Symbols 27 symbol APIs +when-to-use: building or reviewing toolbars, navigation bars, tab bars, sidebars, search placement, menu icons or symbol animations on iOS/iPadOS/macOS 26+ +keywords: ToolbarSpacer, sharedBackgroundVisibility, DefaultToolbarItem, searchToolbarBehavior, Tab role search, tabBarMinimizeBehavior, scrollEdgeEffectStyle, backgroundExtensionEffect, menu icons, SF Symbols 27, SF Symbols 8 beta, drawOn +priority: high +related: liquid-glass.md, navigation.md, views-modifiers.md, hig-modality.md +--- + +# Toolbars, Tab Bars, Search and Symbols (Liquid Glass era) + +Complements `liquid-glass.md` (glass rules) and `navigation.md` (stacks, split views). Every symbol below was read on its `developer.apple.com/tutorials/data/documentation/...json` page on 2026-11-13; HIG rules come from `developer.apple.com/tutorials/data/design/human-interface-guidelines/.json` (same date). Per `swiftui-core/SKILL.md`: verify any other symbol the same way; never conclude an API is absent from the apple-docs MCP search alone. + +## Toolbars (HIG toolbars, updated 2025-12-16 for Liquid Glass) + +- Three content types: title, navigation controls (back, search), actions. Positions: leading (not customizable), center (customizable, collapses to overflow), trailing (always visible: inspector buttons, search, More menu, primary action). +- Do not add an overflow menu by hand (macOS/iPadOS add it); aim for at most three groups; prefer SF Symbols over text (except Done-like actions); one primary action, trailing, tinted. +- Do not paint custom bar backgrounds: they fight the system background effect. Let the content layer set the color; use a scroll edge effect to separate bar from content. +- Separate adjacent text-labeled buttons with fixed space so labels do not read as one action. + +| API (availability read 2026-11-13) | Use | +|---|---| +| `ToolbarSpacer(_ sizing: SpacerSizing = .flexible, placement: ToolbarItemPlacement = .automatic)` iOS/iPadOS/macOS 26.0; `SpacerSizing` cases `.fixed`, `.flexible` | Visual break between glass groups; flexible pushes items apart. Customizable via `.toolbar(id:)` | +| `ToolbarContent.sharedBackgroundVisibility(_ visibility: Visibility)` iOS/iPadOS/macOS 26.0 | Items in a bar share one glass background; `.hidden` puts the item in its own grouping (e.g. a status item in `.principal`) | +| `DefaultToolbarItem(kind:placement:)` 26.0; `ToolbarDefaultItemKind` (17.0; macOS 14.0) `.sidebarToggle` (17.0), `.title` (iOS/iPadOS 18.0, macOS 15.0), `.search` (26.0) | Position a system component (search field, sidebar toggle) explicitly | +| `ToolbarItemPlacement.primaryAction` | Primary action slot | + +```swift +.toolbar(id: "main") { + ToolbarItem(id: "share") { ShareButton() } + ToolbarSpacer(.fixed) + ToolbarItem(id: "more") { MoreButton() } + ToolbarItem(id: "status", placement: .principal) { BuildStatus() } + .sharedBackgroundVisibility(.hidden) +} +``` + +Existing toolbar APIs (`visibilityPriority`, `ToolbarOverflowMenu`, `topBarPinnedTrailing`, `toolbarMinimizationBehavior`) are listed in `views-modifiers.md`. + +## Tab bars and search (HIG tab-bars, search-fields, 2026-06-08) + +- Tab bar = sections of the app; toolbar = actions on the current view. Do not hide the tab bar except under a modal. Single-word labels; filled symbols; badges only for critical info; few tabs (extra tabs fall into More). +- iPadOS: the tab bar sits near the top and can convert to a sidebar (`TabViewStyle.sidebarAdaptable`, iOS/iPadOS 18.0). Use `NavigationSplitView` when a sidebar must not convert. Default tab list of five or fewer if people can customize. +- iOS 26: `tabBarMinimizeBehavior(_:)` with `TabBarMinimizeBehavior` `.automatic/.never/.onScrollDown/.onScrollUp`, and `tabViewBottomAccessory(content:)` (iOS/iPadOS 26.0) for a MiniPlayer-style accessory. +- **Search as a tab**: `TabRole.search` (`Tab(role: .search)`, iOS 18.0) marks the search tab; the HIG names two styles: standard tab (landing page with suggestions) and button appearance (focuses the field and shows the keyboard, returns to the previous tab on exit). Alternatives: search in a bottom or top toolbar, or an inline field next to the content it filters. Search field behavior in a toolbar: `searchToolbarBehavior(_:)` with `SearchToolbarBehavior` `.automatic`, `.minimize` (26.0). + +## Scroll edge effects and sidebars + +- `scrollEdgeEffectStyle(_ style: ScrollEdgeEffectStyle?, for edges: Edge.Set)` (26.0; not visionOS): `.automatic` (default, most opaque separation for dense bars and pinned headers), `.hard`, `.soft` (test legibility). Effects are not decoration; keep split-view panes consistent in height. +- `backgroundExtensionEffect()` (26.0): mirrors adjacent content under a floating sidebar or inspector. HIG sidebars (2026-06-08): sidebar icons use the accent color by default; a few fixed colors are acceptable when sparing; hide/show by edge swipe (iPadOS) or View menu commands (macOS). + +## Menu item icons (HIG menus, updated 2026-06-08) + +- Icons help people find items; use standard symbols for common actions (Share, Print, Search); no icon when none clearly represents the item. +- Within a group, give icons to all items or none. In SwiftUI use `Label("Rename", systemImage: "pencil")` inside `Button` in `Menu`, `contextMenu`, or `CommandMenu`. +- iOS/iPadOS menus can show a top row: small layout = 4 symbol-only items (only for closely related actions: Bold, Italic, Underline, Strikethrough); medium layout = 3 items, symbol above a short label (three important actions, e.g. Notes: Scan, Lock, Pin). visionOS supports only the small and large layouts. + +## SF Symbols 27 (announced at WWDC26 as "SF Symbols 8 beta", read 2026-11-14) + +Sources: https://developer.apple.com/sf-symbols/ (New Symbols for iOS/iPadOS/macOS/watchOS/tvOS/visionOS 27; Enhanced Search; Draw, Annotation, Variable Rendering, gradients), https://developer.apple.com/design/resources/ ("Download SF Symbols 27"), https://developer.apple.com/design/whats-new/ ("SF Symbols 8 beta", 2026-06-08). The HIG sf-symbols page (alert 2025-07-28) still documents SF Symbols 7 features; symbols and features are unavailable on older OS versions, so gate by deployment target. + +| API | Notes | +|---|---| +| `.symbolEffect(.drawOn)` / `.drawOff` (`DrawOnSymbolEffect`, `DrawOffSymbolEffect`) | 26.0 all platforms; whole symbol, by layer or individually; custom symbols need Draw annotation in the SF Symbols app | +| `symbolVariableValueMode(_:)` with `SymbolVariableValueMode` `.color`, `.draw` | 26.0 all platforms; Variable Color vs Variable Draw rendering | +| Magic Replace | default `.replace` between related symbols | + +Respect Reduce Motion for symbol animations (`hig-accessibility.md`). diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/views-modifiers.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/views-modifiers.md index 770e86b..3736d27 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/views-modifiers.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/views-modifiers.md @@ -145,6 +145,8 @@ TabView { `PreviewProvider` is deprecated (iOS 27.0): use `#Preview`. +More verified 26/27 APIs (`WebView`, `@Animatable`, drag containers, status bar, `TabsPickerStyle`, hinge toolbar APIs, behaviour changes): [swiftui-26-27-apis.md](swiftui-26-27-apis.md). + Source: developer.apple.com/documentation/updates/swiftui (June 2026); symbols re-checked on developer.apple.com (Oct 2026); deprecations and 27.x notes from the iOS & iPadOS 27 / 27.2 release notes (Nov 2026), see swift-core `references/sdk-27-changes.md`. → See `templates/view-structure.md` for code examples diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/widgetkit-activitykit.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/widgetkit-activitykit.md new file mode 100644 index 0000000..d808b17 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/swiftui-core/references/widgetkit-activitykit.md @@ -0,0 +1,65 @@ +--- +name: widgetkit-activitykit +description: WidgetKit and ActivityKit APIs for widget push updates, controls on watchOS and macOS, CarPlay and visionOS widgets, watchOS relevance widgets, and scheduled Live Activity start +when-to-use: reloading widgets with push, building controls for Control Center on Mac or Watch, adapting a widget for CarPlay or Apple Vision Pro, scheduling a Live Activity +keywords: WidgetKit, ActivityKit, WidgetPushHandler, ControlWidgetButton, ControlWidgetToggle, RelevanceConfiguration, WidgetMountingStyle, WidgetTexture, LevelOfDetail, Activity request start, ActivityStyle +priority: medium +related: hig-system-surfaces.md, app-intents.md +--- + +# WidgetKit and ActivityKit APIs + +Design rules (sizes, rendering modes, Live Activity layout) are in [hig-system-surfaces.md](hig-system-surfaces.md); this file lists the code-level APIs. Every symbol was read on its Apple JSON page (`https://developer.apple.com/tutorials/data/documentation/.json`) on 2026-11-13; change lists: https://developer.apple.com/documentation/updates/widgetkit and https://developer.apple.com/documentation/updates/activitykit. + +## Push-driven widget reloads + +`WidgetPushHandler` (iOS, iPadOS, Mac Catalyst, macOS, visionOS, watchOS 26.0) receives push tokens so your server can reload widget timelines and relevance. Register the type on the widget configuration with `pushHandler(_:)` (`WidgetConfiguration`, 26.0). + +```swift +struct MyPushHandler: WidgetPushHandler { + func pushTokenDidChange(_ pushInfo: WidgetPushInfo, widgets: [WidgetInfo]) { + // pushInfo.token is a Data; send it to your server with the widget kinds + } +} + +StaticConfiguration(kind: "Status", provider: Provider()) { entry in StatusView(entry) } + .pushHandler(MyPushHandler.self) +``` + +Sources: https://developer.apple.com/documentation/widgetkit/widgetpushhandler, https://developer.apple.com/documentation/swiftui/widgetconfiguration/pushhandler(_:), https://developer.apple.com/documentation/widgetkit/widgetpushinfo + +## Controls on watchOS and macOS + +`ControlWidgetButton` (runs an action) and `ControlWidgetToggle` (toggles state) are available on iOS/iPadOS 18.0 and, since 26.0, on macOS and watchOS. Drive them with App Intents (`AppIntent`; `SetValueIntent`, iOS 18.0, for value-setting actions; see [app-intents.md](app-intents.md)). Sources: https://developer.apple.com/documentation/widgetkit/controlwidgetbutton, https://developer.apple.com/documentation/widgetkit/controlwidgettoggle + +## Widgets in other contexts + +| Context | API | Notes | +|---------|-----|-------| +| CarPlay | `WidgetFamily.systemSmall` | Update an existing small widget so it looks right in CarPlay (updates page, Jun 2025) | +| Apple Vision Pro | `supportedMountingStyles(_:)` with `WidgetMountingStyle` `.elevated` (composite material around the widget) / `.recessed` (recessed portal) | iOS/iPadOS/Mac Catalyst/visionOS 26.0 | +| Apple Vision Pro | `widgetTexture(_:)` with `WidgetTexture` `.glass` / `.paper` | visionOS 26.0 | +| Apple Vision Pro | `@Environment(\.levelOfDetail)` / `LevelOfDetail` `.default` / `.simplified` | Show more or less information by user proximity (visionOS only: on every other platform the value is always `.default`, so never gate content on `.simplified` there); 26.0 | +| iOS, iPadOS, macOS, watchOS, visionOS | `WidgetAccentedRenderingMode` | Per-image rendering in accented mode; iOS 18.0, macOS 15.0, watchOS 11.0, visionOS 26.0 | +| watchOS | `RelevanceConfiguration` | Relevance-clue widget for the Smart Stack; watchOS 26.0 | +| watchOS, visionOS | `AppIntentConfiguration` | User-configurable widget; watchOS 10.0, visionOS 26.0 | +| watchOS | `AccessoryWidgetGroup` (+ `.accessoryWidgetGroupStyle(.circular / .roundedSquare)`) | One label and three content views, optionally interactive; watchOS 11.0 | + +Sources: https://developer.apple.com/documentation/widgetkit/widgetmountingstyle, https://developer.apple.com/documentation/widgetkit/widgettexture, https://developer.apple.com/documentation/widgetkit/levelofdetail, https://developer.apple.com/documentation/widgetkit/relevanceconfiguration, https://developer.apple.com/documentation/widgetkit/accessorywidgetgroup + +## Live Activities + +Live Activities appear automatically on the Mac menu bar and in CarPlay (ActivityKit updates page, Jun 2025); watchOS shows them in the Smart Stack. To start one at a specific time, use the scheduled request (iOS/iPadOS 26.0): + +```swift +let activity = try Activity.request( + attributes: attributes, + content: content, + pushType: nil, + style: .standard, // ActivityStyle: .standard or .transient + alertConfiguration: alert, // AlertConfiguration + start: startDate // Date +) +``` + +`Activity` and `ActivityStyle` (and the scheduled `request`) list **macOS 27.3 and Mac Catalyst 27.3 as BETA** in Apple's docs (read 2026-11-13): do not rely on them in a shipping macOS build before 27.3 is released. Sources: https://developer.apple.com/documentation/activitykit/activity/request(attributes:content:pushtype:style:alertconfiguration:start:), https://developer.apple.com/documentation/activitykit/activitystyle diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/tvos/SKILL.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/tvos/SKILL.md index 2aab9f4..e4f8e94 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/tvos/SKILL.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/tvos/SKILL.md @@ -4,7 +4,7 @@ description: Use when building Apple TV apps — focus-based navigation, Siri Re versions: tvos: 27.2 user-invocable: false -references: references/focus-system.md, references/media-playback.md, references/remote-control.md +references: references/focus-system.md, references/media-playback.md, references/remote-control.md, references/dynamic-type.md related-skills: swift-core, swiftui-core, mcp-tools --- @@ -92,7 +92,8 @@ struct ContentView: View { | Need | Reference | |------|-----------| | Focus, selection states | [focus-system.md](references/focus-system.md) | -| AVKit, video playback | [media-playback.md](references/media-playback.md) | +| AVKit, video playback, background audio, Now Playing (27) | [media-playback.md](references/media-playback.md) | +| Dynamic Type / Large Text (tvOS 27) | [dynamic-type.md](references/dynamic-type.md) | | Siri Remote, gestures | [remote-control.md](references/remote-control.md) | --- @@ -105,3 +106,4 @@ struct ContentView: View { 4. **Remote-friendly** - Siri Remote gestures 5. **Media-first** - Optimize for video/audio 6. **Multi-user** - Support user switching +7. **Large Text (tvOS 27)** - Semantic text styles, flexible constraints, layouts that adapt at accessibility sizes ([dynamic-type.md](references/dynamic-type.md)) diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/tvos/references/dynamic-type.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/tvos/references/dynamic-type.md new file mode 100644 index 0000000..f7cee33 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/tvos/references/dynamic-type.md @@ -0,0 +1,53 @@ +--- +name: dynamic-type +description: Dynamic Type (Large Text) on tvOS 27 with text styles, flexible layout and conditional layouts for grids and cards +when-to-use: making a tvOS app support larger text sizes, fixing truncated or clipped text on Apple TV +keywords: tvOS, Dynamic Type, Large Text, dynamicTypeSize, isAccessibilitySize, AnyLayout, containerRelativeFrame, adjustsFontForContentSizeCategory +priority: high +requires: focus-system.md +related: media-playback.md +--- + +# Dynamic Type on tvOS + +Source: WWDC26 session 221 "Prepare your tvOS apps for Dynamic Type", https://developer.apple.com/videos/play/wwdc2026/221/ (page and transcript read 2026-11-13). + +## Overview + +tvOS 27 adds Large Text, system-wide text scaling for every app. Dynamic Type works the same way on tvOS as on iOS: UIKit and SwiftUI scale text from the person's preference. People enable it in Settings > Accessibility > Display > Text Size and can choose sizes from Large up to Accessibility XXXL. Standard components (Labels, Buttons, navigation tab bars) scale automatically; your job is custom elements. + +You can declare Larger Text support in your Accessibility Nutrition Labels for tvOS in the App Store. + +## Fix the common issues + +| Problem | Fix | +|---------|-----| +| Hard-coded font size (`UIFont.boldSystemFont(ofSize: 28)`) | Semantic text style: SwiftUI `.font(.caption)`; UIKit `UIFont.preferredFont(forTextStyle: .headline)` plus `adjustsFontForContentSizeCategory = true` | +| Fixed width or height (`.frame(width: 300)`) truncates or clips | Flexible constraint: `.frame(maxWidth: .infinity, alignment: .leading)` | +| Not enough padding or spacing as elements grow | Adjust spacing for the larger sizes | + +Search the app for hard-coded text sizes and for fixed height and width constraints. + +## Adapt layout for larger sizes + +Read `@Environment(\.dynamicTypeSize)` and branch on `isAccessibilitySize`. + +```swift +// Poster shelf: 4 columns instead of 6 when accessibility sizes are on +.containerRelativeFrame( + .horizontal, + count: dynamicTypeSize.isAccessibilitySize ? 4 : 6, + spacing: 40) +``` + +- Cards (image, title, subtitle): switch from horizontal to vertical stacks for larger text. In SwiftUI, read `dynamicTypeSize`, choose `VStackLayout` or `HStackLayout`, and use `AnyLayout` to abstract the two. In UIKit, update `UIStackView.axis` from `preferredContentSizeCategory.isAccessibilityCategory` and call `registerForTraitChanges` with `UITraitPreferredContentSizeCategory` to react while the app runs. +- For titles that still do not fit, consider a custom marquee strategy. +- Related Apple resources linked on the session page: https://developer.apple.com/documentation/SwiftUI/Applying-Custom-Fonts-to-Text and https://developer.apple.com/documentation/UIKit/scaling-fonts-automatically. + +## Best Practices + +- ✅ Use standard text styles, never fixed font sizes +- ✅ Test with Large Text enabled up to Accessibility XXXL +- ✅ Adapt shelves, grids and cards instead of shrinking text +- ✅ Declare Larger Text in the Accessibility Nutrition Labels once supported +- ❌ Don't pin text containers to fixed widths or heights diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/tvos/references/media-playback.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/tvos/references/media-playback.md index 7ffa66d..a67dfdf 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/tvos/references/media-playback.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/tvos/references/media-playback.md @@ -19,9 +19,32 @@ related: focus-system.md, remote-control.md ## Key Concepts -### AVPlayerViewController +### AVPlayerViewController (system player UI) -Standard video player with full controls. +`AVPlayerViewController` (AVKit, tvOS 9.0+) is the class that gives your app the tvOS system playback experience: the same features and interactions as the Apple TV app, including Siri Remote voice commands and Picture in Picture. Apple's tvOS article: https://developer.apple.com/documentation/avkit/customizing-the-tvos-playback-experience (read 2026-11-13). Use it from SwiftUI through a representable: + +```swift +import AVKit +import SwiftUI + +struct SystemPlayerView: UIViewControllerRepresentable { + let player: AVPlayer + + func makeUIViewController(context: Context) -> AVPlayerViewController { + let controller = AVPlayerViewController() + controller.player = player + return controller + } + + func updateUIViewController(_ controller: AVPlayerViewController, context: Context) { + controller.player = player + } +} +``` + +### SwiftUI VideoPlayer + +`VideoPlayer` (AVKit, tvOS 14.0+; https://developer.apple.com/documentation/avkit/videoplayer, read 2026-11-13) is the SwiftUI view that shows a player with a native control UI. ```swift import AVKit @@ -64,18 +87,80 @@ let playerItem = AVPlayerItem(url: hlsURL) player.replaceCurrentItem(with: playerItem) ``` -### Background Audio +### Background Audio and Now Playing ```swift // In App init try? AVAudioSession.sharedInstance().setCategory(.playback) ``` +`AVAudioSession` is available on tvOS 9.0+ (https://developer.apple.com/documentation/avfaudio/avaudiosession, read 2026-11-13). + +For audio that continues in the background, add the Background Modes capability and select "Audio, AirPlay, and Picture in Picture"; Xcode writes `UIBackgroundModes` with the value `audio` into `Info.plist`. Apple's Xcode article "Configuring background execution modes" covers iOS, iPadOS, tvOS, visionOS and watchOS (https://developer.apple.com/documentation/xcode/configuring-background-execution-modes, read 2026-11-13), and "Configuring your app for media playback" (iOS, tvOS, visionOS; https://developer.apple.com/documentation/avfoundation/configuring-your-app-for-media-playback) says the `.playback` category plus this mode lets the app play background audio and enables AirPlay and Picture in Picture. Note: the `UIBackgroundModes` key's own reference page lists iOS, iPadOS, visionOS and watchOS but no tvOS entry, so rely on the two articles above. + +#### Publishing to system surfaces: Now Playing framework (27.0) + +The `NowPlaying` framework (tvOS 27.0 and all other platforms) makes playback controls available on the Lock Screen, Control Center and connected accessories (https://developer.apple.com/documentation/nowplaying). For a local session, from Apple's "Publishing media sessions" article (read 2026-11-13): + +- Create an `@Observable` type conforming to `MediaSessionRepresentable`; the framework reads four properties: `id` (uniquely identifies the session), `content` (what is playing), `playbackSnapshot` (playback state), `commands` (supported controls). +- Register it with the system using `MediaSession` (`@MainActor` class, generic over the representable; registration call below). +- Content types: `MusicContent`, `PodcastContent`, `MovieContent`, `TVShowContent`, `BookContent`, `RadioContent`, `HomeMediaContent`, `GenericContent`. Artwork is an `Artwork` value requested asynchronously. +- `MediaPlaybackSnapshot` takes state, elapsed time and a timestamp; the system extrapolates position between updates. + +```swift +// Adapted from Apple's "Publishing media sessions"; Track is your own model type +import NowPlaying + +@Observable +@MainActor +final class AudioPlayer: MediaSessionRepresentable { + let id: String = UUID().uuidString + + var currentTrack: Track? + var isPlaying: Bool = false + var elapsedTime: TimeInterval = 0 + var timestamp: Date = .now + + var content: (any MediaContentRepresentable)? { + guard let track = currentTrack else { return nil } + return MusicContent( + id: track.id, songTitle: track.title, artistName: track.artist, + albumName: track.album, type: .audio, + duration: .finite(track.duration), artwork: nil + ) + } + + var playbackSnapshot: MediaPlaybackSnapshot? { + MediaPlaybackSnapshot( + state: isPlaying ? .playing() : .paused, + elapsedTime: elapsedTime, + timestamp: timestamp + ) + } + + var commands: [MediaCommand] { + [.play { self.play() }, .pause { self.pause() }] + } + + func play() { /* start playback */ } + func pause() { /* pause playback */ } +} +``` + +Register the session with `MediaSession.init(_:)` (`@MainActor`, takes the representable, 27.0) and make it primary with `requestToBecomeApplicationPrimary()` (`@MainActor`, `async throws`, 27.0), as in Apple's article: + +```swift +let session = MediaSession(self) +try await session.requestToBecomeApplicationPrimary() +``` + +Sources: https://developer.apple.com/documentation/nowplaying/mediasession/init(_:) and .../requesttobecomeapplicationprimary() (read 2026-11-13). The article also states that `requestToBecomeSystemPrimary()` has no effect unless the app is in the foreground (reported by review, not re-read here). + --- ## Best Practices -- ✅ Use `VideoPlayer` for standard playback +- ✅ Use `AVPlayerViewController` (or SwiftUI `VideoPlayer`) for standard playback - ✅ Support picture-in-picture - ✅ Handle interruptions gracefully - ✅ Preload content for smooth playback diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/SKILL.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/SKILL.md index 14bb2a3..043c5ce 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/SKILL.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/SKILL.md @@ -4,16 +4,18 @@ description: Use when building Vision Pro apps — spatial computing, RealityKit versions: visionos: 27.2 user-invocable: false -references: references/spatial-computing.md, references/realitykit.md, references/ornaments.md +references: references/spatial-computing.md, references/realitykit.md, references/realitykit-27.md, references/arkit-spatial.md, references/spatial-web.md, references/ornaments.md related-skills: swift-core, swiftui-core, mcp-tools --- -Covers visionOS-specific development for Apple Vision Pro spatial computing: 3D spatial interaction, RealityKit-based 3D content rendering, immersive environments, mixed-reality features, and hand/eye tracking. +Covers visionOS-specific development for Apple Vision Pro spatial computing: 3D spatial interaction, RealityKit-based 3D content rendering (RealityKit 27 components and Reality Composer Pro 3), immersive environments, mixed-reality features, the ARKit provider stack (hand tracking with permission, world tracking, accessory tracking), Spatial Preview, Foveated Streaming, the spatial web, and SharePlay. Covers the three scene types available — WindowGroup (2D windows in space), Volume (3D bounded content), and ImmersiveSpace (full immersive experience) — with references on windows/volumes/spaces, RealityView/3D content, and ornament-based 2D UI attachments. -Best practices: start with familiar 2D windows before adding depth, introduce volumes gradually for 3D content, use ornaments to attach 2D UI to 3D scenes, respect the user's physical space rather than overwhelming it, design for natural hand tracking, and avoid rapid movements that cause eye discomfort. +Gaze: visionOS does not give apps gaze data. Eye input is system-handled hover; apps learn only about the tap (HIG Eyes). Hand tracking is an ARKit provider that needs an ImmersiveSpace and the person's permission. + +Best practices: start with familiar 2D windows before adding depth, introduce volumes gradually for 3D content, use ornaments to attach 2D UI to 3D scenes, respect the user's physical space rather than overwhelming it, use system hover and gestures first and ARKit hand tracking only when you need joints, and avoid rapid movements that cause eye discomfort. # visionOS Platform @@ -40,7 +42,8 @@ After implementation, run **fuse-ai-pilot:sniper** for validation. - Creating 3D spatial experiences - Mixed reality features - Immersive environments -- Hand and eye tracking +- Hand tracking (ARKit, with permission) and system hover/gesture input +- Spatial accessories, Mac-to-Vision Pro preview, remote rendering, spatial web ### Why visionOS Skill @@ -50,6 +53,17 @@ After implementation, run **fuse-ai-pilot:sniper** for validation. | RealityKit | 3D content rendering | | Immersive spaces | Full environment | | Volumes | 3D bounded content | +| ARKit providers | Hands, world, accessories | + +--- + +## Eyes and hands (read before designing input) + +Source: HIG Eyes, https://developer.apple.com/design/human-interface-guidelines/eyes (JSON read 2026-11-13). + +- Looking at an interactive element highlights it with a hover effect; the person then taps (indirect gesture). The HIG states: "To help preserve people's privacy, visionOS doesn't provide direct information about where people are looking before they tap." With system components visionOS tells you when the component is tapped. +- There is no eye-tracking API. Do not plan features that need gaze position. +- Hand tracking is `HandTrackingProvider` (ARKit, visionOS 1.0), run in an `ARKitSession` while your app presents a Full Space (on visionOS, ARKit data is unavailable otherwise). Add `NSHandsTrackingUsageDescription`; people can decline or revoke, so provide an alternative and handle lost access (https://developer.apple.com/documentation/visionos/setting-up-access-to-arkit-data, read 2026-11-13). Details: [arkit-spatial.md](references/arkit-spatial.md). --- @@ -68,7 +82,10 @@ After implementation, run **fuse-ai-pilot:sniper** for validation. | Need | Reference | |------|-----------| | Windows, volumes, spaces | [spatial-computing.md](references/spatial-computing.md) | -| RealityView, 3D content | [realitykit.md](references/realitykit.md) | +| RealityView, 3D content, ManipulationComponent, Entity.animate | [realitykit.md](references/realitykit.md) | +| RealityKit 27 components, Reality Composer Pro 3 | [realitykit-27.md](references/realitykit-27.md) | +| ARKit providers, Spatial Preview, USDKit, Foveated Streaming, accessories, SharePlay, TabletopKit | [arkit-spatial.md](references/arkit-spatial.md) | +| HTML model element, immersive website environments | [spatial-web.md](references/spatial-web.md) | | Attachments, UI ornaments | [ornaments.md](references/ornaments.md) | --- @@ -79,5 +96,6 @@ After implementation, run **fuse-ai-pilot:sniper** for validation. 2. **Add depth gradually** - Volumes for 3D 3. **Use ornaments** - Attach 2D UI to 3D 4. **Respect space** - Don't overwhelm user -5. **Hand tracking** - Natural interactions +5. **System input first** - Hover effects and gestures; ARKit hand tracking only for joint-level input, with a fallback 6. **Eye comfort** - Avoid rapid movements +7. **Symbols per platform** - RealityKit 27 types differ in availability (e.g. `ClothSimulationComponent` is not on macOS/tvOS); check each page ([realitykit-27.md](references/realitykit-27.md)) diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/arkit-spatial.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/arkit-spatial.md new file mode 100644 index 0000000..362b279 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/arkit-spatial.md @@ -0,0 +1,77 @@ +--- +name: arkit-spatial +description: visionOS ARKit provider stack, Spatial Preview, USDKit, Foveated Streaming, spatial accessories, SharePlay nearby and TabletopKit +when-to-use: reading hands or world data, tracking handheld accessories, previewing Mac content on Vision Pro, streaming remote-rendered scenes, multiplayer spatial games +keywords: ARKitSession, HandTrackingProvider, WorldTrackingProvider, AccessoryTrackingProvider, SharedCoordinateSpaceProvider, VisualFidelityProvider, FieldOfViewAnchor, SpatialPreview, USDKit, FoveatedStreaming, TabletopKit, groupActivityAssociation +priority: high +requires: spatial-computing.md +related: realitykit-27.md, spatial-web.md +--- + +# ARKit and the visionOS spatial stack + +Every symbol below was read on its Apple documentation JSON page on 2026-11-13 (`https://developer.apple.com/tutorials/data/documentation//.json`, same content as `https://developer.apple.com/documentation/...`). Availability is the `introducedAt` value shown on that page. + +## Overview + +On visionOS, ARKit is a provider API: create one `ARKitSession`, run the data providers you need, read their anchor streams. Apps get no gaze data (HIG Eyes); hand and world sensing are gated by permission. + +## ARKitSession and providers + +`ARKitSession` is "the main entry point for receiving data from ARKit" (visionOS 1.0, macOS 26.0). Sessions need implicit or explicit authorization; people can decline or revoke later, so offer an alternative and handle lost access (https://developer.apple.com/documentation/visionos/setting-up-access-to-arkit-data). + +| Provider / type | Purpose | Available | Permission | +|-----------------|---------|-----------|------------| +| `HandTrackingProvider` | Live hand and joint positions; anchors are `HandAnchor` | visionOS 1.0 | `NSHandsTrackingUsageDescription` | +| `WorldTrackingProvider` | Device pose and world anchors | visionOS 1.0, macOS 26.0 | none: world tracking, unlike world sensing, needs no authorization | +| image tracking, plane detection, scene reconstruction | world sensing | visionOS | `NSWorldSensingUsageDescription` | +| `AccessoryTrackingProvider` | Real-time position of accessories in the environment | visionOS 26.0 | - | +| `SharedCoordinateSpaceProvider` | Establish a shared coordinate space among multiple participants | visionOS 26.0 | - | +| `VisualFidelityProvider` | Delivers visual fidelity monitoring data | visionOS 27.0 | - | +| `FieldOfViewAnchor` | Field of view boundary polygon points in immersive space | visionOS 27.0 | - | +| `ARKitCoordinateSpaceProviding` (protocol) | Provides an ARKit coordinate space with an optional correction; `HandAnchor` conforms | macOS 27.0, visionOS 27.0 | n/a | +| `ReferenceObject.Configuration` | Configuration for an individual reference object (object tracking) | visionOS 27.0 | - | + +`-` = permission key not read on the symbol page; check the page before shipping. + +Rules: +- "ARKit data is available only when your app presents a Full Space and other apps are hidden": present the `ImmersiveSpace` first, then call `ARKitSession.run(_:)` (Apple's sample runs it in a `.task` on the space content and iterates `provider.anchorUpdates`). +- Authorization is implicit when you call `run(_:)`; call `ARKitSession.requestAuthorization(for:)` to control when the prompt appears. +- Design the declined/revoked path first: fade out or recenter dependent content, and keep a non-ARKit input route (trackpad, keyboard, accessibility input) for anything ARKit drives. +- Object tracking changes are described in session 283: https://developer.apple.com/videos/play/wwdc2026/283/ (new ways to track moving and handheld objects, new spatial accessory classes). + +## Spatial accessories + +"Generic spatial accessories" are purpose-built devices (medical instruments, steering rigs, industrial tooling) that ARKit tracks; they are distinct from spatial controllers and styli, which have dedicated APIs. ARKit keeps tracking orientation when the accessory leaves the field of view; GameController provides input and haptics. Sample code: https://developer.apple.com/documentation/visionos/working-with-generic-spatial-accessories (visionOS 27.0, Xcode 27.0). Manufacturers follow the Accessory Design Guidelines PDF linked from that page. + +## Spatial Preview (macOS 27.0, visionOS 27.0) + +Preview spatial content from a macOS app on a connected visionOS device in real time, with live syncing and bidirectional editing. `SpatialPreviewEndpoint` represents a visionOS device you can connect to (macOS 27.0; the page also lists visionOS, but the declaration is for macOS). Session 282: https://developer.apple.com/videos/play/wwdc2026/282/ (device discovery, 2D and 3D sessions, Quick Look additions). + +## USDKit (27.0, all platforms) + +"The Swift API for authoring, composing, and manipulating Universal Scene Description content" (iOS, iPadOS, Mac Catalyst, macOS, tvOS, visionOS 27.0). Session 285: https://developer.apple.com/videos/play/wwdc2026/285/ (USDKit, OpenUSD updates for accessibility, Gaussian splats, compressed geometry). + +## Foveated Streaming (visionOS 26.4) + +Session-based API to connect Apple Vision Pro to local and cloud streaming endpoints; the endpoint host streams high quality content only where necessary, based on information about the approximate region where the person is looking (framework overview, read 2026-11-13). Session 286 demonstrates an OpenXR scene with NVIDIA CloudXR: https://developer.apple.com/videos/play/wwdc2026/286/. Framework page: https://developer.apple.com/documentation/foveatedstreaming. + +## SharePlay nearby + +`View.groupActivityAssociation(_:)` (visionOS 26.0, module GroupActivities, takes `GroupActivityAssociationKind?`) specifies how a view associates with the current SharePlay group activity. `SharedCoordinateSpaceProvider` (above) establishes a shared coordinate space among multiple participants. + +## TabletopKit (visionOS 2.0) + +"Create multiplayer spatial games on a virtual table surface and use FaceTime to invite players": game design, rules, rendering effects and multiplayer state sync over SharePlay (https://developer.apple.com/documentation/tabletopkit). + +## visionOS 27 overview + +Session 287 "Build next-generation experiences with visionOS 27" is the umbrella session linked from session 393: https://developer.apple.com/videos/play/wwdc2026/287/ (title read, content not summarized here). + +## Best Practices + +- ✅ Ask for the narrowest ARKit data you need and explain it in the usage description +- ✅ Keep a non-ARKit fallback (gestures, hover) for declined permission +- ✅ Read each symbol page for its platform; several 27 types are visionOS-only +- ❌ Don't promise gaze-based features: visionOS exposes no gaze position +- ❌ Don't call `run(_:)` before a Full Space is presented diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/realitykit-27.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/realitykit-27.md new file mode 100644 index 0000000..c41bbac --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/realitykit-27.md @@ -0,0 +1,54 @@ +--- +name: realitykit-27 +description: RealityKit 27 components (navigation mesh, cloth, behavior tree, animation graph, compute graph, Gaussian splat) and Reality Composer Pro 3 +when-to-use: adding pathfinding, cloth, AI behavior, skeletal animation graphs, GPU particles or Gaussian splats; authoring with Reality Composer Pro 3 +keywords: RealityKit, NavigationMeshComponent, ClothSimulationComponent, BehaviorTreeComponent, AnimationGraphComponent, ComputeGraphComponent, GaussianSplatComponent, Reality Composer Pro, ScriptGraph +priority: high +requires: realitykit.md +related: arkit-spatial.md +--- + +# RealityKit 27 and Reality Composer Pro 3 + +All symbol facts below were read on 2026-11-13 from the Apple documentation JSON (`https://developer.apple.com/tutorials/data/documentation/realitykit/.json`, same content as `https://developer.apple.com/documentation/realitykit/`). The 27 components are not visionOS-only; availability differs per symbol, so check the page before using one on another platform. + +## Overview + +RealityKit 27 adds component-based systems for pathfinding, cloth, behavior trees, animation graphs, GPU compute graphs and Gaussian splat rendering. Reality Composer Pro 3 authors most of them visually and can be extended with project plugins. + +## Components (all introduced in 27.0) + +| Component | What Apple says it does | Platforms (27.0) | +|-----------|--------------------------|------------------| +| `NavigationMeshComponent` | Provides the navigation meshes an entity uses to find paths through a scene | iOS, iPadOS, Mac Catalyst, macOS, tvOS, visionOS | +| `ClothSimulationComponent` | Marks an entity as the simulation root of a localized cloth simulation; each entity belongs to at most one cloth simulation (the closest ancestor) | iOS, iPadOS, visionOS (declaration also lists Mac Catalyst); not macOS, not tvOS | +| `BehaviorTreeComponent` | Manages which behavior tree is active for the entity | iOS, iPadOS, Mac Catalyst, macOS, tvOS, visionOS | +| `AnimationGraphComponent` | Drives skeletal animation on an entity using an animation graph | iOS, iPadOS, Mac Catalyst, macOS, tvOS, visionOS | +| `ComputeGraphComponent` | Drives a compute graph-based particle simulation on an entity | iOS, iPadOS, macOS, tvOS, visionOS | +| `GaussianSplatComponent` | Renders 3D Gaussian splat data | iOS, iPadOS, Mac Catalyst, macOS, visionOS; not tvOS | + +Add each like any RealityKit component (`entity.components.set(...)`). Configure the data they consume (navigation mesh, cloth setup, trees, graphs, splat data) in Reality Composer Pro 3 or with the types referenced on each symbol page; do not invent initializers, open the page. + +Gaussian splat guidance (https://developer.apple.com/documentation/realitykit/gaussian-splat-rendering-guidelines, read 2026-11-13): splat data can be very large and needs alpha blending, so rendering is costly and can overheat the device. Monitor the device thermal state and reduce rendering load in response: per review of the page, the system throttles to protect frame rate but does not automatically limit splat rendering on thermal state, so that is the app's job. + +## Reality Composer Pro 3 + +Sessions (WWDC26, titles read on each page 2026-11-13): + +| Session | Topic | URL | +|---------|-------|-----| +| 252 | Design no-code games with Reality Composer Pro 3: ScriptGraph visual nodes for animation, interaction, SwiftUI elements such as speech bubbles | https://developer.apple.com/videos/play/wwdc2026/252/ | +| 279 | Advances in RealityKit: interactive cloth, NavMesh pathfinding, mixed reality lighting, customizable reverb meshes, improved shadows, character rendering, Gaussian splats | https://developer.apple.com/videos/play/wwdc2026/279/ | +| 280 | Iterate faster: add content, effects, lighting and interactivity inside the editor, AI-assisted features | https://developer.apple.com/videos/play/wwdc2026/280/ | +| 281 | Extend Reality Composer Pro 3 with Xcode: project-specific plugins that edit custom components, run custom systems, build your own ScriptGraph nodes | https://developer.apple.com/videos/play/wwdc2026/281/ | +| 393 | Graph tools: Shader Graph materials, Animation Graph skeletal blending, Compute Graph particles, Script Graph interactivity | https://developer.apple.com/videos/play/wwdc2026/393/ | + +Chapters and descriptions read on the session pages: session 280 covers entities and components, prototypes and instances, live preview, lightmaps and the Reality Composer Pro Assistant; session 393 covers Animation Graph, Behavior Tree, Script Graph, Navigation Mesh, Compute Graph, Shader Graph enhancements, and coordinating scene events with Sequencer. Mapping by name: Animation Graph ↔ `AnimationGraphComponent`, Behavior Tree ↔ `BehaviorTreeComponent`, Navigation Mesh ↔ `NavigationMeshComponent`, Compute Graph ↔ `ComputeGraphComponent`. The tool-to-runtime link is inferred from names; the session pages do not state symbol names in what was read. + +## Best Practices + +- ✅ Check the symbol page for the target platform before using a 27 component outside visionOS +- ✅ Author graphs in Reality Composer Pro 3, keep runtime Swift for wiring and state +- ✅ Put custom components and systems in a project plugin so Reality Composer Pro can edit them +- ❌ Don't assume cloth or Gaussian splats exist on every RealityKit platform +- ❌ Don't write initializer calls you have not read on the symbol page diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/realitykit.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/realitykit.md index 5949372..0e020ed 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/realitykit.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/realitykit.md @@ -5,7 +5,7 @@ when-to-use: rendering 3D content, adding models, implementing spatial gestures, keywords: RealityKit, RealityView, Entity, ModelEntity, gesture, 3D, animation priority: high requires: spatial-computing.md -related: ornaments.md +related: ornaments.md, realitykit-27.md --- # RealityKit for visionOS @@ -47,21 +47,27 @@ Visible 3D content with mesh and materials. - Add physics ### Gestures -Spatial interaction with entities. +Spatial interaction with entities. Two paths: -**Supported:** +**SwiftUI gestures targeted to entities** (view level): - `TapGesture` - Point and tap - `DragGesture` - Move in space - `RotateGesture3D` - Rotate object - `MagnifyGesture` - Scale object +**Entity-level components** (preferred for object handling): +- `ManipulationComponent` (visionOS 26.0 only) - system hand/trackpad manipulation: single-hand translate, hand rotation changes orientation, two-hand scale and rotate, hand handoff, system audio cues. The system edits the entity's transform directly; put your own transforms on a subentity or react to events. +- `GestureComponent` (iOS/iPadOS/macOS/tvOS/visionOS 26.0) - attaches a UI gesture to an entity. + +Source: https://developer.apple.com/documentation/realitykit/manipulationcomponent and .../gesturecomponent (JSON read 2026-11-13). + ### Animations Entity movement and changes. **Methods:** -- `Entity.move(to:relativeTo:duration:)` -- Transform animations -- Component-based animation +- `Entity.animate(_:body:completion:)` - static, SwiftUI-style: `static func animate(_ animation: Animation, body: () -> Void, completion: (() -> Void)?)` (`@MainActor`, iOS/iPadOS/macOS/tvOS/visionOS 26.0+; source: https://developer.apple.com/documentation/realitykit/entity/animate(_:body:completion:), read 2026-11-13). Mutate entity properties inside `body` and they animate with the SwiftUI `Animation`. +- `Entity.move(to:relativeTo:duration:)` - older explicit transform animation, still available +- Component-based animation; skeletal graphs use `AnimationGraphComponent` (27, see [realitykit-27.md](realitykit-27.md)) --- @@ -97,6 +103,27 @@ RealityView { content in --- +## Manipulation and Animation Snippets + +`ManipulationComponent.configureEntity(_:hoverEffect:allowedInputTypes:collisionShapes:)` is a static method that applies a default configuration so an entity works with the component (https://developer.apple.com/documentation/realitykit/manipulationcomponent/configureentity(_:hovereffect:allowedinputtypes:collisionshapes:), read 2026-11-13: parameters are `Entity`, `HoverEffectComponent?`, `InputTargetComponent.InputType?`, `[ShapeResource]?`). Manipulation lifecycle events on `ManipulationEvents`: `WillBegin`, `DidHandOff`, `DidUpdateTransform`, `WillRelease`, `WillEnd`. Set `audioConfiguration` to `.none` to replace system audio with your own. + +```swift +// Animate a property change with a SwiftUI Animation (RealityKit 26.0+, main actor) +Entity.animate(.spring) { + entity.position.y += 0.2 +} completion: { + // finished +} +``` + +--- + +## RealityKit beyond visionOS + +RealityKit is not visionOS-only: the 27 components in [realitykit-27.md](realitykit-27.md) list iOS, iPadOS, macOS and tvOS availability per symbol. + +--- + ## Best Practices - ✅ Use .usdz for complex models diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/spatial-computing.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/spatial-computing.md index 5a08fc2..38a3e20 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/spatial-computing.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/spatial-computing.md @@ -92,6 +92,22 @@ await dismissSpace() --- +## Look to Scroll + +Source: HIG scroll-views > Look to Scroll (added 2026-03-24; read 2026-11-13). + +- People scroll with their eyes by looking near the scroll view boundary (top/bottom, or sides). It does **not** work by default: add it per scroll view. +- Add it in reading and browsing views; skip it in views with UI controls or dense information needing quick, precise scrolling (Notes: yes in the note, no in the note list). Support it in all similar views for consistency. +- Prefer full-width or full-height scroll views for generous space and clear edges; if inset, provide clear boundaries. Parallax or scroll-driven animations can make it behave unexpectedly. +- API (visionOS 26.0): `ScrollInputKind.look` (axes chosen automatically) and `ScrollInputKind.look(axes:)`, used with `scrollInputBehavior(_:for:)` and `ScrollInputBehavior` `.automatic/.enabled/.disabled`. + +```swift +ScrollView { ArticleBody() } + .scrollInputBehavior(.enabled, for: .look) +``` + +--- + ## Best Practices - ✅ Start with windows diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/spatial-web.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/spatial-web.md new file mode 100644 index 0000000..4685bd5 --- /dev/null +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/visionos/references/spatial-web.md @@ -0,0 +1,36 @@ +--- +name: spatial-web +description: HTML model element and the Immersive JavaScript API for websites on visionOS (and the model element on iOS, iPadOS, macOS) +when-to-use: bringing interactive 3D to web pages, launching an immersive website environment on Vision Pro, designing environments shared by apps and websites +keywords: HTML model element, USDZ, Immersive API, JavaScript, immersive website environment, spatial web, WebKit +priority: medium +requires: spatial-computing.md +related: arkit-spatial.md, realitykit-27.md +--- + +# Spatial web on Apple platforms + +Scope note: this reference summarizes three WWDC26 sessions (titles and descriptions read on 2026-11-13). The sessions are the source for element attributes and JavaScript signatures; no web API names are listed here because they were not read from a primary reference page. Open the session before writing markup or script. + +## Overview + +| Session | Topic | URL | +|---------|-------|-----| +| 215 | Get started with the HTML Model Element: interactive 3D on websites, now on iOS, iPadOS, macOS and visionOS; preparing the USDZ model, tools to create and optimize 3D assets, model element features, web standards direction | https://developer.apple.com/videos/play/wwdc2026/215/ | +| 320 | Explore immersive website environments in visionOS: new Immersive API in JavaScript, request immersive transitions from an inline model element, video docking, performance for real-world-scale experiences | https://developer.apple.com/videos/play/wwdc2026/320/ | +| 234 | Design immersive environments for visionOS apps and the spatial web: photoreal environments for apps, websites and SharePlay, design principles, reference capture, high-fidelity CG assets, real-time effects such as motion and lighting | https://developer.apple.com/videos/play/wwdc2026/234/ | +| 285 | Discover USDKit and what's new in OpenUSD: mentions enhanced spatial web capabilities alongside the spatial preview API | https://developer.apple.com/videos/play/wwdc2026/285/ | + +## Key Concepts + +- The model element renders a USDZ model inline in a web page; on visionOS an inline model can request an immersive transition (session 320). +- The Immersive JavaScript API lets a website present a virtual environment in Apple Vision Pro, with video docking. +- Environments designed for the web can be reused for apps and SharePlay (session 234), so design them once at real-world scale. +- Prepare assets as USDZ and optimize them (session 215); USDKit ([arkit-spatial.md](arkit-spatial.md)) authors and edits USD from Swift. + +## Best Practices + +- ✅ Treat the model element as progressive enhancement: the page must work without 3D +- ✅ Optimize USDZ size and polygon count before shipping +- ✅ Check each session for exact attributes and API names before coding +- ❌ Don't copy web API names from memory or from this summary diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/watchos/SKILL.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/watchos/SKILL.md index 71f2c77..863f22b 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/watchos/SKILL.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/watchos/SKILL.md @@ -58,8 +58,25 @@ After implementation, run **fuse-ai-pilot:sniper** for validation. | Need | Reference | |------|-----------| | Watch face complications | [complications.md](references/complications.md) | -| Workout sessions, HealthKit | [workouts.md](references/workouts.md) | +| Workout sessions, workout zones (27), HealthKit | [workouts.md](references/workouts.md) | | iPhone ↔ Watch sync | [watch-connectivity.md](references/watch-connectivity.md) | +| Smart Stack widget sizes, accessory widgets, Live Activities on Watch | [hig-system-surfaces.md](../swiftui-core/references/hig-system-surfaces.md) | + +--- + +## Vision on watchOS (27) + +The Vision framework supports watchOS 27: `DetectLensSmudgeRequest` is introduced on watchOS 27.0 (iOS, iPadOS, macOS, tvOS, visionOS 26.0) and returns a `SmudgeObservation` with a `confidence` from 0.0 to 1.0 (https://developer.apple.com/documentation/vision/detectlenssmudgerequest, read 2026-11-13). Session 237 "What's new in image understanding" covers Vision on watchOS and the new tap-to-segment request: https://developer.apple.com/videos/play/wwdc2026/237/. HealthKit on iOS is covered by the `apple-frameworks` skill; workouts on the watch stay in [workouts.md](references/workouts.md). + +--- + +## Liquid Glass on watchOS + +API table and rules live in [liquid-glass.md](../swiftui-core/references/liquid-glass.md) (`glassEffect(_:in:)` is available on watchOS 26.0); do not duplicate them here. watchOS specifics (HIG, read 2026-11-13): + +- Standard components adopt the system look automatically; the HIG materials page lists watchOS as a supported platform ([HIG materials](https://developer.apple.com/design/human-interface-guidelines/materials)). Full-screen modal views are common on Apple Watch: keep the material backgrounds the system gives modal sheets instead of removing or replacing them. +- Toolbars ([HIG toolbars](https://developer.apple.com/design/human-interface-guidelines/toolbars), 2025-12-16): toolbar buttons go in the top corners or along the bottom (`ToolbarItemPlacement.topBarLeading`, `.topBarTrailing`, `.bottomBar`, all watchOS 10.0); above scrolling content they stay visible, and a button placed inside the scroll view stays hidden until the person scrolls up. Use for essential functionality closely related to the view. +- Scroll edge effects ([HIG scroll-views](https://developer.apple.com/design/human-interface-guidelines/scroll-views)): `scrollEdgeEffectStyle(_:for:)` is available on watchOS 26.0; keep `.automatic`. --- diff --git a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/watchos/references/workouts.md b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/watchos/references/workouts.md index 9dd7653..6b7af7e 100644 --- a/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/watchos/references/workouts.md +++ b/.cursor-plugin/plugins/fuse-swift-apple-expert/skills/watchos/references/workouts.md @@ -19,24 +19,64 @@ related: complications.md, watch-connectivity.md ## Key Concepts +### Where these classes run (not watch-only) + +| Class | iOS/iPadOS | watchOS | Other | +|-------|------------|---------|-------| +| `HKWorkoutSession` | 17.0+ | 2.0+ | visionOS 1.0, macOS | +| `HKLiveWorkoutBuilder` | 26.0+ | 5.0+ | macOS | + +Source: Apple documentation JSON pages read 2026-11-13 (https://developer.apple.com/documentation/healthkit/hkworkoutsession, .../hkliveworkoutbuilder). Apple's article "Running workout sessions" (https://developer.apple.com/documentation/healthkit/running-workout-sessions) is framed around Apple Watch: while a session runs, the system tunes the watch sensors for the activity, and every session generates high-frequency heart rate samples. A live builder on iOS (26.0+) is documented as a symbol; this skill covers the watchOS flow. For HealthKit on iOS (authorization, queries, medications), see the `apple-frameworks` skill instead of duplicating it here. + ### HKWorkoutSession Manages active workout state. **Key Points:** -- Request authorization first -- Configure workout type +- Request authorization first (share `HKQuantityType.workoutType()`, read the quantity types you display) +- Configure workout type with `HKWorkoutConfiguration` (`activityType`, `locationType`) - Start/pause/resume/end -- Runs in background +- Active session lets the app run in the background: add the Workout processing background mode to the watchOS app, plus the Audio background mode if it plays audio or provides haptics during the workout +- Background audio clips (coaching, notifications) are valid only while a workout session is running (Apple article, read 2026-11-13) ### HKLiveWorkoutBuilder Collects data during workout. **Key Points:** -- Attached to session +- Obtained from the session: `session.associatedWorkoutBuilder()` - Auto-collects metrics - Saves to HealthKit - Provides data stream +```swift +// From Apple's "Running workout sessions" +let configuration = HKWorkoutConfiguration() +configuration.activityType = .running +configuration.locationType = .outdoor + +do { + session = try HKWorkoutSession(healthStore: healthStore, configuration: configuration) + builder = session.associatedWorkoutBuilder() +} catch { + // Handle failure here. + return +} +``` + +### Workout zones (27.0) + +Workout zones divide measurements like heart rate and cycling power into ranges that represent training intensities. People configure zones in Health Settings: system-generated from their health metrics, or manually defined ranges. HealthKit calculates time in zone during workouts. Source: https://developer.apple.com/documentation/healthkit/accessing-workout-zone-data (read 2026-11-13). + +| Symbol | Role | Available | +|--------|------|-----------| +| `HKWorkoutZoneConfiguration` | Complete set of zones for a quantity type: an ordered array of zones plus the configuration `source`; apps can supply custom zones for specific workouts | iOS, iPadOS, Mac Catalyst, macOS, visionOS, watchOS 27.0 | +| `HKWorkoutZoneGroup` | Zone configuration plus time-in-zone data (`HKWorkoutZoneDuration` array) for a quantity type | same, 27.0 | +| `HKLiveWorkoutZoneUpdate` | Information about zone transitions during a live workout session | iOS, iPadOS, Mac Catalyst, watchOS 27.0 (macOS listed, no version) | +| `HKHealthStore.preferredWorkoutZoneConfiguration(for:)` | `func preferredWorkoutZoneConfiguration(for: HKQuantityType) async throws -> HKWorkoutZoneConfiguration?` | iOS, iPadOS, Mac Catalyst, macOS, visionOS, watchOS 27.0 (per review of the page) | + +- Zone groups are available from `HKWorkout` and `HKWorkoutActivity` for completed workouts and from `HKWorkoutBuilder` for real-time zone data during an active workout. +- Reading zone data needs permission: call `HKHealthStore.requestAuthorization(toShare:read:)` first. +- Zones are not on tvOS (no tvOS entry on these pages). + ### Workout Types | Type | Activity | diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b8162d..d6ca3ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,27 @@ # Changelog +## [0.1.14] - 14-11-2026 + +- docs(swift-apple-expert): Apple OS 27 skills ported from claude-plugins + v1.40.0 (iOS/iPadOS/macOS/watchOS/visionOS/tvOS 27.2, Xcode 27.2, + Swift 6.4.2) — 4 new skills `apple-intelligence`, `apple-frameworks`, + `graphics-games`, `media-vision`; 10 skills updated (`build-distribution`, + `ios`, `ipados`, `macos`, `mcp-tools`, `swift-core`, `swiftui-core`, `tvos`, + `visionos`, `watchos`) and the `swift-expert` agent updated +- docs(design): `design-ios` skill updated to Apple OS 27.2, new references + `app-icons`, `app-store-assets`, `apple-design-tools`, `bars-menus-scroll`, + `generative-ai`, `system-surfaces` +- docs(cursor): Cursor adaptations of the port — `Agent` → `Task`, `mcp.json` + in `type: stdio` form, `xcode-agents.md` adapted +- docs(readme): fuse-swift-apple-expert and fuse-design READMEs updated; + fuse-swift-apple-expert marketplace description updated to Swift 6.4.2 / + Xcode 27.2 / OS 27.2 +- chore(plugins): PATCH bump, mirrored in `.cursor-plugin/marketplace.json` — + fuse-design 2.2.14, fuse-swift-apple-expert 1.1.25 +- chore(marketplace): suite `metadata.version` 0.1.13 → 0.1.14, README version badge updated +- Not verified: real Cursor run — cursor-agent Free quota exhausted + ('You've hit your usage limit') + ## [0.1.13] - 11-11-2026 - chore(harness): shared harness minimum raised to `@fusengine/harness` diff --git a/README.md b/README.md index 06c6c3e..163a390 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Fusengine Cursor Plugins -![version](https://img.shields.io/badge/version-0.1.13-blue?style=flat-square) +![version](https://img.shields.io/badge/version-0.1.14-blue?style=flat-square) ![plugins](https://img.shields.io/badge/plugins-26-brightgreen?style=flat-square) ![runtime](https://img.shields.io/badge/runtime-Cursor%20CLI-black?style=flat-square) ![License: MIT](https://img.shields.io/badge/License-MIT-yellow?style=flat-square) diff --git a/docs/decisions.md b/docs/decisions.md index 6919fc5..c5067e1 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -8,3 +8,4 @@ Owner decisions for this repository, dated. Agents execute recorded decisions; a - **2026-11-11 — Harness minimum 0.1.116.** Owner: « fais corrigé ». `HARNESS_MIN` is 0.1.116 in every `hook.sh`, so installs at 0.1.115 upgrade at the next session start (0.1.116 fixes the false shell-redirect CONFIRM on `( … 2>&1) || true`). - **2026-11-10 — Releases.** Release only on the owner's go typed in this repository's lead session; a relayed message is never a release go. - **2026-11-11 — Release 0.1.13.** Owner, typed in this session: « Oui, release 0.1.13 ». +- **2026-11-14 — Release 0.1.14.** Owner, typed in this session: « Oui, release 0.1.14 » (PR #18, Apple OS 27 skills port; real Cursor run not executed — Free quota exhausted).