Why does my SwiftUI app crash when opened from an intent?

I'm encountering a crash in my SwiftUI app when it is opened via an AppIntent. The app runs perfectly when launched by tapping the app icon, but it crashes when opened from an intent.

Here is a simplified version of my code:

import AppIntents
import SwiftData
import SwiftUI

@main
struct GOGODemoApp: App {
  @State
  private var state: MyController = MyController()
  var body: some Scene {
    WindowGroup {
      MyView()
        //.environment(state) // ok
    }
    .environment(state) // failed to start app, crash with 'Dispatch queue: com.apple.main-thread'
  }
}

struct MyView: View {
  @Environment(MyController.self) var stateController
  var body: some View {
    Text("Hello")
  }
}

@Observable
public class MyController {
}

struct OpenIntents: AppIntent {
  static var title: LocalizedStringResource = "OpenIntents"
  static var description = IntentDescription("Open App from intents.")
  static var openAppWhenRun: Bool = true

  @MainActor
  func perform() async throws -> some IntentResult {
    return .result()
  }
}

Observations:

  • The app works fine when launched by tapping the app icon.
  • The app crashes when opened via an AppIntent.
  • The app works if I inject the environment in MyView instead of in WindowGroup.

Question: Why does injecting the environment in WindowGroup cause the app to crash when opened from an intent, but works fine otherwise? What is the difference when injecting the environment directly in MyView?

Why does my SwiftUI app crash when opened from an intent?
 
 
Q