# Magic Devtools documentation > Magic Devtools adds Magic-aware context to tapir snapshots and crumbs records, so an LLM agent or a CI driver sees your app the way Magic does. # Installation Add `magic_devtools` to a Magic app and wire tapir and crumbs into it in the two phases around `Magic.init()`, so debug and profile builds carry the tools and release builds drop them. - [Install](#install) - [Requirements](#requirements) - [The Two-Phase Install](#the-two-phase-install) - [Wiring One Tool](#wiring-one-tool) - [What the Installers Write](#what-the-installers-write) - [Release Builds](#release-builds) - [Related Documentation](#related-documentation) ## Install From an app that already runs Magic, one command adds the three packages and wires `lib/main.dart`: ```bash dart run magic:dowel magic:install --with-devtools ``` To do it by hand, add the packages as regular dependencies and call the two halves of `MagicDevtools` in `lib/main.dart`: ```yaml dependencies: magic_devtools: ^1.0.0 tapir: ^1.0.0 crumbs: ^1.0.0 ``` ```dart import 'package:flutter/foundation.dart' show kReleaseMode; import 'package:flutter/widgets.dart'; import 'package:magic/magic.dart'; import 'package:magic_devtools/magic_devtools.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kReleaseMode) MagicDevtools.installPre(); await Magic.init(); // pass your configFactories and providers here if (!kReleaseMode) MagicDevtools.installPost(); runApp(MagicApplication()); } ``` `lib/main.dart` imports these packages, so they belong under `dependencies`: a `dev_dependencies` entry would trip the `depend_on_referenced_packages` lint. The `!kReleaseMode` guard, not the dependency section, is what keeps them out of a release build. ## Requirements | Requirement | Value | |:------------|:------| | Dart | `>=3.13.0` | | Flutter | `>=3.47.0` | | `magic` | `^1.0.0` | | `tapir`, `crumbs` | `^1.0.0`, resolved through `magic_devtools` | | Also pulled in | `magic_socket`, `wind_kit`, `material_ui` | `magic` core depends on neither tapir nor crumbs; this package is the only place they meet a Magic app. ## The Two-Phase Install | Call | When | What it wires | |:-----|:-----|:--------------| | `MagicDevtools.installPre()` | Before `Magic.init()` | `TapirPlugin.install()`, `CrumbsPlugin.install()` (which adds crumbs' `LogWatcher` itself), one `ExceptionWatcher` and one `DumpWatcher`, and `MagicPerfIntegration.install()` | | `MagicDevtools.installPost()` | After `Magic.init()` | `MagicCrumbsIntegration.install()`, then `MagicTapirIntegration.install()` | The order is fixed by what each half touches: - The pre half has to observe Magic booting: the snapshot pipeline and the exception watcher are live before the first provider runs, so a boot error lands in crumbs. `MagicPerfIntegration` adds a navigator observer through `MagicRouter.addObserver`, which throws a `StateError` once `routerConfig` has been read, so it cannot run later. - The post half resolves Magic's container: the HTTP adapter looks up the `network` binding and the enrichers read controllers, the router, `Gate`, `Auth` and the `broadcasting` binding. Both halves are idempotent: a second call in the same isolate registers nothing twice. `installPre()` keeps the watcher pair it registered, so a second call does not chain a second `ExceptionWatcher` or `DumpWatcher` onto the first. ## Wiring One Tool Import a narrow barrel when the app uses one tool, or wants a different crumbs watcher set. The rule stays the same: the plugin before `Magic.init()`, the Magic integration after it. | Barrel | Exports | |:-------|:--------| | `package:magic_devtools/magic_devtools.dart` | `MagicDevtools`, `MagicPerfIntegration`, `PerfInsightRules`, `PerfRuleInputs` | | `package:magic_devtools/tapir.dart` | `MagicTapirIntegration` and its 14 enricher functions | | `package:magic_devtools/crumbs.dart` | `MagicCrumbsIntegration`, `MagicHttpFacadeAdapter` and the five watchers | | `package:magic_devtools/preview.dart` | `MagicPreview`, `PreviewEntry`, `MagicPreviewCatalog`, `kPreviewEnabled` | ```dart import 'package:crumbs/crumbs.dart'; import 'package:flutter/foundation.dart' show kReleaseMode; import 'package:flutter/widgets.dart'; import 'package:magic/magic.dart'; import 'package:magic_devtools/crumbs.dart'; import 'package:magic_devtools/tapir.dart'; import 'package:tapir/tapir.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kReleaseMode) { TapirPlugin.install(); CrumbsPlugin.install(); CrumbsPlugin.registerWatcher(ExceptionWatcher()); CrumbsPlugin.registerWatcher(DumpWatcher()); } await Magic.init(); if (!kReleaseMode) { MagicCrumbsIntegration.install(); MagicTapirIntegration.install(); } runApp(MagicApplication()); } ``` This wiring leaves out `MagicPerfIntegration`, so tapir's perf reports come back with zero counters. Add `MagicPerfIntegration.install()` to the first block, or use `MagicDevtools`, when you measure performance. Do not mix the two styles: `MagicDevtools.installPre()` after a hand-written `ExceptionWatcher` registration adds a second one. ## What the Installers Write | Command | Writes into `lib/main.dart` | |:--------|:----------------------------| | `dart run magic:dowel magic:install --with-devtools` | The tapir, crumbs (with `ExceptionWatcher` and `DumpWatcher`) and `MagicPerfIntegration.install()` blocks before `await Magic.init(`, the `MagicCrumbsIntegration` and `MagicTapirIntegration` blocks after it, all under `!kReleaseMode`; adds `magic_devtools`, `tapir` and `crumbs` at `^1.0.0` to `dependencies` | | `dart run tapir tapir:install` | A `TapirPlugin.install()` block under `!kReleaseMode`, and `MagicTapirIntegration.install()` after `await Magic.init(` when the pubspec lists `magic_devtools` and `flutter pub get` has resolved it | | `dart run crumbs crumbs:install` | A `CrumbsPlugin.install()` block with `ExceptionWatcher` and `DumpWatcher` under `!kReleaseMode`, and `MagicCrumbsIntegration.install()` after `await Magic.init(` when the pubspec lists `magic_devtools` and `flutter pub get` has resolved it | Every installer decides by call presence, so a re-run writes nothing twice. `magic:install` leaves a file that already calls `MagicDevtools.installPre(` untouched. Neither `tapir:install` nor `crumbs:install` writes `MagicDevtools` or `MagicPerfIntegration`. ## Release Builds `kReleaseMode` is a compile-time constant, so a release build drops every `if (!kReleaseMode)` branch and, with it, the tapir, crumbs and `magic_devtools` code those branches reach. Nothing in this package checks the build mode on its own: `installPre()`, `installPost()` and every `install()` do their work wherever they are called, so the guard belongs at the call site. The one exception is the preview catalog, whose `MagicPreview.registerRoutes()` returns early in release by itself. A profile build keeps the tools, which is what a performance measurement needs. ## Related Documentation - [Tapir Integration](https://anilcancakir.com/magic/docs/devtools/basics/tapir-integration.md): the 14 snapshot enrichers and the navigate adapter. - [Crumbs Integration](https://anilcancakir.com/magic/docs/devtools/basics/crumbs-integration.md): the HTTP adapter, the five watchers and credential masking. - [Performance](https://anilcancakir.com/magic/docs/devtools/basics/performance.md): the perf data path and the insight rules. - [Preview Catalog](https://anilcancakir.com/magic/docs/devtools/basics/preview-catalog.md): the dev-only `/preview` pages. - [Testing](https://anilcancakir.com/magic/docs/devtools/guides/testing.md): resetting the integrations between tests. --- # Tapir Integration `MagicTapirIntegration` adds 14 Magic-aware enrichers to tapir's snapshot pipeline and a navigate adapter that drives `MagicRouter`, so an agent reading a snapshot sees forms, routes, controllers, gates, auth, broadcasting and recent crumbs records next to each element. - [Basic Usage](#basic-usage) - [Quick Reference](#quick-reference) - [Reading the Enrichers](#reading-the-enrichers) - [Recent Crumbs Records](#recent-crumbs-records) - [The Navigate Adapter](#the-navigate-adapter) - [Install Behaviour](#install-behaviour) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage ```dart import 'package:flutter/foundation.dart' show kReleaseMode; import 'package:flutter/widgets.dart'; import 'package:magic/magic.dart'; import 'package:magic_devtools/tapir.dart'; import 'package:tapir/tapir.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kReleaseMode) TapirPlugin.install(); await Magic.init(); if (!kReleaseMode) MagicTapirIntegration.install(); runApp(MagicApplication()); } ``` `MagicDevtools.installPost()` makes the same `MagicTapirIntegration.install()` call. Enricher lines appear only in a snapshot that asks for them: ```bash dart run tapir tapir:snap --includeEnrichers ``` ## Quick Reference The enrichers run in this order for every element tapir emits, and each returns nothing when it has nothing to say. | Slot | Function | Line it adds | |:-----|:---------|:-------------| | 0 | `magicFormEnricher` | `magicFormField: ` | | 1 | `magicNavigationEnricher` | `magicRoute: ` | | 2 | `magicControllerEnricher` | `magicControllerState: .` | | 3 | `magicFormErrorsEnricher` | `magicFormErrors: ="",...` | | 4 | `magicGateResultEnricher` | `magicGateResult: .` | | 5 | `magicMiddlewareEnricher` | `magicMiddleware: ,` | | 6 | `magicAuthUserEnricher` | `magicAuthUser: ` or `magicAuthUser: :` | | 7 | `magicControllerFlagsEnricher` | `magicControllerFlags: .isLoading=,isSuccess=,isError=,isEmpty=` | | 8 | `magicRouteParamsEnricher` | `magicRouteParams: =,...` | | 9 | `magicEchoConnectionEnricher` | `magicEchoConnection: ` | | 10 | `magicGateResultsAllEnricher` | `magicGateResultsAll: =,...` | | 11 | `magicRecentHttpEnricher` | `magicRecentHttp: ms,...` | | 12 | `magicRecentLogsEnricher` | `magicRecentLogs: [] ,...` | | 13 | `magicRecentExceptionsEnricher` | `magicRecentExceptions: at :,...` | Every enricher is synchronous, has tapir's `TapirSnapshotEnricher` signature (`String? Function(Element, RefRegistry)`), and keeps no reference to the element between calls. ## Reading the Enrichers | Key | Source and rules | |:----|:-----------------| | `magicFormField` | The element, or a descendant, is an `EditableText` whose controller is a text controller of the `MagicFormData` on the nearest `MagicForm` ancestor. The value is that field's name. | | `magicRoute` | `MagicRouter.instance.currentLocation`; absent while it is null or empty. | | `magicControllerState` | The first controller in `Magic.controllers` that has an `rxStatus` (a `MagicStateMixin` controller); the status is the enum name, such as `loading` or `success`. | | `magicControllerFlags` | The first such controller's `isLoading`, `isSuccess`, `isError` and `isEmpty`, always in that order. | | `magicFormErrors` | `validationErrors` of the controller behind the nearest `MagicForm`, when that controller uses `ValidatesRequests`. Only the form's own fields are listed when it has `MagicFormData`; each message is quoted and cut to 80 characters (77 plus `...`). | | `magicGateResult` | `Gate.manager.mostRecentResult`, the last ability any `Gate` check decided. | | `magicGateResultsAll` | The cached result of every defined ability that has one, newest first, at most 5. It reads the cache only and never runs an ability. | | `magicMiddleware` | The middlewares of `MagicRouter.instance.currentRoute`: a string alias as written, a `MagicMiddleware` by its `toString()`. | | `magicAuthUser` | `Auth.user()`: the `id` attribute, plus `:` when that attribute is a non-empty string. Absent for a guest, and absent when the container has no `auth` binding (no `AuthServiceProvider`). | | `magicRouteParams` | `MagicRouter.instance.pathParameters` first, then `queryParameters`; absent when both are empty. | | `magicEchoConnection` | Absent unless the container has a `broadcasting` binding. The last state the Echo connection stream emitted (`connecting`, `connected`, `reconnecting` or `disconnected`), or, before the first event, `connected` or `disconnected` from `isConnected`. | The route, controller, gate, auth and Echo values do not depend on the element, so they repeat under every element of one snapshot. The `wind:` block of a snapshot is not one of these: tapir reads it through `wind_kit_diagnostics_contracts` from the resolver `Wind.installDebugResolver()` registers, and this package does not install that resolver. ## Recent Crumbs Records Three enrichers read `CrumbsStore` directly, so a snapshot carries the latest network, log and exception context without a second call. | Key | Records | Limits | |:----|:--------|:-------| | `magicRecentHttp` | `CrumbsStore.recentHttp(limit: 5)` | URLs longer than 40 characters keep 37 plus `...` | | `magicRecentLogs` | `CrumbsStore.recentLogs(limit: 3, minLevel: 'WARNING')` | `WARNING` prints as `WARN`, `SEVERE` as `ERROR`; messages longer than 50 characters keep 47 plus `...` | | `magicRecentExceptions` | `CrumbsStore.recentExceptions(limit: 3)` | ` at :` from the first stack line, or the type alone when no location parses | Each read is wrapped so a failure yields no line instead of an error. With crumbs installed but nothing recorded yet, the three keys are simply absent. ## The Navigate Adapter `install()` registers a navigate adapter with `TapirPlugin.registerNavigateAdapter`, so `tapir:navigate --route /path` calls `MagicRouter.instance.to(route)`. The route is a URL path, not a route name. When the router throws a `StateError`, the adapter answers `false` and tapir falls back to its own path (a `Navigator` push, then the platform route broadcast). ## Install Behaviour - Idempotent: a second `install()` in the same isolate returns at once and adds nothing. - The enrichers are appended to `TapirPlugin.enrichers` in the slot order above, after whatever the app added before. - tapir writes every line every enricher returns and removes no duplicates, so an app enricher that emits one of these keys produces two lines under the same element. - The Echo connection stream is subscribed during `install()` only when `broadcasting` is bound at that moment. ## Gotchas | Mistake | Fix | |:--------|:----| | Calling `tapir:snap` and finding no `magic*` lines. | Enrichers are off by default; pass `--includeEnrichers`. | | Reading `tapir:observe` output and finding only `magicFormField`, `magicRoute` and `magicGateResult`. | That is observe's default subset; pass `--includeEnrichers=full` for every key. | | Installing before the broadcasting provider has registered, then expecting `reconnecting`. | Without the stream subscription the enricher can only answer `connected` or `disconnected`; install after `Magic.init()`. | | Expecting a readable name from a middleware object and getting `Instance of 'AuthMiddleware'`. | `MagicMiddleware` is printed with `toString()`; override it, or register the middleware under a string alias. | | Expecting `magicAuthUser` to show a name. | Only the `display_name` attribute is read; the line falls back to the `id` alone. | | Adding a custom enricher that reuses a `magic*` key. | Keep keys distinct; tapir prints both lines. | ## Related Documentation - [Installation](https://anilcancakir.com/magic/docs/devtools/getting-started/installation.md): the two-phase install. - [Crumbs Integration](https://anilcancakir.com/magic/docs/devtools/basics/crumbs-integration.md): where the recent HTTP, log and exception records come from. - [Testing](https://anilcancakir.com/magic/docs/devtools/guides/testing.md): removing the enrichers between tests. --- # Crumbs Integration `MagicCrumbsIntegration` feeds Magic's HTTP traffic, model, cache, event, gate and query activity into crumbs' buffers, masks the auth header Magic sends, and points tapir's network-idle, console and exceptions readers at crumbs. - [Basic Usage](#basic-usage) - [Quick Reference](#quick-reference) - [HTTP Capture](#http-capture) - [Credential Masking](#credential-masking) - [The Watchers](#the-watchers) - [The Tapir Bridge](#the-tapir-bridge) - [Release and Disabled Builds](#release-and-disabled-builds) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage ```dart import 'package:crumbs/crumbs.dart'; import 'package:flutter/foundation.dart' show kReleaseMode; import 'package:flutter/widgets.dart'; import 'package:magic/magic.dart'; import 'package:magic_devtools/crumbs.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kReleaseMode) { CrumbsPlugin.install(); CrumbsPlugin.registerWatcher(ExceptionWatcher()); // boot errors CrumbsPlugin.registerWatcher(DumpWatcher()); // debugPrint } await Magic.init(); if (!kReleaseMode) MagicCrumbsIntegration.install(); runApp(MagicApplication()); } ``` `MagicDevtools.installPre()` and `installPost()` make the same calls. `MagicCrumbsIntegration.install()` has to follow `Magic.init()`: the HTTP adapter looks the `network` driver up in the container. ## Quick Reference | Unit | `name` | Listens to | Record | Read it with | |:-----|:-------|:-----------|:-------|:-------------| | `MagicHttpFacadeAdapter` | `magic_http_facade` | An interceptor on the `network` driver | `HttpRequestRecord` | `crumbs:requests` | | `MagicModelWatcher` | `magic_model` | `ModelCreated`, `ModelSaved`, `ModelDeleted` | `ModelRecord` | `CrumbsStore.recentModels()` | | `MagicCacheWatcher` | `magic_cache` | `CacheHit`, `CacheMiss`, `CachePut`, `CacheForget`, `CacheFlush` | `CacheRecord` | `crumbs:caches` | | `MagicEventWatcher` | `magic_event` | `AuthLogin`, `AuthLogout`, `AuthFailed`, `AuthRestored`, `DatabaseConnected`, `GateAbilityDefined`, `GateBeforeRegistered` | `EventRecord` | `crumbs:events` | | `MagicGateWatcher` | `magic_gate` | `GateAccessChecked` | `GateRecord` | `crumbs:gates` | | `MagicQueryWatcher` | `magic_query` | `QueryExecuted` | `QueryRecord` | `crumbs:queries` | `install()` is idempotent: a second call registers nothing twice. It does re-add the auth header to the masked list on every call (see [Credential Masking](#credential-masking)). ## HTTP Capture The adapter adds one interceptor to the driver `Magic.make('network')` returns. Each answer becomes one `HttpRequestRecord`: | Field | Value | |:------|:------| | `url`, `method`, `requestHeaders` | From the request; header values are stringified | | `statusCode`, `isError` | From the response (`isError` is its `failed` flag); an error is always `isError: true` | | `requestBody`, `responseBody` | Masked (below), then cut at 8192 characters with a `... [truncated N chars]` suffix; an error with a `message` stores the message as `responseBody` | | `durationMs`, `startUs`, `endUs` | Timed on `FlutterTimeline.now` from request to answer | | `requestId` | The id Magic's driver stamps on the request | | `attributedHeuristically` | `true` only for an answer without an id, which is paired with the oldest id-less request in flight | | `interactionId`, `linkedBy` | The tapir interaction the request was sent from (see [Performance](https://anilcancakir.com/magic/docs/devtools/basics/performance.md#interaction-links)) | Requests and answers are paired by that id, so two requests that finish out of order keep their own URL and duration. An answer whose request went out before `install()` is dropped. `MagicHttpFacadeAdapter.pendingCount` is the number of requests in flight, which `CrumbsStore.pendingHttpCount` sums. ## Credential Masking Every masked value reads `********` (`CrumbsRedaction.mask`). | What | Masked by | |:-----|:----------| | The header `auth.token.header` names (default `Authorization`) | `install()` passes it to `CrumbsRedaction.hideRequestHeaders`, so a renamed bearer header is hidden too | | `authorization`, `proxy-authorization`, `cookie`, `set-cookie`, `x-api-key` headers | crumbs' own defaults | | Request body keys such as `password`, `token`, `access_token`, `secret`, `api_key` | `CrumbsRedaction.hiddenRequestParameters`, applied by the adapter before the body is stringified | | Response body keys: the request list plus `plain_text_token`, `recovery_codes`, `qr_url`, `qr_svg` | `CrumbsRedaction.hiddenResponseParameters` | The adapter masks a structured body (a `Map` or `List`) itself, because crumbs only parses JSON and form-encoded text, and `toString()` of a Dart map is neither. It masks a copy: the driver sends the object the interceptor saw, so masking in place would send the mask to the server. Add your own names with `CrumbsRedaction.hideRequestHeaders`, `hideRequestParameters` and `hideResponseParameters`; additions merge with the defaults. ## The Watchers | Watcher | What a record carries | |:--------|:----------------------| | `MagicModelWatcher` | `modelClass` (the runtime type), `event` (`created`, `saved` or `deleted`), `modelKey` (the `id` as a string, empty when null), a copy of `attributes` | | `MagicCacheWatcher` | `operation` (`hit`, `miss`, `put`, `forget` or `flush`), `key` (`*` for a flush), `ttl` on a put | | `MagicEventWatcher` | `eventType` (the class name) and an empty `payload` | | `MagicGateWatcher` | `ability`, `result`, `arguments` (always one element; a `Model` is stored as `toMap()`), `userId` as a string or null | | `MagicQueryWatcher` | `sql`, `bindings`, `timeMs`, `connectionName` | Every record except the gate record also carries `interactionId` and `linkedBy`. Model lifecycle and `QueryExecuted` stay out of `MagicEventWatcher`, and `GateAccessDenied` is not subscribed, so each action lands on one channel once. Each watcher guards its own `install()`, because magic's `EventDispatcher.register` is additive. `uninstall()` removes nothing: the dispatcher has no per-listener removal. ## The Tapir Bridge tapir does not depend on crumbs; it reads crumbs through three function pointers this integration assigns. | Pointer | Reads | Used by | |:--------|:------|:--------| | `pendingHttpCountReader` | `CrumbsStore.pendingHttpCount` | `tapir:wait_for_network_idle` | | `recentLogsReader` | `CrumbsStore.recentLogs`, as `level`, `message`, `time`, `logger` and `error` | `tapir:console` | | `recentExceptionsReader` | `CrumbsStore.recentExceptions`, as `type`, `message`, `time` and `stackHead` (the first three stack lines) | `tapir:exceptions` | Without this integration the three pointers keep tapir's defaults: zero in-flight requests and empty lists. ## Release and Disabled Builds The integration has no build-mode check of its own. Under the `!kReleaseMode` guard a release build never reaches it and records nothing; a debug or profile build records everything above. A build compiled with `--dart-define=CRUMBS_DISABLE=true` turns `CrumbsPlugin.registerWatcher` and `registerHttpAdapter` into no-ops, so none of the Magic units is attached. ## Gotchas | Mistake | Fix | |:--------|:----| | Calling `MagicCrumbsIntegration.install()` before `Magic.init()`. | The adapter finds no `network` binding and attaches nothing, and the install guard stops a later call from retrying; call it after `Magic.init()`. | | Expecting model attributes to be masked. | Only HTTP headers and bodies are masked by key; a `ModelRecord` copies every attribute as given, so keep secrets out of model attributes in a debug session. | | Expecting HTTP records while the test uses `Http.fake()`. | The fake driver ignores interceptors, so nothing reaches crumbs; assert on the fake instead. | | Reading `EventRecord.payload` for event details. | It is always empty; the record says which event fired and when, not its fields. | | Registering `ExceptionWatcher` by hand and also calling `MagicDevtools.installPre()`. | Each registration chains onto `FlutterError.onError`, so every exception is recorded twice; use one style. | ## Related Documentation - [Installation](https://anilcancakir.com/magic/docs/devtools/getting-started/installation.md): the two-phase install. - [Tapir Integration](https://anilcancakir.com/magic/docs/devtools/basics/tapir-integration.md): the snapshot enrichers that read these buffers. - [Performance](https://anilcancakir.com/magic/docs/devtools/basics/performance.md): how records are linked to tapir interactions. - [Testing](https://anilcancakir.com/magic/docs/devtools/guides/testing.md): resetting the integration between tests. --- # Performance `MagicPerfIntegration` is the data path behind tapir's perf sessions: it counts Magic's runtime activity and wind's build work, links crumbs records to tapir interactions, and adds the Magic and wind insight rules (`PerfInsightRules`) to the session report. - [Basic Usage](#basic-usage) - [Quick Reference](#quick-reference) - [Why It Lives Here](#why-it-lives-here) - [Session Modes](#session-modes) - [What a Session Collects](#what-a-session-collects) - [Interaction Links](#interaction-links) - [Insight Rules](#insight-rules) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage `MagicDevtools.installPre()` installs it, so an app wired with the umbrella needs nothing more. Without the umbrella, install it before `Magic.init()`: ```dart import 'package:flutter/foundation.dart' show kReleaseMode; import 'package:flutter/widgets.dart'; import 'package:magic/magic.dart'; import 'package:magic_devtools/magic_devtools.dart'; import 'package:tapir/tapir.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kReleaseMode) { TapirPlugin.install(); MagicPerfIntegration.install(); } await Magic.init(); runApp(MagicApplication()); } ``` Then drive a session from the tapir CLI against a running debug or profile build: ```bash dart run tapir tapir:perf_begin --mode=attribution # drive the screen you want to measure dart run tapir tapir:perf_end dart run tapir tapir:perf_trace --out=build/perf/trace.json ``` ## Quick Reference | Member | Type | Meaning | |:-------|:-----|:--------| | `MagicPerfIntegration.install()` | `static void` | Wires the data path. Idempotent; throws the router's `StateError` once `routerConfig` has been read. | | `MagicPerfIntegration.interactionLink({int? startUs})` | `({String? interactionId, String linkedBy})` | The tapir interaction the calling code belongs to, and how that was decided. | | `MagicPerfIntegration.controllerNotifyCounts` | `Map` | `refreshUI()` calls per controller type since the last attribution session began. | | `MagicPerfIntegration.routeTransitions` | `List>` | Named route pushes since the last session began, oldest first, at most 200. | | `PerfInsightRules.evaluate(report, inputs)` | `List>` | The insights that fired for one report; tapir calls it through `perfInsightContributors`. | | `PerfRuleInputs` | `final class` | The uncut counters and per-interaction joins the rules read beyond the report. | ## Why It Lives Here tapir may not import magic, wind or crumbs, so it declares function pointers with no-op defaults and leaves them for someone else to assign. This package is the one place where all four packages are visible, so `install()` assigns them: | tapir pointer | Assigned to | |:--------------|:------------| | `framePerfReader` | crumbs' frame records (`CrumbsStore.recentFramePerf()`) and `FramePerfWatcher.livenessCounter` | | `perfExtrasReader` | The Magic counters of the current session (below) | | `perfTimelineReader` | The session's Magic rows plus one row per crumbs HTTP, query, event, model and cache record | | `perfSessionBeginHook`, `perfSessionEndHook` | Turn counting on and off (see [Session Modes](#session-modes)) | | `perfInsightContributors` | Gains `PerfInsightRules.evaluate`, added once | `install()` also registers a crumbs `FramePerfWatcher`, calls `Wind.installPerfResolver()` and adds a navigator observer to `MagicRouter`. An unassigned pointer fails silently: the report comes back structurally complete with every counter at zero. ## Session Modes | Mode | wind counters | `MagicPerfHooks.sink` | Insights | |:-----|:--------------|:----------------------|:---------| | `attribution` (the `tapir:perf_begin` default) | On | Set to the session recorder | Evaluated | | `timing` | Off | `null` | None | The begin hook resets wind's counters, clears crumbs' frame buffer with `CrumbsStore.clearFramePerf()` (the HTTP, log and exception buffers stay), and resets the Magic counters and route transitions. The end hook switches counting off and removes the sink but keeps the totals, which `tapir:perf_end` reads. Between sessions the sink and wind's counters stay off; the navigator observer keeps recording route transitions, and the next begin hook clears them. ## What a Session Collects `perfExtrasReader` returns exactly these keys, each a map of name to count unless noted: | Key | Counts | |:----|:-------| | `controllerNotifies` | Controller notifies per controller type | | `notifyCauses` | Controller notifies per cause name | | `queryReloads` | Query reloads per model type | | `actions` | Actions run per action type | | `events` | Events dispatched per event type | | `casts` | Attribute casts per cast type (counted only, no trace row) | | `timerTicks` | Timer ticks per owner type | | `broadcasts` | Broadcast messages per event name | | `routeTransitions` | A list of `route`, `durationMicros` and `time` per named push | A route transition is timed from the navigator's push to the first post-frame callback after it. Only named routes count: a dialog or bottom sheet pushes an unnamed route and is skipped. Pops are not timed. The trace rows use the tracks `magic.notify`, `magic.repository`, `magic.query`, `magic.action`, `magic.event`, `magic.timer` and `magic.broadcast` for the sink, and `http`, `db`, `events`, `models` and `cache` for crumbs records. The session keeps at most 2000 sink rows. ## Interaction Links Every crumbs record this package writes (except gate records) and every trace row carries an `interactionId` and a `linkedBy`, decided in this order: | `linkedBy` | When | |:-----------|:-----| | `zone` | The code runs in the zone of an open tapir interaction (a gesture's callbacks and the timers, microtasks and streams they created) | | `frame` | No zone reaches it, but an interaction is active (or, for a span, an interaction's window holds the span's start) | | `window` | No interaction; `interactionId` is null and the work belongs to the session window only | A span that is reported when it ends (a query reload, an action, an event dispatch) is linked from its start time, so a reload that outlives the tap that started it still belongs to that tap. ## Insight Rules Rules run only on an `attribution` report with at least one painted frame. Each insight has `severity: 'warn'`, and its `evidence` carries `metric`, `value`, `perFrame` and the `threshold` it fired on. | Rule | Metric | Fires when | |:-----|:-------|:-----------| | Wrapper emissions | `wind.wrapperEmissions.` | A wrapper type is emitted at least `wrapperMinPerWidgetBuild` (0.5) times per W-widget build and `wrapperMinPerFrame` (20) times per frame | | MediaQuery reads | `wind.inheritedReads.mediaQuerySize` | At least `mediaQueryMinPerFrame` (10) size reads per frame | | Warm parse misses | `wind.cacheMisses` | No route was pushed, at least `parseMinMisses` (20) misses and a miss rate of at least `parseMinMissRate` (0.1) | | Notify storm | `magic.notifyCauses.` | One cause (timer ticks aside) notifies at least `notifyMinPerFrame` (2) times per frame | | Timer notifies | `magic.notifyCauses.timerTick` | Timer-driven notifies reach `timerNotifyMinPerSecond` (4) per second | | Uncached reloads | `magic.queryReloads.uncached` | One model type reloads with its own request more than `uncachedReloadsMaxPerInteraction` (1) times in one interaction | | Attribute casts | `magic.casts` | At least `castMinPerFrame` (50) casts per frame | | HTTP per interaction | `magic.httpPerInteraction` | One interaction sends more than `httpMaxPerInteraction` (4) requests, or the same request more than `httpMaxSameRequestPerInteraction` (1) time | ## Gotchas | Mistake | Fix | |:--------|:----| | Wiring only `tapir:install` and `crumbs:install`, then reading a perf report of zeros. | Neither installer writes `MagicPerfIntegration`; call `MagicDevtools.installPre()` or `MagicPerfIntegration.install()`. | | Calling `MagicPerfIntegration.install()` (or `installPre()`) after `Magic.init()`, whether in `main` or from a lazy debug toggle. | `Magic.init()` builds the router as its last step, so it throws the router's `StateError`; install it before `Magic.init()`. | | Guarding the wiring with `kDebugMode`. | A profile build then registers nothing; use `!kReleaseMode`, since a measurement belongs on a profile build. | | Expecting insights from a `timing` session. | Timing sessions count nothing; run an `attribution` session for insights and a `timing` one for comparable milliseconds. | | Expecting a dialog in `routeTransitions`. | Only named pushes are timed; give the route a name if it matters. | ## Related Documentation - [Installation](https://anilcancakir.com/magic/docs/devtools/getting-started/installation.md): where `installPre()` installs this. - [Crumbs Integration](https://anilcancakir.com/magic/docs/devtools/basics/crumbs-integration.md): the records the trace and the links read. - [Testing](https://anilcancakir.com/magic/docs/devtools/guides/testing.md): resetting the perf pointers between tests. --- # Preview Catalog `MagicPreview` hosts a dev-only component catalog at `/preview`: a sidebar of your registered previews next to the one you picked, with a light and dark toggle, generated from your `*.preview.dart` files and dropped from release builds. - [Basic Usage](#basic-usage) - [Quick Reference](#quick-reference) - [Writing a Preview](#writing-a-preview) - [Generating the Index](#generating-the-index) - [The Release Boundary](#the-release-boundary) - [Router Timing](#router-timing) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage Register the generated entries and the routes from a provider's `boot()`: ```dart import 'package:flutter/foundation.dart' show kDebugMode; import 'package:magic/magic.dart'; import 'package:magic_devtools/preview.dart'; import '_previews.g.dart'; class RouteServiceProvider extends ServiceProvider { RouteServiceProvider(super.app); @override void register() {} @override Future boot() async { // Register your app routes here first. if (kDebugMode) { MagicPreview.register(previewEntries()); MagicPreview.registerRoutes(); } } } ``` Run the app and open `/preview`. Selecting an entry in the sidebar navigates to `/preview/`. ## Quick Reference | Member | Type | Meaning | |:-------|:-----|:--------| | `PreviewEntry({label, slug, builder})` | `final class` | One catalog entry: the sidebar `label`, the URL `slug` and a `WidgetBuilder` | | `MagicPreview.register(entries)` | `static void` | Stores an unmodifiable copy of the entries, replacing any earlier set | | `MagicPreview.entries` | `List` | The registered entries, read-only | | `MagicPreview.registerRoutes()` | `static void` | Adds `/preview` (named `magic-preview.index`) and `/preview/:component` (named `magic-preview.component`) | | `MagicPreviewCatalog` | `StatefulWidget` | The catalog page; `entries`, `activeSlug` and `onSelect` | | `kPreviewEnabled` | `const bool` | `bool.fromEnvironment('PREVIEW_ENABLED', defaultValue: kDebugMode)` | The catalog builds only the selected preview, so a long list of heavy screens stays responsive. An unknown slug, or `/preview` itself, shows the first entry. The header's "Toggle theme" button calls `WindTheme.of(context).toggleTheme()`, so the whole catalog flips between light and dark. ## Writing a Preview A preview is a file ending in `.preview.dart` anywhere under the scanned directory, with exactly one public class whose name ends in `Preview` and that has a `const` constructor: ```dart import 'package:flutter/widgets.dart'; import 'package:magic/magic.dart'; class PrimaryButtonPreview extends StatelessWidget { const PrimaryButtonPreview({super.key}); @override Widget build(BuildContext context) { return WButton( onTap: () {}, className: 'px-4 py-2 rounded-md bg-primary', child: const WText('Save', className: 'text-white'), ); } } ``` The label is the class name without `Preview` (`PrimaryButton`) and the slug is its snake case (`primary_button`). ## Generating the Index ```bash dart run magic:dowel previews:refresh dart run magic:dowel previews:refresh --path=lib/resources/views ``` The command scans `--path` (default `lib`), writes `/_previews.g.dart`, and prints how many previews it found. The generated file imports `package:magic_devtools/preview.dart` and every preview file, and defines `List previewEntries()`, sorted by slug, with each builder as `(_) => const XxxPreview()`. It is a function, never a top-level const list, so a release build can drop every entry. The command stops with a `FormatException` when a file holds zero or several public `*Preview` classes, when a class name is not a PascalCase identifier, or when two previews produce the same slug. ## The Release Boundary `registerRoutes()` returns at once when `kReleaseMode` is true or `kPreviewEnabled` is false. Both are compile-time constants, so a release build folds the whole body away along with the catalog and every entry it would reach. | Build | Default | Override | |:------|:--------|:---------| | Debug | On | `--dart-define=PREVIEW_ENABLED=false` turns it off | | Profile | Off | `--dart-define=PREVIEW_ENABLED=true` turns it on | | Release | Off | None | The `kDebugMode` check around the calls in the sample keeps `previewEntries()` itself out of profile and release builds. Drop it if you want the profile override to work. ## Router Timing `MagicRouter` locks its route table the first time `routerConfig` is read, and `Magic.init()` reads it itself as its last step, once every provider has booted. A provider's `boot()` runs before that read, so it is the place to call `registerRoutes()`. A call after `Magic.init()` has returned, before `runApp` included, throws the router's `StateError` ("Cannot add routes after the router has been built") from the first `MagicRoute.page` it adds. ## Gotchas | Mistake | Fix | |:--------|:----| | Calling `registerRoutes()` after `Magic.init()`, in `main` or later. | It throws a `StateError`; call it from a provider's `boot()`. | | Calling `register()` after `registerRoutes()`. | The routes captured the entries at registration, so the catalog stays empty; call `register()` first. | | Giving a preview class a non-const constructor. | The generated builder is `const XxxPreview()` and fails to compile; add a `const` constructor. | | Declaring a helper `class FooPreview` next to the real one in the same file. | Only one public `*Preview` class per file; make the helper private or rename it. | | Wrapping the calls in `kDebugMode` and then passing `PREVIEW_ENABLED=true` to a profile build. | The `kDebugMode` check is false in profile and nothing registers; use `!kReleaseMode` at the call site instead. | ## Related Documentation - [Installation](https://anilcancakir.com/magic/docs/devtools/getting-started/installation.md): the tooling the catalog ships beside. - [Testing](https://anilcancakir.com/magic/docs/devtools/guides/testing.md): resetting the registered entries between tests. --- # Testing Test code that installs the `magic_devtools` integrations, and reset every static they leave behind so one test cannot leak enrichers, watchers or tapir pointers into the next. - [A Test That Installs](#a-test-that-installs) - [What Each Reset Clears](#what-each-reset-clears) - [Faking Interactions](#faking-interactions) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## A Test That Installs ```dart import 'package:crumbs/crumbs.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:magic/magic.dart'; import 'package:magic_devtools/crumbs.dart'; import 'package:magic_devtools/tapir.dart'; import 'package:tapir/tapir.dart'; void main() { setUpAll(TestWidgetsFlutterBinding.ensureInitialized); setUp(() { MagicApp.reset(); Magic.flush(); MagicRouter.reset(); CrumbsStore.resetForTesting(); }); tearDown(() { MagicTapirIntegration.resetForTesting(); MagicCrumbsIntegration.resetForTesting(); }); test('installs the Magic enrichers once', () { MagicTapirIntegration.install(); MagicTapirIntegration.install(); expect(TapirPlugin.enrichers, hasLength(14)); }); } ``` Every `resetForTesting()` and `isInstalled` here is `@visibleForTesting`: call them from tests only. ## What Each Reset Clears | Call | Clears | Leaves | |:-----|:-------|:-------| | `MagicDevtools.resetForTesting()` | Uninstalls the `ExceptionWatcher` and `DumpWatcher` that `installPre()` registered, which restores `FlutterError.onError`, the platform error callback and `debugPrint`; the next `installPre()` registers a new pair | The plugins and the perf integration | | `MagicTapirIntegration.resetForTesting()` | Removes the 14 enrichers from `TapirPlugin.enrichers`, clears the navigate adapter, cancels the Echo subscription, drops the install guard | Enrichers the app added itself | | `MagicCrumbsIntegration.resetForTesting()` | Drops the install guard; resets `pendingHttpCountReader`, `recentLogsReader` and `recentExceptionsReader` to zero and empty lists | The adapter and the five watchers registered with `CrumbsPlugin`, and their `EventDispatcher` listeners | | `MagicPerfIntegration.resetForTesting()` | Drops the install guard, clears the session counters and route transitions, removes `MagicPerfHooks.sink` and the insight contributor, uninstalls the frame watcher, turns wind's counting off, restores the interaction sources and puts every tapir perf pointer back to the default tapir declared | The navigator observer, which `MagicRouter.reset()` drops with the router | | `MagicPreview.resetForTesting()` | The registered entries | Routes already added; `MagicRouter.reset()` clears those | Pair them with the resets of the packages underneath: | Call | Why | |:-----|:----| | `CrumbsStore.resetForTesting()` | Empties every crumbs buffer and restores the default masked names, including the auth header `MagicCrumbsIntegration.install()` added | | `EventDispatcher.instance.clear()` | Removes the model, cache, event, gate and query listeners, since the watchers cannot remove their own | | `MagicRouter.reset()` | A fresh router, unlocked, without the perf observer or the preview routes | | `Gate.manager.flush()` | Empties the gate result cache the gate enrichers read | ## Faking Interactions tapir's `PerfInteraction` has a private constructor, so a host test cannot open a real interaction without a perf session over the VM Service. Three static fields on `MagicPerfIntegration` decide what counts as one, and a test may replace them: | Field | Default reads | |:------|:--------------| | `zoneInteraction` | A `PerfInteraction` stored in the zone under `PerfInteraction.zoneKey` (`#tapir_interaction`) | | `interactionIdAt` | tapir's `perfInteractionAt(us)` | | `activeInteractionId` | tapir's `activeInteraction()` | `MagicPerfIntegration.resetForTesting()` puts all three back. ## Gotchas | Mistake | Fix | |:--------|:----| | Calling `MagicDevtools.installPre()` in a `testWidgets` case and restoring `debugPrint` in `tearDown`. | flutter_test checks its debug variables right after the test body, before `tearDown`; call `MagicDevtools.resetForTesting()` at the end of the body. | | Resetting `MagicCrumbsIntegration` and expecting its watchers gone. | The reset drops the guard only; clear `EventDispatcher.instance` too, or a reinstall records each event twice. | | Calling `MagicPerfIntegration.install()` twice across tests without `MagicRouter.reset()`. | The reset clears the observer flag, so the next install adds a second observer to the same router; reset the router as well. | | Asserting crumbs HTTP records while using `Http.fake()`. | The fake driver ignores interceptors; assert on the fake. | | Expecting `MagicCrumbsIntegration.resetForTesting()` to restore the masked header list. | It does not; `CrumbsStore.resetForTesting()` restores crumbs' defaults, and the next `install()` adds the auth header again. | ## Related Documentation - [Installation](https://anilcancakir.com/magic/docs/devtools/getting-started/installation.md): what each install call wires. - [Tapir Integration](https://anilcancakir.com/magic/docs/devtools/basics/tapir-integration.md): the enrichers the reset removes. - [Crumbs Integration](https://anilcancakir.com/magic/docs/devtools/basics/crumbs-integration.md): the watchers and the tapir bridge. - [Performance](https://anilcancakir.com/magic/docs/devtools/basics/performance.md): the perf pointers and the interaction links.